// ==========================================
// DETAY - ALL LINKS - Main Script
// ==========================================

document.addEventListener('DOMContentLoaded', async () => {
    await loadAllData();
    renderLinks();
    createParticles();
    startTimestamp();
    applyPositionSettings();
    applyGeneralSettings();
    await initWardrobeSwitcher();
    window.addEventListener('resize', () => {
        applyPositionSettings();
        lockDefaultCharacterSize();
    });
});

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

    if (!container) return;

    if (!links || links.length === 0) {
        container.innerHTML = `
            <div class="no-links">
                <i class="fas fa-link"></i>
                <p>Henüz link eklenmemiş.</p>
            </div>
        `;
        return;
    }

    container.innerHTML = links.map((link, index) => `
        <a href="${escapeHtml(link.url)}" target="_blank" rel="noopener noreferrer" 
           class="link-item" style="animation-delay: ${0.6 + index * 0.08}s"
           id="link-${escapeHtml(String(link.id))}">
            <div class="link-icon" style="color: ${escapeHtml(link.color)};">
                <i class="${escapeHtml(link.icon || 'fas fa-link')}"></i>
            </div>
            <span class="link-text">${escapeHtml(link.title)}</span>
            <span class="link-arrow"><i class="fas fa-arrow-right"></i></span>
        </a>
    `).join('');
}

// ---- Camera Timestamp Counter ----
function startTimestamp() {
    const el = document.getElementById('camTimestamp');
    if (!el) return;

    let seconds = 0;
    setInterval(() => {
        seconds++;
        const h = String(Math.floor(seconds / 3600)).padStart(2, '0');
        const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
        const s = String(seconds % 60).padStart(2, '0');
        el.textContent = `${h}:${m}:${s}`;
    }, 1000);
}

function hasPositionValues(pos) {
    return !!pos && Object.keys(pos).some(key => pos[key] !== undefined && pos[key] !== null && pos[key] !== '');
}

// ---- Apply Position Settings from Admin ----
function applyPositionSettings() {
    const allPos = getPositionSettings() || { desktop: {}, mobile: {} };
    const isMobile = window.innerWidth <= 768;

    // Migration/fallback support:
    // 1) New format: { desktop: {...}, mobile: {...} }
    // 2) Old flat format: { charOffsetX: ..., boardOffsetY: ... }
    let desktopPos = allPos.desktop || {};
    let mobilePos = allPos.mobile || {};

    if (!allPos.desktop && !allPos.mobile) {
        desktopPos = allPos;
        mobilePos = {};
    }

    // If mobile was never configured, use desktop instead of silently ignoring admin changes.
    const pos = isMobile && hasPositionValues(mobilePos) ? mobilePos : desktopPos;

    const character = document.getElementById('characterContainer');
    const hoverboard = document.getElementById('hoverboardContainer');

    const charX = Number(pos.charOffsetX || 0);
    const charY = Number(pos.charOffsetY || 0);
    const charScale = pos.charScale !== undefined ? Number(pos.charScale) : 1;
    const boardX = Number(pos.boardOffsetX || 0);
    const boardY = Number(pos.boardOffsetY || 0);
    const boardScale = pos.boardScale !== undefined ? Number(pos.boardScale) : 1;
    const wardrobePanelX = Number(pos.wardrobePanelOffsetX || 0);
    const wardrobePanelY = Number(pos.wardrobePanelOffsetY || 0);
    const wardrobePanelScale = pos.wardrobePanelScale !== undefined ? Number(pos.wardrobePanelScale) : 1;
    const wardrobeToggleX = Number(pos.wardrobeToggleOffsetX || 0);
    const wardrobeToggleY = Number(pos.wardrobeToggleOffsetY || 0);

    // Always write the transform. Otherwise old inline transforms can survive resize/device switches.
    if (character) {
        character.style.setProperty('--character-offset-x', `${charX}px`);
        character.style.setProperty('--character-offset-y', `${charY}px`);
        character.style.setProperty('--character-scale', `${charScale}`);
        character.style.transform = `translate(${charX}px, ${charY}px) scale(${charScale})`;
    }

    if (hoverboard) {
        hoverboard.style.transform = `translate(${boardX}px, ${boardY}px) scale(${boardScale})`;
    }

    applyWardrobePositionSettings({
        wardrobePanelX,
        wardrobePanelY,
        wardrobePanelScale,
        wardrobeToggleX,
        wardrobeToggleY
    });
}

