// ==========================================
// DETAY - ADMIN PANEL SCRIPT
// ==========================================

// ---- Config ----
// Şifreyi değiştirmek için aşağıdaki değeri değiştirin
const ADMIN_PASSWORD = 'detay2026';

// ---- Available Icons ----
const AVAILABLE_ICONS = [
    { class: 'fab fa-spotify', name: 'Spotify' },
    { class: 'fab fa-instagram', name: 'Instagram' },
    { class: 'fab fa-youtube', name: 'YouTube' },
    { class: 'fab fa-soundcloud', name: 'SoundCloud' },
    { class: 'fab fa-x-twitter', name: 'X / Twitter' },
    { class: 'fab fa-tiktok', name: 'TikTok' },
    { class: 'fab fa-twitch', name: 'Twitch' },
    { class: 'fab fa-discord', name: 'Discord' },
    { class: 'fab fa-apple', name: 'Apple Music' },
    { class: 'fab fa-deezer', name: 'Deezer' },
    { class: 'fab fa-bandcamp', name: 'Bandcamp' },
    { class: 'fab fa-facebook', name: 'Facebook' },
    { class: 'fab fa-snapchat', name: 'Snapchat' },
    { class: 'fab fa-pinterest', name: 'Pinterest' },
    { class: 'fab fa-linkedin', name: 'LinkedIn' },
    { class: 'fab fa-github', name: 'GitHub' },
    { class: 'fab fa-telegram', name: 'Telegram' },
    { class: 'fab fa-whatsapp', name: 'WhatsApp' },
    { class: 'fab fa-threads', name: 'Threads' },
    { class: 'custom-kick', name: 'Kick' },
    { class: 'fab fa-patreon', name: 'Patreon' },
    { class: 'fas fa-globe', name: 'Website' },
    { class: 'fas fa-envelope', name: 'Email' },
    { class: 'fas fa-music', name: 'Müzik' },
    { class: 'fas fa-headphones', name: 'Kulaklık' },
    { class: 'fas fa-store', name: 'Mağaza' },
    { class: 'fas fa-link', name: 'Link' },
    { class: 'fas fa-star', name: 'Yıldız' },
    { class: 'fas fa-fire', name: 'Ateş' },
    { class: 'fas fa-heart', name: 'Kalp' },
];

// ---- State ----
let currentEditId = null;

// ---- Init ----
document.addEventListener('DOMContentLoaded', async () => {
    await loadAllData();
    checkSession();
    setupEventListeners();
    buildIconPickers();
    loadPositionSettings();
    loadGeneralSettings();
});

// ---- Session / Auth ----
function checkSession() {
    const session = sessionStorage.getItem('detay_admin_session');
    if (session === 'active') {
        showDashboard();
    } else {
        showLogin();
    }
}

function showLogin() {
    document.getElementById('loginScreen').classList.remove('hidden');
    document.getElementById('adminDashboard').classList.remove('active');
}

function showDashboard() {
    document.getElementById('loginScreen').classList.add('hidden');
    document.getElementById('adminDashboard').classList.add('active');
    sessionStorage.setItem('detay_admin_session', 'active');
    renderAdminLinks();
    updateStats();

    if (typeof getLastApiError === 'function' && getLastApiError()) {
        showApiError('API bağlantısı yok. Değişiklikler diğer cihazlara gitmez');
    }
}

function logout() {
    sessionStorage.removeItem('detay_admin_session');
    showLogin();
    document.getElementById('passwordInput').value = '';
}

