import { writable } from 'svelte/store';
import { supabase } from '../supabase.js';
import { getEmailForUsername, updateProfile } from '../api/profile.js';

function createAuthStore() {
  const { subscribe, set, update } = writable({
    user: null,
    loading: true,
    error: null,
  });

  function setSession(session) {
    const user = session?.user ?? null;
    set({
      user,
      loading: false,
      error: null,
    });
  }

  return {
    subscribe,
    init: async () => {
      try {
        const { data: { session } } = await supabase.auth.getSession();
        setSession(session);
      } catch (e) {
        set({ user: null, loading: false, error: e?.message ?? 'Auth error' });
      }
      supabase.auth.onAuthStateChange(async (_event, session) => {
        if (session != null) {
          setSession(session);
          return;
        }
        const { data: { session: current } } = await supabase.auth.getSession();
        setSession(current);
      });
    },
    login: async (emailOrUsername, password) => {
      update((s) => ({ ...s, error: null }));
      let email = (emailOrUsername ?? '').trim();
      if (!email) {
        update((s) => ({ ...s, error: 'Enter your email or username.' }));
        return false;
      }
      if (!email.includes('@')) {
        const resolved = await getEmailForUsername(supabase, email);
        if (!resolved) {
          update((s) => ({ ...s, error: 'No account with that username.' }));
          return false;
        }
        email = resolved;
      }
      try {
        const { error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) {
          update((s) => ({ ...s, error: error.message }));
          return false;
        }
        update((s) => ({ ...s, error: null }));
        return true;
      } catch (e) {
        update((s) => ({ ...s, error: e?.message ?? 'Login failed' }));
        return false;
      }
    },
    register: async (email, password, displayName) => {
      update((s) => ({ ...s, error: null }));
      try {
        const { data, error } = await supabase.auth.signUp({
          email,
          password,
          options: { data: { display_name: (displayName || '').trim() || null } },
        });
        if (error) {
          update((s) => ({ ...s, error: error.message }));
          return { success: false };
        }
        update((s) => ({ ...s, error: null }));
        if (data?.user?.id && data?.session && (displayName || '').trim()) {
          try {
            await updateProfile(supabase, data.user.id, { display_name: (displayName || '').trim() });
          } catch (_) {}
        }
        const needsConfirmation = data?.user && !data?.session;
        return { success: true, needsConfirmation, data };
      } catch (e) {
        update((s) => ({ ...s, error: e?.message ?? 'Registration failed' }));
        return { success: false };
      }
    },
    logout: async () => {
      await supabase.auth.signOut();
      set({ user: null, loading: false, error: null });
    },
    clearError: () => update((s) => ({ ...s, error: null })),
  };
}

export const auth = createAuthStore();