function applyWardrobePositionSettings(settings = {}) {
    const wardrobeShell = document.getElementById('wardrobeShell');
    if (!wardrobeShell) return;

    wardrobeShell.style.setProperty('--wardrobe-panel-offset-x', `${Number(settings.wardrobePanelX || 0)}px`);
    wardrobeShell.style.setProperty('--wardrobe-panel-offset-y', `${Number(settings.wardrobePanelY || 0)}px`);
    wardrobeShell.style.setProperty('--wardrobe-panel-scale', `${settings.wardrobePanelScale !== undefined ? Number(settings.wardrobePanelScale) : 1}`);
    wardrobeShell.style.setProperty('--wardrobe-toggle-offset-x', `${Number(settings.wardrobeToggleX || 0)}px`);
    wardrobeShell.style.setProperty('--wardrobe-toggle-offset-y', `${Number(settings.wardrobeToggleY || 0)}px`);
}

// ---- Create Floating Particles ----
function createParticles() {
    const container = document.getElementById('particles');
    if (!container) return;

    const count = 25;

    for (let i = 0; i < count; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        particle.style.left = Math.random() * 100 + '%';
        particle.style.animationDuration = (10 + Math.random() * 18) + 's';
        particle.style.animationDelay = (Math.random() * 12) + 's';
        
        const size = (1 + Math.random() * 2) + 'px';
        particle.style.width = size;
        particle.style.height = size;
        
        const colors = [
            'rgba(230, 57, 70, 0.3)',
            'rgba(193, 18, 31, 0.2)',
            'rgba(255, 255, 255, 0.1)',
            'rgba(255, 77, 90, 0.2)'
        ];
        particle.style.background = colors[Math.floor(Math.random() * colors.length)];
        
        container.appendChild(particle);
    }
}

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

// ---- Apply General Settings ----
function applyGeneralSettings() {
    const settings = getGeneralSettings();
    if (settings.subtitle) {
        const subtitleEl = document.getElementById('subtitleText');
        if (subtitleEl) {
            subtitleEl.textContent = settings.subtitle;
        }
    }
}


// ---- Character Costume Switcher ----
const CHARACTER_COSTUMES = [
    { id: 'main', src: 'character-1.webp', thumb: 'thumb-1.webp', name: 'Detay', code: '01', role: 'ORIGINAL SIGNAL' },
    { id: 'duts', src: 'character-2.webp', thumb: 'thumb-2.webp', name: 'Duts', code: '02', role: 'BLACK SWORD' },
    { id: 'portgas-detay', src: 'character-3.webp', thumb: 'thumb-3.webp', name: 'Portgas Detay', code: '03', role: 'FLAME MODE' },
    { id: 'cyber-detay', src: 'character-4.webp', thumb: 'thumb-4.webp', name: 'Cyber Detay', code: '04', role: 'NIGHT CITY' },
    { id: 'dojo', src: 'character-5.webp', thumb: 'thumb-5.webp', name: 'Dojo', code: '05', role: 'LIMITLESS' },
    { id: 'detay-durden', src: 'character-6.webp', thumb: 'thumb-6.webp', name: 'Detay Durden', code: '06', role: 'RED JACKET' },
    { id: 'detay-auditore', src: 'character-7.webp', thumb: 'thumb-7.webp', name: 'Auditore da Firenze', code: '07', role: 'ASSASSIN PROTOCOL' },
    { id: 'detay-nightmares', src: 'character-8.webp', thumb: 'thumb-8.webp', name: 'Nightmares', code: '08', role: 'RAIN SIGNAL' }
];

const COSTUME_STORAGE_KEY = 'detayhotline_selected_costume_v6';
const ASSET_VERSION = '20260711-look-archive';
const DEFAULT_CHARACTER_WIDTH_DESKTOP = 210;
const DEFAULT_CHARACTER_WIDTH_MOBILE = 148;
const costumeImageCache = new Map();

let activeCostumeId = CHARACTER_COSTUMES[0].id;
let activeCharacterLayerIndex = 0;
let wardrobeOpen = false;
let costumeRequestId = 0;

function costumeUrl(costume) {
    return `${costume.src}?v=${ASSET_VERSION}`;
}

function getCostumeById(id) {
    return CHARACTER_COSTUMES.find(costume => costume.id === id) || CHARACTER_COSTUMES[0];
}

function preloadCostume(costume) {
    if (costumeImageCache.has(costume.id)) return costumeImageCache.get(costume.id);

    const request = new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = async () => {
            try {
                if (image.decode) await image.decode();
            } catch (_) {}
            resolve(image);
        };
        image.onerror = reject;
        image.src = costumeUrl(costume);
    });

    costumeImageCache.set(costume.id, request);
    return request;
}

