/**
 *    Scheduler - جدولة الحملات
 */

const Scheduler = {
    scheduledCampaign: null,
    timeoutId: null,

    // ============================================================
    // جدولة حملة
    // ============================================================
    schedule(dateTime, campaignData, callback) {
        const now = new Date();
        const targetTime = new Date(dateTime);
        const delayMs = targetTime.getTime() - now.getTime();

        if (delayMs <= 0) {
            return { success: false, error: typeof t === 'function' ? t('error.timePassed', 'الوقت المحدد قد مضى') : 'الوقت المحدد قد مضى' };
        }

        // إلغاء أي جدولة سابقة
        this.cancel();

        // حفظ callback محلياً (لا في storage)
        this.scheduledCampaign = {
            dateTime: targetTime.toISOString(),
            campaignData: campaignData,
            callback: callback
        };

        // ضبط المؤقت
        this.timeoutId = setTimeout(() => {
            console.log('   الوقت المجدول! بدء الحملة...');
            if (this.scheduledCampaign && this.scheduledCampaign.callback) {
                this.scheduledCampaign.callback(this.scheduledCampaign.campaignData);
            }
            this.scheduledCampaign = null;
            // حذف من storage بعد التنفيذ
            chrome.storage.local.remove('scheduledCampaign');
        }, delayMs);

        // حفظ في storage (بدون callback - لا يمكن serialize)
        chrome.storage.local.set({
            scheduledCampaign: {
                dateTime: targetTime.toISOString(),
                campaignData: campaignData
            }
        });

        return {
            success: true,
            scheduledFor: targetTime.toLocaleString('ar-EG'),
            delayMs: delayMs
        };
    },

    // ============================================================
    // إلغاء الجدولة
    // ============================================================
    cancel() {
        if (this.timeoutId) {
            clearTimeout(this.timeoutId);
            this.timeoutId = null;
        }
        this.scheduledCampaign = null;
        chrome.storage.local.remove('scheduledCampaign');
        return { success: true };
    },

    // ============================================================
    // التحقق من وجود جدولة
    // ============================================================
    async getScheduled() {
        return new Promise((resolve) => {
            chrome.storage.local.get('scheduledCampaign', (data) => {
                if (data.scheduledCampaign) {
                    const scheduled = new Date(data.scheduledCampaign.dateTime);
                    if (scheduled > new Date()) {
                        resolve(data.scheduledCampaign);
                    } else {
                        // الوقت انتهى
                        this.cancel();
                        resolve(null);
                    }
                } else {
                    resolve(null);
                }
            });
        });
    },

    // ============================================================
    // استعادة الجدولة عند فتح الـ popup
    // ============================================================
    async restore(callback) {
        const scheduled = await this.getScheduled();
        if (scheduled) {
            const now = new Date();
            const targetTime = new Date(scheduled.dateTime);
            const delayMs = targetTime.getTime() - now.getTime();

            if (delayMs > 0) {
                this.scheduledCampaign = {
                    ...scheduled,
                    callback: callback
                };
                this.timeoutId = setTimeout(() => {
                    if (callback) callback(scheduled.campaignData);
                    this.cancel();
                }, delayMs);

                return {
                    active: true,
                    scheduledFor: targetTime.toLocaleString('ar-EG'),
                    remainingMs: delayMs
                };
            }
        }
        return { active: false };
    },

    // ============================================================
    // تنسيق الوقت المتبقي
    // ============================================================
    formatRemaining(ms) {
        const seconds = Math.floor(ms / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);

        if (hours > 0) {
            return `${hours} ${typeof t === 'function' ? t('time.hour', 'ساعة') : 'ساعة'} ${typeof t === 'function' ? t('time.and', 'و') : 'و'} ${minutes % 60} ${typeof t === 'function' ? t('time.minute', 'دقيقة') : 'دقيقة'}`;
        } else if (minutes > 0) {
            return `${minutes} ${typeof t === 'function' ? t('time.minute', 'دقيقة') : 'دقيقة'}`;
        } else {
            return `${seconds} ${typeof t === 'function' ? t('time.second', 'ثانية') : 'ثانية'}`;
        }
    }
};

// تصدير للاستخدام العالمي
window.Scheduler = Scheduler;
