import { madarApi, unwrap } from './madar-api.js';

async function load() {
    const [ref, gam, rew] = await Promise.all([
        madarApi.get('/referral/summary').catch(() => null),
        madarApi.get('/gamification/summary').catch(() => null),
        madarApi.get('/rewards').catch(() => null),
    ]);

    const r = ref ? unwrap(ref.data) : {};
    const g = gam ? unwrap(gam.data) : {};
    const w = rew ? unwrap(rew.data) : {};

    document.getElementById('reward-points').textContent = g.points ?? w.points ?? '—';
    document.getElementById('reward-streak').textContent = g.streak_days ?? '0';
    document.getElementById('reward-level').textContent = g.level ?? '1';
    const link = document.getElementById('referral-link');
    if (link && r.referral_code) {
        link.value = `${location.origin}/register?ref=${r.referral_code}`;
    }
}

document.getElementById('claim-daily')?.addEventListener('click', async () => {
    try {
        const { data } = await madarApi.post('/engagement/daily-reward/claim');
        alert(unwrap(data)?.message || 'تم استلام المكافأة');
        load();
    } catch (err) {
        alert(err.madarMessage || 'تعذر الاستلام');
    }
});

document.getElementById('copy-referral')?.addEventListener('click', () => {
    const el = document.getElementById('referral-link');
    el?.select();
    navigator.clipboard.writeText(el?.value || '');
});

load();
