// ==========================================
// DETAY - API HANDLER
// Server-first data store. Admin changes are saved to data.json via api.php.
// ==========================================

const API_URL = 'api.php';
const DATA_CACHE_VERSION = '20260711-look-archive';

const DEFAULT_APP_DATA = {
    links: [
        { id: 1, title: 'Kick', url: 'https://kick.com/detayhotline', icon: 'custom-kick', color: '#53FC18' },
        { id: 2, title: 'Instagram', url: 'https://instagram.com/detayhotline', icon: 'fab fa-instagram', color: '#E4405F' },
        { id: 3, title: 'YouTube', url: 'https://youtube.com', icon: 'fab fa-youtube', color: '#FF0000' },
        { id: 4, title: 'Spotify', url: 'https://spotify.com', icon: 'fab fa-spotify', color: '#1DB954' }
    ],
    position: { desktop: {}, mobile: {} },
    general: { subtitle: 'MÜZİSYEN' }
};

// ---- Unified Data Store ----
let appData = structuredCloneSafe(DEFAULT_APP_DATA);
let lastApiError = null;

function structuredCloneSafe(obj) {
    return JSON.parse(JSON.stringify(obj));
}

function buildApiUrl(params = {}) {
    const url = new URL(API_URL, window.location.href);
    Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));

    // Prevent browser/CDN cache from serving old data.json/API responses.
    url.searchParams.set('_v', `${DATA_CACHE_VERSION}-${Date.now()}`);
    return url.toString();
}

function normalizePosition(position = {}) {
    // Supports the old flat format: { charOffsetX, boardOffsetX, ... }
    const hasDeviceShape = position && (position.desktop || position.mobile);

    if (!hasDeviceShape) {
        return {
            desktop: position && typeof position === 'object' ? position : {},
            mobile: {}
        };
    }

    return {
        desktop: position.desktop && typeof position.desktop === 'object' ? position.desktop : {},
        mobile: position.mobile && typeof position.mobile === 'object' ? position.mobile : {}
    };
}

function normalizeData(data) {
    const safeData = data && typeof data === 'object' ? data : {};
    const defaults = structuredCloneSafe(DEFAULT_APP_DATA);

    return {
        links: Array.isArray(safeData.links) ? safeData.links : defaults.links,
        position: normalizePosition(safeData.position || defaults.position),
        general: {
            ...defaults.general,
            ...(safeData.general && typeof safeData.general === 'object' ? safeData.general : {})
        }
    };
}

// Fetch all data from server
async function loadAllData() {
    lastApiError = null;

    try {
        const response = await fetch(buildApiUrl({ type: 'all' }), {
            method: 'GET',
            cache: 'no-store',
            headers: { 'Accept': 'application/json' }
        });

        if (!response.ok) {
            throw new Error(`API cevap vermedi: HTTP ${response.status}`);
        }

        const data = await response.json();
        appData = normalizeData(data);
        return true;
    } catch (e) {
        lastApiError = e;
        // Statik önizleme/CDN ortamlarında PHP çalışmayabilir. Bu durumda
        // aynı ayarları salt okunur data.json dosyasından yüklemeye devam et.
        try {
            const fallbackResponse = await fetch(`data.json?_v=${DATA_CACHE_VERSION}-${Date.now()}`, {
                cache: 'no-store',
                headers: { 'Accept': 'application/json' }
            });
            if (!fallbackResponse.ok) throw new Error(`data.json HTTP ${fallbackResponse.status}`);
            appData = normalizeData(await fallbackResponse.json());
            console.info('Statik veri modu aktif.');
            return true;
        } catch (fallbackError) {
            console.error('Site verileri yüklenemedi. Varsayılan veri kullanılıyor:', fallbackError);
            appData = normalizeData(appData);
            return false;
        }
    }
}

function getLastApiError() {
    return lastApiError;
}

// ---- Links API ----
function getLinks() {
    return appData.links || [];
}

async function saveLinks(links) {
    const success = await saveToServer('links', links);
    if (success) appData.links = links;
    return success;
}

// ---- Position API ----
function getPositionSettings() {
    return appData.position || { desktop: {}, mobile: {} };
}

async function savePositionSettingsData(posData) {
    const normalized = normalizePosition(posData);
    const success = await saveToServer('position', normalized);
    if (success) appData.position = normalized;
    return success;
}

// ---- General Settings API ----
function getGeneralSettings() {
    return appData.general || { subtitle: 'MÜZİSYEN' };
}

async function saveGeneralSettingsData(genData) {
    const merged = { ...DEFAULT_APP_DATA.general, ...(genData || {}) };
    const success = await saveToServer('general', merged);
    if (success) appData.general = merged;
    return success;
}

// ---- Internal Save Utility ----
async function saveToServer(type, data) {
    lastApiError = null;

    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            cache: 'no-store',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ type, data })
        });

        let result = null;
        try {
            result = await response.json();
        } catch (_) {
            throw new Error('API JSON cevap döndürmedi. PHP çalışmıyor veya sunucu statik olabilir.');
        }

        if (!response.ok || !result.success) {
            throw new Error(result.error || `Kaydetme başarısız: HTTP ${response.status}`);
        }

        return true;
    } catch (e) {
        lastApiError = e;
        console.error('API kaydetme hatası:', e);
        return false;
    }
}
