import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'

const LOGTO_URL = import.meta.env.VITE_LOGTO_URL || 'https://logto-admin-bzlued1boxl3t8ewsyn99an9.187.77.227.172.sslip.io';
const APP_ID = import.meta.env.VITE_LOGTO_APP_ID || 'gpi-app-001';

const redirectUrl = `${window.location.origin}/auth/callback`;

function generateRandomString(length: number) {
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');
}

function storeState(state: string) {
  sessionStorage.setItem('logto_oauth_state', state);
}

export function login() {
  const state = generateRandomString(21);
  storeState(state);

  const params = new URLSearchParams({
    client_id: APP_ID,
    redirect_uri: redirectUrl,
    response_type: 'code',
    scope: 'openid profile email',
    state: state
  });

  window.location.href = `${LOGTO_URL}/oidc/auth?${params.toString()}`;
}

export function logout() {
  sessionStorage.removeItem('logto_token');
  sessionStorage.removeItem('logto_user');
  window.location.href = '/';
}

export function getToken() {
  return sessionStorage.getItem('logto_token');
}

export function getUser() {
  const user = sessionStorage.getItem('logto_user');
  return user ? JSON.parse(user) : null;
}

export function setUser(token: string, user: any) {
  sessionStorage.setItem('logto_token', token);
  sessionStorage.setItem('logto_user', JSON.stringify(user));
}

createRoot(document.getElementById('root')!).render(
  <App />
)