// ---- Event Listeners ----
function setupEventListeners() {
    // Login
    document.getElementById('loginForm').addEventListener('submit', handleLogin);
    document.getElementById('loginBtn').addEventListener('click', handleLogin);

    // Logout
    document.getElementById('logoutBtn').addEventListener('click', logout);

    // Add Link
    document.getElementById('addBtn').addEventListener('click', handleAddLink);

    // Color sync
    document.getElementById('addColorPicker').addEventListener('input', (e) => {
        document.getElementById('addColor').value = e.target.value;
    });
    document.getElementById('addColor').addEventListener('input', (e) => {
        if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) {
            document.getElementById('addColorPicker').value = e.target.value;
        }
    });

    document.getElementById('editColorPicker').addEventListener('input', (e) => {
        document.getElementById('editColor').value = e.target.value;
    });
    document.getElementById('editColor').addEventListener('input', (e) => {
        if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) {
            document.getElementById('editColorPicker').value = e.target.value;
        }
    });

    // Modal
    document.getElementById('modalClose').addEventListener('click', closeEditModal);
    document.getElementById('modalCancel').addEventListener('click', closeEditModal);
    document.getElementById('modalSave').addEventListener('click', handleSaveEdit);
    document.getElementById('editModal').addEventListener('click', (e) => {
        if (e.target === document.getElementById('editModal')) closeEditModal();
    });

    // Close icon dropdowns on outside click
    document.addEventListener('click', (e) => {
        const addPicker = document.getElementById('addIconPicker');
        const editPicker = document.getElementById('editIconPicker');
        if (!addPicker.contains(e.target)) {
            document.getElementById('addIconDropdown').classList.remove('open');
        }
        if (!editPicker.contains(e.target)) {
            document.getElementById('editIconDropdown').classList.remove('open');
        }
    });

    // Icon picker triggers
    document.getElementById('addIconTrigger').addEventListener('click', () => {
        document.getElementById('addIconDropdown').classList.toggle('open');
    });
    document.getElementById('editIconTrigger').addEventListener('click', () => {
        document.getElementById('editIconDropdown').classList.toggle('open');
    });

    // Position Sliders
    const posSliders = document.querySelectorAll('.pos-slider');
    posSliders.forEach(slider => {
        slider.addEventListener('input', handlePositionChange);
    });

    // Device Tabs
    const deviceBtns = document.querySelectorAll('.device-btn');
    deviceBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            // Remove active from all
            deviceBtns.forEach(b => b.classList.remove('active'));
            // Add active to clicked
            const targetBtn = e.currentTarget;
            targetBtn.classList.add('active');
            
            // Switch mode
            currentDeviceMode = targetBtn.dataset.device;
            
            // Toggle preview class for mobile width
            const previewBox = document.getElementById('positionPreview');
            if(currentDeviceMode === 'mobile') {
                previewBox.classList.add('mobile');
            } else {
                previewBox.classList.remove('mobile');
            }
            
            loadPositionSettings();
        });
    });

    document.getElementById('savePositionBtn').addEventListener('click', savePositionSettings);
    document.getElementById('resetPositionBtn').addEventListener('click', resetPositionSettings);

    // General Settings
    document.getElementById('saveGeneralBtn').addEventListener('click', saveGeneralSettings);
}

// ---- Build Icon Pickers ----
function buildIconPickers() {
    buildIconGrid('addIconGrid', 'add');
    buildIconGrid('editIconGrid', 'edit');
}

function buildIconGrid(containerId, prefix) {
    const container = document.getElementById(containerId);
    container.innerHTML = AVAILABLE_ICONS.map(icon => `
        <div class="icon-option" data-icon="${icon.class}" title="${icon.name}" 
             onclick="selectIcon('${prefix}', '${icon.class}', '${icon.name}')">
            <i class="${icon.class}"></i>
        </div>
    `).join('');
}

function selectIcon(prefix, iconClass, iconName) {
    document.getElementById(`${prefix}Icon`).value = iconClass;
    document.getElementById(`${prefix}IconPreview`).className = 'selected-icon ' + iconClass;
    document.getElementById(`${prefix}IconText`).textContent = iconName;
    document.getElementById(`${prefix}IconDropdown`).classList.remove('open');

    // Highlight selected
    const grid = document.getElementById(`${prefix}IconGrid`);
    grid.querySelectorAll('.icon-option').forEach(opt => {
        opt.classList.toggle('selected', opt.dataset.icon === iconClass);
    });
}