async function initWardrobeSwitcher() {
    const characterBox = document.getElementById('characterContainer');
    const optionsContainer = document.getElementById('wardrobeOptions');
    const wardrobeToggle = document.getElementById('wardrobeToggle');
    const wardrobeClose = document.getElementById('wardrobeClose');
    const wardrobeBackdrop = document.getElementById('wardrobeBackdrop');

    if (!characterBox || !optionsContainer) return;

    optionsContainer.innerHTML = CHARACTER_COSTUMES.map((costume, index) => `
        <button class="wardrobe-option" type="button" role="option" data-costume-id="${escapeHtml(costume.id)}" aria-selected="false" aria-label="${escapeHtml(costume.name)} kostümünü seç">
            <span class="wardrobe-option-code">${escapeHtml(costume.code)}</span>
            <span class="wardrobe-option-thumb">
                <img src="${escapeHtml(costume.thumb)}?v=${ASSET_VERSION}" alt="" loading="${index < 4 ? 'eager' : 'lazy'}" width="72" height="90">
            </span>
            <span class="wardrobe-option-text">
                <strong>${escapeHtml(costume.name)}</strong>
                <small>${escapeHtml(costume.role)}</small>
            </span>
            <span class="wardrobe-option-status"></span>
        </button>
    `).join('');

    optionsContainer.addEventListener('click', (event) => {
        const button = event.target.closest('.wardrobe-option');
        if (button) setActiveCostume(button.dataset.costumeId, true);
    });

    wardrobeToggle?.addEventListener('click', () => setWardrobeOpen(!wardrobeOpen));
    wardrobeClose?.addEventListener('click', () => setWardrobeOpen(false));
    wardrobeBackdrop?.addEventListener('click', () => setWardrobeOpen(false));
    document.getElementById('wardrobePrev')?.addEventListener('click', () => cycleCostume(-1));
    document.getElementById('wardrobeNext')?.addEventListener('click', () => cycleCostume(1));

    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && wardrobeOpen) setWardrobeOpen(false);
        if (!wardrobeOpen) return;
        if (event.key === 'ArrowLeft') cycleCostume(-1);
        if (event.key === 'ArrowRight') cycleCostume(1);
    });

    const savedCostume = getCostumeById(localStorage.getItem(COSTUME_STORAGE_KEY));
    await setActiveCostume(savedCostume.id, false, true);
    setWardrobeOpen(false);
    lockDefaultCharacterSize();

    // Önce komşu kostümleri, tarayıcı boş kaldığında da kalan arşivi hazırlar.
    const savedIndex = CHARACTER_COSTUMES.findIndex(item => item.id === savedCostume.id);
    [savedIndex - 1, savedIndex + 1].forEach(index => {
        preloadCostume(CHARACTER_COSTUMES[(index + CHARACTER_COSTUMES.length) % CHARACTER_COSTUMES.length]).catch(() => {});
    });
    const warmArchive = () => CHARACTER_COSTUMES.forEach(costume => preloadCostume(costume).catch(() => {}));
    if ('requestIdleCallback' in window) requestIdleCallback(warmArchive, { timeout: 2200 });
    else setTimeout(warmArchive, 900);
}

function cycleCostume(direction) {
    const currentIndex = CHARACTER_COSTUMES.findIndex(costume => costume.id === activeCostumeId);
    const nextIndex = ((currentIndex < 0 ? 0 : currentIndex) + direction + CHARACTER_COSTUMES.length) % CHARACTER_COSTUMES.length;
    setActiveCostume(CHARACTER_COSTUMES[nextIndex].id, true);
}

function setWardrobeOpen(isOpen) {
    wardrobeOpen = !!isOpen;
    const shell = document.getElementById('wardrobeShell');
    const panel = document.getElementById('wardrobePanel');
    const toggle = document.getElementById('wardrobeToggle');

    shell?.classList.toggle('open', wardrobeOpen);
    panel?.setAttribute('aria-hidden', wardrobeOpen ? 'false' : 'true');
    toggle?.setAttribute('aria-expanded', wardrobeOpen ? 'true' : 'false');
    document.body.classList.toggle('wardrobe-open', wardrobeOpen);

    if (wardrobeOpen) {
        requestAnimationFrame(() => document.querySelector('.wardrobe-option.active')?.scrollIntoView({ block: 'nearest', inline: 'center' }));
    }
}

