import { initializeApp, getApps, getApp } from "firebase/app";
import {
  initializeAuth,
  getAuth,
  onAuthStateChanged as fbOnAuthStateChanged,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  signOut as fbSignOut,
  sendPasswordResetEmail,
  type Auth,
  type User,
  type Persistence,
} from "firebase/auth";
import * as fbAuth from "firebase/auth";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Platform } from "react-native";
import type { AuthProvider, AuthUser, Unsubscribe } from "./types";

/**
 * ENDA mobilfilen som importerar Firebase. App-koden använder bara
 * AuthProvider-gränssnittet. Byt till Zitadel => byt bara denna fil.
 * Publik klient-config (identifierare, ingen hemlighet).
 */
const firebaseConfig = {
  apiKey: "AIzaSyAH2F-aZRvZXQtGD7X8cF9Zp3yXUhEl3sM",
  authDomain: "cibello-c2ff3.firebaseapp.com",
  projectId: "cibello-c2ff3",
  storageBucket: "cibello-c2ff3.firebasestorage.app",
  messagingSenderId: "1034102905039",
  appId: "1:1034102905039:web:12e31120989655f34affba",
};

const app = getApps().length ? getApp() : initializeApp(firebaseConfig);

// getReactNativePersistence finns i runtime men saknas ibland i typerna
// (firebase-js-sdk#9316) – hämtas därför via en typsäker modul-cast.
const getReactNativePersistence = (
  fbAuth as unknown as { getReactNativePersistence: (storage: unknown) => Persistence }
).getReactNativePersistence;

// Persistens så inloggningen överlever omstart. På webben (react-native-web)
// finns INTE getReactNativePersistence/AsyncStorage – att anropa dem kraschar
// hela appen vid start ("Cannot read properties of undefined (reading 'bind')").
// Där använder vi Firebases standard-webblagring (getAuth), på native AsyncStorage.
let auth: Auth;
try {
  auth =
    Platform.OS === "web"
      ? getAuth(app)
      : initializeAuth(app, { persistence: getReactNativePersistence(AsyncStorage) });
} catch {
  // initializeAuth kastar om den redan körts (Fast Refresh) – återanvänd instansen.
  auth = getAuth(app);
}

function toAuthUser(u: User | null): AuthUser | null {
  if (!u) return null;
  return {
    uid: u.uid,
    email: u.email,
    emailVerified: u.emailVerified,
    displayName: u.displayName,
    providerId: u.providerData[0]?.providerId ?? null,
  };
}

export const firebaseAuthProvider: AuthProvider = {
  async signUpWithEmail(email, password) {
    const cred = await createUserWithEmailAndPassword(auth, email, password);
    return toAuthUser(cred.user)!;
  },
  async signInWithEmail(email, password) {
    const cred = await signInWithEmailAndPassword(auth, email, password);
    return toAuthUser(cred.user)!;
  },
  async signInWithGoogle(): Promise<AuthUser> {
    throw new Error("Google-inloggning läggs till i AUTH-6."); // i18n-ignore (temporär dev-stub)
  },
  async signInWithApple(): Promise<AuthUser> {
    throw new Error("Apple-inloggning läggs till i AUTH-6."); // i18n-ignore (temporär dev-stub)
  },
  async signOut() {
    await fbSignOut(auth);
  },
  async sendPasswordReset(email) {
    await sendPasswordResetEmail(auth, email);
  },
  currentUser() {
    return toAuthUser(auth.currentUser);
  },
  onAuthStateChanged(callback): Unsubscribe {
    return fbOnAuthStateChanged(auth, (u) => callback(toAuthUser(u)));
  },
  async getIdToken(forceRefresh = false) {
    const u = auth.currentUser;
    if (!u) return null;
    return u.getIdToken(forceRefresh);
  },
};