// ---- Login Handler ----
function handleLogin(e) {
    e.preventDefault();
    const password = document.getElementById('passwordInput').value;

    if (password === ADMIN_PASSWORD) {
        showDashboard();
    } else {
        const error = document.getElementById('loginError');
        error.classList.add('show');
        setTimeout(() => error.classList.remove('show'), 3000);
    }
}

// ---- Add Link ----
async function handleAddLink() {
    const title = document.getElementById('addTitle').value.trim();
    const url = document.getElementById('addUrl').value.trim();
    const icon = document.getElementById('addIcon').value;
    const color = document.getElementById('addColor').value.trim();

    if (!title || !url) {
        showToast('Başlık ve URL alanları zorunludur!', 'error');
        return;
    }

    // URL validation
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        showToast('URL http:// veya https:// ile başlamalıdır!', 'error');
        return;
    }

    const links = getLinks();
    const newId = links.length > 0 ? Math.max(...links.map(l => l.id)) + 1 : 1;

    links.push({
        id: newId,
        title: title,
        url: url,
        icon: icon || 'fas fa-link',
        color: color || '#a855f7'
    });

    const success = await saveLinks(links);
    if (success) {
        renderAdminLinks();
        updateStats();

        // Clear form
        document.getElementById('addTitle').value = '';
        document.getElementById('addUrl').value = '';
        document.getElementById('addIcon').value = 'fab fa-spotify';
        document.getElementById('addColor').value = '#e63946';
        document.getElementById('addColorPicker').value = '#e63946';
        document.getElementById('addIconPreview').className = 'selected-icon fab fa-spotify';
        document.getElementById('addIconText').textContent = 'İkon seçin';

        showToast('Link başarıyla eklendi!', 'success');
    } else {
        showApiError('Link eklenirken hata oluştu');
    }
}

