/**
 * lib/facebook-ads-storage.ts
 * ---------------------------
 * Shared localStorage helpers for Facebook Ads cache.
 * Used by both FacebookAdsPanel.tsx and UbaidiAdsMarketer.tsx
 * so data flows seamlessly between components.
 */

export const LS_CACHE    = 'fb_ads_summary_cache';
export const LS_RATE     = 'fb_exchange_rate';
export const LS_TOKEN    = 'fb_ads_token';
export const LS_ACCOUNT  = 'fb_ads_account';

export interface AdsCache {
    spend_usd:   number;
    spend_bdt:   number;
    purchases:   number;
    roas:        number;
    clicks:      number;
    impressions: number;
    ctr:         number;
    cpc:         number;
    rate?:       number;
    preset?:     string;
    updatedAt?:  number;
}

/** Read cached ads data from localStorage */
export function readAdsCache(): AdsCache | null {
    try {
        const raw = localStorage.getItem(LS_CACHE);
        if (!raw) return null;
        const parsed: AdsCache = JSON.parse(raw);
        const rate = parseFloat(localStorage.getItem(LS_RATE) || '0');
        if (rate > 0) parsed.rate = rate;
        return parsed;
    } catch {
        return null;
    }
}

/** Write/update ads cache and fire a cross-component event */
export function writeAdsCache(data: AdsCache): void {
    try {
        data.updatedAt = Date.now();
        localStorage.setItem(LS_CACHE, JSON.stringify(data));
        if (data.rate) localStorage.setItem(LS_RATE, String(data.rate));
        // Notify UbaidiAdsMarketer that new data is available
        window.dispatchEvent(new Event('fb_ads_cache_updated'));
    } catch (e) {
        console.error('[AdsStorage] Failed to write cache:', e);
    }
}

/** Clear cached data */
export function clearAdsCache(): void {
    localStorage.removeItem(LS_CACHE);
    window.dispatchEvent(new Event('fb_ads_cache_updated'));
}

/** Save token and account ID for auto-reconnect */
export function saveCredentials(token: string, account: string): void {
    try {
        localStorage.setItem(LS_TOKEN,   token);
        localStorage.setItem(LS_ACCOUNT, account);
    } catch { /* ignore */ }
}

/** Load saved credentials */
export function loadCredentials(): { token: string; account: string } {
    return {
        token:   localStorage.getItem(LS_TOKEN)   || '',
        account: localStorage.getItem(LS_ACCOUNT) || '',
    };
}

/** Format "updated N minutes ago" string */
export function updatedAgoLabel(updatedAt?: number): string | null {
    if (!updatedAt) return null;
    const mins = Math.floor((Date.now() - updatedAt) / 60000);
    if (mins < 1)  return 'এইমাত্র';
    if (mins < 60) return `${mins} মিনিট আগে`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24)  return `${hrs} ঘণ্টা আগে`;
    return `${Math.floor(hrs / 24)} দিন আগে`;
}