function updateWardrobeMeta(costume) {
    const values = {
        wardrobeSelectedName: costume.name,
        wardrobeSelectedNameMini: costume.name,
        wardrobeSelectedNameRight: costume.name,
        wardrobeSelectedCode: `LOOK ${costume.code} / ${String(CHARACTER_COSTUMES.length).padStart(2, '0')}`,
        wardrobeSelectedRole: costume.role,
        wardrobeSelectedRoleRight: costume.role
    };

    Object.entries(values).forEach(([id, value]) => {
        const element = document.getElementById(id);
        if (element) element.textContent = value;
    });

    const previewImage = document.getElementById('wardrobePreviewImg');
    if (previewImage) {
        previewImage.src = costumeUrl(costume);
        previewImage.alt = `${costume.name} önizleme`;
    }

    document.querySelectorAll('.wardrobe-option').forEach(button => {
        const active = button.dataset.costumeId === costume.id;
        button.classList.toggle('active', active);
        button.setAttribute('aria-selected', active ? 'true' : 'false');
        if (active && wardrobeOpen) button.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    });
}

async function setActiveCostume(costumeId, remember, instant = false) {
    const costume = getCostumeById(costumeId);
    const characterBox = document.getElementById('characterContainer');
    const layers = Array.from(document.querySelectorAll('.character-layer'));
    if (!characterBox || layers.length < 2) return;

    activeCostumeId = costume.id;
    updateWardrobeMeta(costume);
    if (remember) localStorage.setItem(COSTUME_STORAGE_KEY, costume.id);

    const requestId = ++costumeRequestId;
    characterBox.classList.add('is-loading');

    try {
        await preloadCostume(costume);
        if (requestId !== costumeRequestId) return;

        const currentLayer = layers[activeCharacterLayerIndex];
        const nextLayerIndex = activeCharacterLayerIndex === 0 ? 1 : 0;
        const nextLayer = layers[nextLayerIndex];
        nextLayer.src = costumeUrl(costume);
        nextLayer.alt = `Detay Character - ${costume.name}`;
        nextLayer.setAttribute('aria-hidden', 'false');

        if (nextLayer.decode) {
            try { await nextLayer.decode(); } catch (_) {}
        }
        if (requestId !== costumeRequestId) return;

        if (instant) {
            currentLayer.classList.remove('is-active');
            nextLayer.classList.add('is-active');
        } else {
            characterBox.classList.add('costume-changing');
            nextLayer.classList.add('is-entering');
            void nextLayer.offsetWidth;
            currentLayer.classList.remove('is-active');
            currentLayer.classList.add('is-exiting');
            nextLayer.classList.remove('is-entering');
            nextLayer.classList.add('is-active');
            setTimeout(() => currentLayer.classList.remove('is-exiting'), 420);
        }

        currentLayer.setAttribute('aria-hidden', 'true');
        activeCharacterLayerIndex = nextLayerIndex;
        lockDefaultCharacterSize();
    } catch (error) {
        console.error('Kostüm görseli yüklenemedi:', error);
    } finally {
        if (requestId === costumeRequestId) {
            setTimeout(() => characterBox.classList.remove('is-loading', 'costume-changing'), instant ? 0 : 430);
        }
    }
}

function lockDefaultCharacterSize() {
    const characterBox = document.getElementById('characterContainer');
    if (!characterBox) return;
    const width = window.innerWidth <= 480 ? DEFAULT_CHARACTER_WIDTH_MOBILE : DEFAULT_CHARACTER_WIDTH_DESKTOP;
    characterBox.style.setProperty('--character-img-width', `${width}px`);
}

// ===== DETAYHOTLINE Console Message =====
(() => {
    console.clear();

    console.log(
        '%cDETAY HOTLINE',
        `
        font-size: 42px;
        font-weight: 900;
        color: #ff0000;
        text-shadow: 0 0 18px rgba(255,0,0,.6);
        letter-spacing: 3px;
        `
    );

    console.log(
        '%cBuraya kadar geldiysen, sadece dinleyici değilsin.',
        `
        font-size: 16px;
        font-weight: 700;
        color: #ffffff;
        padding: 8px 0;
        `
    );

    console.log(
        '%cBazen bir şarkı, biriyle konuşmanın başka bir yoludur.',
        `
        font-size: 14px;
        color: #bbbbbb;
        font-style: italic;
        `
    );

    console.log(
        '%cBen buradayım. Sen de buradasın. Sinyal alındı.',
        `
        font-size: 15px;
        font-weight: 700;
        color: #ff3333;
        letter-spacing: 1px;
        `
    );

    console.log(
        '%cdetayhotline.info // transmission open',
        `
        font-size: 11px;
        color: #777;
        letter-spacing: 2px;
        `
    );
})();