// ---- Render Admin Links ----
function renderAdminLinks() {
    const container = document.getElementById('linksList');
    const links = getLinks();

    if (!links || links.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <p>Henüz link eklenmemiş. Yukarıdan yeni link ekleyin.</p>
            </div>
        `;
        return;
    }

    container.innerHTML = links.map((link, index) => `
        <div class="admin-link-item" draggable="true" data-id="${link.id}" data-index="${index}">
            <div class="drag-handle"><i class="fas fa-grip-vertical"></i></div>
            <div class="admin-link-icon" style="color: ${escapeHtml(link.color)}">
                <i class="${escapeHtml(link.icon)}"></i>
            </div>
            <div class="admin-link-info">
                <div class="link-title">${escapeHtml(link.title)}</div>
                <div class="link-url">${escapeHtml(link.url)}</div>
            </div>
            <div class="admin-link-actions">
                <button class="action-btn edit" onclick="openEditModal(${link.id})" title="Düzenle">
                    <i class="fas fa-pen"></i>
                </button>
                <button class="action-btn delete" onclick="deleteLink(${link.id})" title="Sil">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `).join('');

    // Setup drag & drop
    setupDragDrop();
}

// ---- Update Stats ----
function updateStats() {
    const links = getLinks();
    document.getElementById('totalLinks').textContent = links.length;
    document.getElementById('activeLinks').textContent = links.length;
}

// ---- Delete Link ----
async function deleteLink(id) {
    if (!confirm('Bu linki silmek istediğinizden emin misiniz?')) return;

    let links = getLinks();
    links = links.filter(l => l.id !== id);
    
    const success = await saveLinks(links);
    if (success) {
        renderAdminLinks();
        updateStats();
        showToast('Link silindi!', 'success');
    } else {
        showApiError('Silinirken hata oluştu');
    }
}

// ---- Edit Modal ----
function openEditModal(id) {
    const links = getLinks();
    const link = links.find(l => l.id === id);
    if (!link) return;

    currentEditId = id;
    document.getElementById('editId').value = id;
    document.getElementById('editTitle').value = link.title;
    document.getElementById('editUrl').value = link.url;
    document.getElementById('editIcon').value = link.icon;
    document.getElementById('editColor').value = link.color;
    document.getElementById('editColorPicker').value = link.color;
    document.getElementById('editIconPreview').className = 'selected-icon ' + link.icon;

    // Find icon name
    const iconData = AVAILABLE_ICONS.find(i => i.class === link.icon);
    document.getElementById('editIconText').textContent = iconData ? iconData.name : link.icon;

    // Highlight selected icon
    const grid = document.getElementById('editIconGrid');
    grid.querySelectorAll('.icon-option').forEach(opt => {
        opt.classList.toggle('selected', opt.dataset.icon === link.icon);
    });

    document.getElementById('editModal').classList.add('active');
}

function closeEditModal() {
    document.getElementById('editModal').classList.remove('active');
    currentEditId = null;
}

async function handleSaveEdit() {
    const id = parseInt(document.getElementById('editId').value);
    const title = document.getElementById('editTitle').value.trim();
    const url = document.getElementById('editUrl').value.trim();
    const icon = document.getElementById('editIcon').value;
    const color = document.getElementById('editColor').value.trim();

    if (!title || !url) {
        showToast('Başlık ve URL zorunludur!', 'error');
        return;
    }

    const links = getLinks();
    const index = links.findIndex(l => l.id === id);
    if (index === -1) return;

    links[index] = { ...links[index], title, url, icon, color };
    
    const success = await saveLinks(links);
    if (success) {
        renderAdminLinks();
        closeEditModal();
        showToast('Link güncellendi!', 'success');
    } else {
        showApiError('Güncellenirken hata oluştu');
    }
}

// ---- Drag & Drop ----
function setupDragDrop() {
    const list = document.getElementById('linksList');
    const items = list.querySelectorAll('.admin-link-item');
    let dragItem = null;

    items.forEach(item => {
        item.addEventListener('dragstart', (e) => {
            dragItem = item;
            item.classList.add('dragging');
            e.dataTransfer.effectAllowed = 'move';
        });

        item.addEventListener('dragend', () => {
            item.classList.remove('dragging');
            dragItem = null;
            // Save new order
            saveNewOrder();
        });

        item.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            const rect = item.getBoundingClientRect();
            const midY = rect.top + rect.height / 2;
            if (e.clientY < midY) {
                list.insertBefore(dragItem, item);
            } else {
                list.insertBefore(dragItem, item.nextSibling);
            }
        });
    });
}

async function saveNewOrder() {
    const items = document.querySelectorAll('.admin-link-item');
    const links = getLinks();
    const newOrder = [];

    items.forEach(item => {
        const id = parseInt(item.dataset.id);
        const link = links.find(l => l.id === id);
        if (link) newOrder.push(link);
    });

    const success = await saveLinks(newOrder);
    if (success) {
        showToast('Sıralama güncellendi!', 'success');
    } else {
        showApiError('Sıralama kaydedilemedi');
    }
}

// ---- Toast Notifications ----
function showToast(message, type = 'success') {
    // Remove existing toasts
    document.querySelectorAll('.toast').forEach(t => t.remove());

    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
        ${message}
    `;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('hide');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}


function showApiError(defaultMessage) {
    const err = typeof getLastApiError === 'function' ? getLastApiError() : null;
    const detail = err && err.message ? ` (${err.message})` : '';
    showToast(defaultMessage + detail, 'error');
}

// ---- HTML Escape Helper ----
function escapeHtml(str) {
    if (!str) return '';
    const div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

// ==========================================
// POSITION SETTINGS (Character & Hoverboard)
// ==========================================
let currentDeviceMode = 'desktop';

function getFullPositionSettings() {
    return getPositionSettings();
}

function loadPositionSettings() {
    const allPos = getFullPositionSettings();
    const pos = allPos[currentDeviceMode] || {};
    
    document.getElementById('charOffsetX').value = pos.charOffsetX !== undefined ? pos.charOffsetX : 0;
    document.getElementById('charOffsetY').value = pos.charOffsetY !== undefined ? pos.charOffsetY : 0;
    document.getElementById('charScale').value = pos.charScale !== undefined ? Math.round(pos.charScale * 100) : 100;
    document.getElementById('boardOffsetX').value = pos.boardOffsetX !== undefined ? pos.boardOffsetX : 0;
    document.getElementById('boardOffsetY').value = pos.boardOffsetY !== undefined ? pos.boardOffsetY : 0;
    document.getElementById('boardScale').value = pos.boardScale !== undefined ? Math.round(pos.boardScale * 100) : 100;
    document.getElementById('wardrobePanelOffsetX').value = pos.wardrobePanelOffsetX !== undefined ? pos.wardrobePanelOffsetX : 0;
    document.getElementById('wardrobePanelOffsetY').value = pos.wardrobePanelOffsetY !== undefined ? pos.wardrobePanelOffsetY : 0;
    document.getElementById('wardrobePanelScale').value = pos.wardrobePanelScale !== undefined ? Math.round(pos.wardrobePanelScale * 100) : 100;
    document.getElementById('wardrobeToggleOffsetX').value = pos.wardrobeToggleOffsetX !== undefined ? pos.wardrobeToggleOffsetX : 0;
    document.getElementById('wardrobeToggleOffsetY').value = pos.wardrobeToggleOffsetY !== undefined ? pos.wardrobeToggleOffsetY : 0;
    
    updatePositionPreview();
}

function handlePositionChange() {
    updatePositionPreview();
}

function updatePositionPreview() {
    // Read values
    const charX = parseInt(document.getElementById('charOffsetX').value);
    const charY = parseInt(document.getElementById('charOffsetY').value);
    const charScaleVal = parseInt(document.getElementById('charScale').value);
    const charScale = charScaleVal / 100;
    const boardX = parseInt(document.getElementById('boardOffsetX').value);
    const boardY = parseInt(document.getElementById('boardOffsetY').value);
    const boardScaleVal = parseInt(document.getElementById('boardScale').value);
    const boardScale = boardScaleVal / 100;
    const wardrobePanelX = parseInt(document.getElementById('wardrobePanelOffsetX').value);
    const wardrobePanelY = parseInt(document.getElementById('wardrobePanelOffsetY').value);
    const wardrobePanelScaleVal = parseInt(document.getElementById('wardrobePanelScale').value);
    const wardrobePanelScale = wardrobePanelScaleVal / 100;
    const wardrobeToggleX = parseInt(document.getElementById('wardrobeToggleOffsetX').value);
    const wardrobeToggleY = parseInt(document.getElementById('wardrobeToggleOffsetY').value);

    // Update labels
    document.getElementById('charXValue').textContent = charX;
    document.getElementById('charYValue').textContent = charY;
    document.getElementById('charScaleValue').textContent = charScale.toFixed(2);
    document.getElementById('boardXValue').textContent = boardX;
    document.getElementById('boardYValue').textContent = boardY;
    document.getElementById('boardScaleValue').textContent = boardScale.toFixed(2);
    document.getElementById('wardrobePanelXValue').textContent = wardrobePanelX;
    document.getElementById('wardrobePanelYValue').textContent = wardrobePanelY;
    document.getElementById('wardrobePanelScaleValue').textContent = wardrobePanelScale.toFixed(2);
    document.getElementById('wardrobeToggleXValue').textContent = wardrobeToggleX;
    document.getElementById('wardrobeToggleYValue').textContent = wardrobeToggleY;

    // Update Preview visual
    const charPreview = document.getElementById('previewCharacter');
    const boardPreview = document.getElementById('previewHoverboard');
    const wardrobePanelPreview = document.getElementById('previewWardrobePanel');
    const wardrobeTogglePreview = document.getElementById('previewWardrobeToggle');

    if (charPreview) {
        charPreview.style.transform = `translate(${charX}px, ${charY}px) scale(${charScale})`;
    }
    
    if (boardPreview) {
        boardPreview.style.transform = `translate(${boardX}px, ${boardY}px) scale(${boardScale})`;
    }

    if (wardrobePanelPreview) {
        wardrobePanelPreview.style.transform = `translate(${wardrobePanelX}px, ${wardrobePanelY}px) scale(${wardrobePanelScale})`;
    }

    if (wardrobeTogglePreview) {
        wardrobeTogglePreview.style.transform = `translate(${wardrobeToggleX}px, ${wardrobeToggleY}px)`;
    }
}

async function savePositionSettings() {
    const charX = parseInt(document.getElementById('charOffsetX').value);
    const charY = parseInt(document.getElementById('charOffsetY').value);
    const charScaleVal = parseInt(document.getElementById('charScale').value);
    const charScale = charScaleVal / 100;
    const boardX = parseInt(document.getElementById('boardOffsetX').value);
    const boardY = parseInt(document.getElementById('boardOffsetY').value);
    const boardScaleVal = parseInt(document.getElementById('boardScale').value);
    const boardScale = boardScaleVal / 100;
    const wardrobePanelX = parseInt(document.getElementById('wardrobePanelOffsetX').value);
    const wardrobePanelY = parseInt(document.getElementById('wardrobePanelOffsetY').value);
    const wardrobePanelScaleVal = parseInt(document.getElementById('wardrobePanelScale').value);
    const wardrobePanelScale = wardrobePanelScaleVal / 100;
    const wardrobeToggleX = parseInt(document.getElementById('wardrobeToggleOffsetX').value);
    const wardrobeToggleY = parseInt(document.getElementById('wardrobeToggleOffsetY').value);

    const allPos = getFullPositionSettings();
    allPos[currentDeviceMode] = {
        charOffsetX: charX,
        charOffsetY: charY,
        charScale: charScale,
        boardOffsetX: boardX,
        boardOffsetY: boardY,
        boardScale: boardScale,
        wardrobePanelOffsetX: wardrobePanelX,
        wardrobePanelOffsetY: wardrobePanelY,
        wardrobePanelScale: wardrobePanelScale,
        wardrobeToggleOffsetX: wardrobeToggleX,
        wardrobeToggleOffsetY: wardrobeToggleY
    };

    const success = await savePositionSettingsData(allPos);
    if (success) {
        showToast(`${currentDeviceMode === 'mobile' ? 'Mobil' : 'Masaüstü'} ayarları kaydedildi!`, 'success');
    } else {
        showApiError('Konum kaydedilemedi');
    }
}

function resetPositionSettings() {
    document.getElementById('charOffsetX').value = 0;
    document.getElementById('charOffsetY').value = 0;
    document.getElementById('charScale').value = 100;
    document.getElementById('boardOffsetX').value = 0;
    document.getElementById('boardOffsetY').value = 0;
    document.getElementById('boardScale').value = 100;
    document.getElementById('wardrobePanelOffsetX').value = 0;
    document.getElementById('wardrobePanelOffsetY').value = 0;
    document.getElementById('wardrobePanelScale').value = 100;
    document.getElementById('wardrobeToggleOffsetX').value = 0;
    document.getElementById('wardrobeToggleOffsetY').value = 0;
    
    updatePositionPreview();
    
    // Optionally auto-save reset state
    savePositionSettings();
    showToast('Konum sıfırlandı!', 'success');
}

// ==========================================
// GENERAL SETTINGS
// ==========================================
function loadGeneralSettings() {
    const settings = getGeneralSettings();
    if (settings.subtitle) {
        document.getElementById('settingSubtitle').value = settings.subtitle;
    }
}

async function saveGeneralSettings() {
    const subtitle = document.getElementById('settingSubtitle').value.trim();
    
    const settings = {
        subtitle: subtitle || 'MÜZİSYEN'
    };
    
    const success = await saveGeneralSettingsData(settings);
    if (success) {
        showToast('Genel ayarlar kaydedildi!', 'success');
    } else {
        showApiError('Ayarlar kaydedilemedi');
    }
}
