'use client';

// Auth store — tracks logged-in user, token, and storage mode preference.

import { create } from 'zustand';
import * as auth from '@/lib/api/auth-client';

export type StorageMode = 'auto' | 'local' | 'server';

interface AuthState {
  user: auth.User | null;
  loading: boolean;
  initialized: boolean;
  error: string | null;
  storageMode: StorageMode;
  setUser: (u: auth.User | null) => void;
  setStorageMode: (m: StorageMode) => void;
  setError: (e: string | null) => void;
  register: (username: string, password: string) => Promise<boolean>;
  login: (username: string, password: string) => Promise<boolean>;
  logout: () => Promise<void>;
  refresh: () => Promise<void>;
}

const STORAGE_MODE_KEY = 'capcut-storage-mode';

export const useAuth = create<AuthState>((set, get) => ({
  user: null,
  loading: false,
  initialized: false,
  error: null,
  storageMode:
    (typeof window !== 'undefined' &&
      (localStorage.getItem(STORAGE_MODE_KEY) as StorageMode | null)) ||
    'auto',

  setUser: (u) => set({ user: u }),
  setStorageMode: (m) => {
    if (typeof window !== 'undefined') localStorage.setItem(STORAGE_MODE_KEY, m);
    set({ storageMode: m });
  },
  setError: (e) => set({ error: e }),

  async register(username, password) {
    set({ loading: true, error: null });
    try {
      const res = await auth.register(username, password);
      set({ user: res.user, loading: false });
      get().setStorageMode('server');
      return true;
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'สมัครไม่สำเร็จ';
      set({ error: msg, loading: false });
      return false;
    }
  },

  async login(username, password) {
    set({ loading: true, error: null });
    try {
      const res = await auth.login(username, password);
      set({ user: res.user, loading: false });
      get().setStorageMode('server');
      return true;
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'login ไม่สำเร็จ';
      set({ error: msg, loading: false });
      return false;
    }
  },

  async logout() {
    await auth.logout();
    set({ user: null });
    get().setStorageMode('local');
  },

  async refresh() {
    set({ loading: true });
    const u = await auth.me();
    set({ user: u, loading: false, initialized: true });
  },
}));
