import {
  Injectable,
  computed,
  inject,
  signal
} from '@angular/core';

import { ElectronBridgeService } from '../../../core/platform/electron/electron-bridge.service';
import { ViewportService } from '../../../core/platform/viewport.service';
import {
  detectRuntimePlatform,
  isCapacitorNativeRuntime,
  shouldUseMobileAttachmentPicker,
  type RuntimePlatform
} from '../logic/platform-detection.rules';
import type { MobilePlatformSnapshot } from '../contracts/mobile.contracts';

/** Detects runtime shell and exposes mobile capability flags to Angular domains. */
@Injectable({ providedIn: 'root' })
export class MobilePlatformService {
  readonly runtime = computed(() => this.runtimeSignal());
  readonly isCapacitor = computed(() => this.runtimeSignal() === 'capacitor');
  readonly isNativeMobile = computed(() => this.isCapacitor());
  readonly shouldShowAttachmentButton = computed(() =>
    shouldUseMobileAttachmentPicker(this.runtimeSignal(), this.viewport.isMobile())
  );
  readonly snapshot = computed<MobilePlatformSnapshot>(() => ({
    runtime: this.runtimeSignal(),
    isNativeMobile: this.isCapacitor(),
    isCapacitor: this.isCapacitor()
  }));

  private readonly electronBridge = inject(ElectronBridgeService);
  private readonly viewport = inject(ViewportService);
  private readonly runtimeSignal = signal<RuntimePlatform>(
    detectRuntimePlatform({
      hasElectronApi: this.electronBridge.isAvailable,
      capacitorIsNative: isCapacitorNativeRuntime()
    })
  );

  /** Re-evaluate runtime detection after Capacitor bootstraps on device. */
  refreshRuntimeDetection(): void {
    this.runtimeSignal.set(
      detectRuntimePlatform({
        hasElectronApi: this.electronBridge.isAvailable,
        capacitorIsNative: isCapacitorNativeRuntime()
      })
    );
  }
}
