/* supabaseClient.jsx — 홈페이지/서브앱 공통 Supabase 부트스트랩
   index.html 에 supabase-js UMD CDN 이 먼저 로드돼야 한다. 그러면 전역
   window.supabase 가 존재하고 (createClient 등이 노출), 여기서 createClient 를
   호출해 단일 인스턴스를 window.SRIKI_SB 로 노출한다.

   게임앱(C:\dev\sriki\app/.env)과 같은 프로젝트(lrctdquopbjadqkfplvg)·같은
   publishable key 를 쓴다. publishable key 는 공개해도 안전한 anon 자리에
   해당하는 새 키 체계. RLS 가 실제 권한을 강제한다. */

(function bootstrap() {
  /* ⚠️ Defensive: this file is loaded as <script type="text/babel"> just like
     the other component files, so the supabase-js UMD must already be present.
     If it isn't, log a clear error and bail — buttons will fall back to direct
     redirect so the modal still works visibly. */
  if (typeof window === 'undefined') return;
  if (!window.supabase || !window.supabase.createClient) {
    console.error('[sriki] supabase-js not loaded. Did the CDN <script> fail?');
    return;
  }
  if (window.SRIKI_SB) return; // already initialised

  /* Same project that the game app uses. Publishable key = safe anon. */
  const URL  = 'https://lrctdquopbjadqkfplvg.supabase.co';
  const KEY  = 'sb_publishable_5TwfGSOJ-Z-PlyruSjlPvg_ocM9dyPk';

  window.SRIKI_SB = window.supabase.createClient(URL, KEY, {
    auth: {
      persistSession:    true,
      autoRefreshToken:  true,
      detectSessionInUrl: true, // OAuth callback parses tokens from the URL
    },
  });

  /* Helper: kick off OAuth with the chosen provider, sending the user to the
     correct subapp afterwards (parent or teacher). The subapp's index.html
     handles the session hash on arrival. */
  window.SRIKI_AUTH = {
    signInWithOAuth: async (provider, redirectTo) => {
      const { error } = await window.SRIKI_SB.auth.signInWithOAuth({
        provider, // 'google' | 'kakao'
        options: { redirectTo },
      });
      if (error) {
        console.error('[sriki] OAuth start failed:', error);
        alert('로그인을 시작할 수 없어요. 잠시 후 다시 시도해 주세요.');
      }
    },
  };
})();
