import { App } from '@capacitor/app';
import { StatusBar, Style } from '@capacitor/status-bar';
import { SplashScreen } from '@capacitor/splash-screen';
import { Preferences } from '@capacitor/preferences';
import { Network } from '@capacitor/network';
import { Device } from '@capacitor/device';
import { Capacitor } from '@capacitor/core';

export const isNative = (): boolean => Capacitor.isNativePlatform();

export async function initBridge(): Promise<{ device: Awaited<ReturnType<typeof Device.getInfo>>; network: Awaited<ReturnType<typeof Network.getStatus>> } | void> {
    if (!isNative()) return;

    // Durum çubuğu stilini ayarla
    await StatusBar.setStyle({ style: Style.Dark });
    await StatusBar.setBackgroundColor({ color: '#0D0E12' });

    // Başlatma sonrası splash ekranını gizle
    setTimeout(() => SplashScreen.hide(), 1500);

    // Uygulama durumu değişikliklerini dinle
    App.addListener('appStateChange', ({ isActive }) => {
        if (isActive) {
            // Uygulamaya dönüldüğünde verileri yenile
            window.dispatchEvent(new CustomEvent('app:resume'));
        }
    });

    // Derin bağlantıları dinle
    App.addListener('appUrlOpen', async (event) => {
        // onoxpanel://accounts/123 → /admin/accounts/123 adresine yönlendir
        const url = new URL(event.url);
        const path = url.pathname + url.search;
        window.location.assign(path);
    });

    // Ağ durumu
    Network.addListener('networkStatusChange', (status) => {
        window.dispatchEvent(new CustomEvent('app:network', { detail: status }));
    });

    return {
        device: await Device.getInfo(),
        network: await Network.getStatus(),
    };
}

export async function persistAuth(token: string): Promise<void> {
    if (!isNative()) return;
    await Preferences.set({ key: 'onox_auth_token', value: token });
}

export async function readAuth(): Promise<string | null> {
    if (!isNative()) return null;
    const { value } = await Preferences.get({ key: 'onox_auth_token' });
    return value;
}

export async function clearAuth(): Promise<void> {
    if (!isNative()) return;
    await Preferences.remove({ key: 'onox_auth_token' });
}
