import { create } from "zustand";
import * as SecureStore from "expo-secure-store";
import { BRAND } from "./brand";
import { detectDeviceLanguageTag, setLocale } from "./i18n";

/**
 * Auth-state. Tokens lagras i SecureStore (spec §44: lokal känslig data skyddas).
 * Access-token hålls i minne; refresh-token endast i SecureStore.
 */

const ACCESS_KEY = `${BRAND.slug}_access`;
const REFRESH_KEY = `${BRAND.slug}_refresh`;
const LANGUAGE_KEY = `${BRAND.slug}_language`;

/** Spara + aktivera språk (anropas från profilens språkval och vid inloggning). */
export async function persistLanguageTag(languageTag: string): Promise<void> {
  await SecureStore.setItemAsync(LANGUAGE_KEY, languageTag);
  setLocale(languageTag);
}

export interface AuthUser {
  id: string;
  email: string;
  displayName: string;
  role: string;
}

interface AuthState {
  hydrated: boolean;
  accessToken: string | null;
  user: AuthUser | null;
  onboardingCompleted: boolean;
  hydrate: () => Promise<void>;
  setSession: (
    tokens: { accessToken: string; refreshToken: string },
    user: AuthUser | null,
  ) => Promise<void>;
  setAccessToken: (token: string) => void;
  setOnboardingCompleted: (done: boolean) => void;
  getRefreshToken: () => Promise<string | null>;
  logout: () => Promise<void>;
}

export const useAuth = create<AuthState>((set) => ({
  hydrated: false,
  accessToken: null,
  user: null,
  onboardingCompleted: true,

  hydrate: async () => {
    try {
      const accessToken = await SecureStore.getItemAsync(ACCESS_KEY);
      set({ accessToken: accessToken ?? null, hydrated: true });
      // Språk (D-031): sparat val vinner; annars enhetens språk (stött → det,
      // ostött → engelska). Spanjoren som laddar ner appen får spanska direkt.
      const savedTag = await SecureStore.getItemAsync(LANGUAGE_KEY);
      if (savedTag) {
        setLocale(savedTag);
      } else {
        const deviceTag = detectDeviceLanguageTag();
        if (deviceTag) setLocale(deviceTag);
      }
    } catch {
      set({ hydrated: true });
    }
  },

  setSession: async (tokens, user) => {
    await SecureStore.setItemAsync(ACCESS_KEY, tokens.accessToken);
    await SecureStore.setItemAsync(REFRESH_KEY, tokens.refreshToken);
    set({ accessToken: tokens.accessToken, user });
  },

  setAccessToken: (token) => {
    set({ accessToken: token });
    void SecureStore.setItemAsync(ACCESS_KEY, token);
  },

  setOnboardingCompleted: (done) => set({ onboardingCompleted: done }),

  getRefreshToken: () => SecureStore.getItemAsync(REFRESH_KEY),

  logout: async () => {
    await SecureStore.deleteItemAsync(ACCESS_KEY);
    await SecureStore.deleteItemAsync(REFRESH_KEY);
    set({ accessToken: null, user: null });
  },
}));
