All files / src/stores auth.js

47.68% Statements 494/1036
86.25% Branches 69/80
51.51% Functions 17/33
47.68% Lines 494/1036

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 11731x                                     1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 9x 9x 9x 9x 6x 6x 9x   1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 2x 98x 98x 3x 98x 98x 98x 3x 98x 98x 6x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x   98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x   98x 98x 2x 98x   98x   98x   98x   98x   98x 3x 98x   98x 21x 21x 17x 17x 11x 11x 17x 17x 17x 17x 17x 17x 10x 10x 10x 17x 21x 4x 4x 4x 4x 4x 98x   98x 98x 98x 17x 13x 13x 1x 1x 1x 13x 98x   98x 42x 12x 12x 12x 98x   98x 98x 98x 98x 13x 3x 3x                     3x 3x 3x 3x 3x 98x   98x 3x                               3x 3x 3x 3x 98x   98x                                                                     98x   98x                                                                                       98x   98x                                                                                                                       98x   98x 98x                                                                                                   98x   98x 98x                                                                                                                                                                                                                 98x   98x 1x 1x   1x 1x 1x                             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x               1x 1x 1x 98x   98x 37x 37x 37x 37x 37x 37x 37x 37x 37x 98x   98x                               98x   98x 98x 98x 98x                                     98x   98x                                                   98x   98x                                                                                                                                                                             98x   98x 98x             98x   98x 98x 98x   98x 13x 13x 13x 13x 13x 13x             13x 13x 13x 98x   98x 98x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x   10x 3x 3x   10x 10x 10x 10x 10x 10x 10x 10x   10x   10x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 4x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 4x   8x 8x   10x 1x 1x 1x 1x 1x 1x         1x 1x 1x     1x 1x 1x 1x 1x   7x 7x 7x 10x   7x 7x 7x 10x     7x 98x   98x 5x 4x 4x 4x 4x 4x 98x   98x 98x 98x 98x 2x 2x 2x 2x 98x   98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 11x 11x 11x 11x 11x   10x 10x 10x 10x                     10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   10x 6x 6x 6x 6x 6x   3x 3x 3x 10x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 10x 10x 10x 10x   10x 98x   98x 3x 3x 3x   3x 3x 3x 3x 3x   3x 3x 3x 3x   3x 3x 3x       3x 3x 98x   98x 98x 98x 98x                                                                     98x   98x                                                           98x   98x                                             98x   98x 98x 98x   98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x   98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x   98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x  
import { reactive, computed } from 'vue';
import { addCSRFHeader, clearCSRFToken } from '../utils/csrf';
import { getTraceHeaders } from '../utils/traceContext';
import { errorMessage } from '../utils/apiError';
import { hasAnyRole } from '../utils/roles';
import { bustApiCache } from '../utils/swCache';
import { getApiBaseUrl } from '../config/api';
import { supabase, getOAuthRedirectUrl } from '../config/supabase';
import {
  recordLogin,
  recordLoginDuration,
  recordSignup,
  recordLogout,
  recordSessionRefresh,
  recordHttpRequest,
  setFaroUser,
  clearFaroUser,
} from '../faro';
 
// Supabase client imported for OAuth only - regular API calls go through backend
 
// Auth store
const state = reactive({
  user: null,
  session: null,
  profile: null,
  loading: false,
  error: null,
});
 
// Silent-refresh machinery — module-level so it is shared across every
// useAuthStore() caller (components each invoke the factory). See SB-78.
let refreshTimer = null; // proactive 60s interval id
let refreshInFlight = null; // single-flight guard: shared in-flight refresh promise
let resumeListenersBound = false; // focus/visibilitychange bound once
 
// Decode a JWT's `exp` claim (epoch seconds) without verifying the signature.
// Used as a fallback when an explicit expires_at isn't available (e.g. on init
// where only the access_token survives in localStorage).
const decodeJwtExp = token => {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return typeof payload.exp === 'number' ? payload.exp : null;
  } catch {
    return null;
  }
};
 
export const useAuthStore = () => {
  // Computed properties
  const isAuthenticated = computed(() => !!state.session);
  // SB-798: compare through hasAnyRole rather than by exact string.
  //
  // user_profiles_role_check accepts both spellings of most roles — club-fan
  // and club_fan, team-manager and team_manager — and real accounts exist under
  // each, because one signup path used to write the underscore form while the
  // others wrote the hyphen form. An exact match therefore covered only the
  // half of its audience that happened to come through the right door, and did
  // so silently: no error, just a capability quietly missing.
  //
  // isTeamManager already had a hand-rolled or-chain for exactly this reason.
  // Its neighbours did not, which is the inconsistency this removes.
  //
  // club_manager is the exception and stays a single spelling: 'club-manager'
  // is not permitted by the constraint at all.
  const isAdmin = computed(() => hasAnyRole(['admin'], state.profile?.role));
  const isClubManager = computed(() =>
    hasAnyRole(['club_manager'], state.profile?.role)
  );
  const isClubFan = computed(() =>
    hasAnyRole(['club-fan'], state.profile?.role)
  );
  const hasClubAccess = computed(() => !!state.profile?.club_id);
  const isTeamManager = computed(() =>
    hasAnyRole(['team-manager'], state.profile?.role)
  );
  const isPlayer = computed(() =>
    hasAnyRole(['team-player'], state.profile?.role)
  );
  // Players can browse all leagues/divisions but not edit
  const canBrowseAll = computed(() => isAdmin.value || isPlayer.value);
  const canManageTeam = computed(
    () => isAdmin.value || isClubManager.value || isTeamManager.value
  );
  const canManageClub = computed(() => isAdmin.value || isClubManager.value);
  const userRole = computed(() => state.profile?.role || 'team-fan');
  const userTeamId = computed(() => state.profile?.team_id);
  const userClubId = computed(() => state.profile?.club_id);
 
  // The user's current-season team assignment, from player_team_history via
  // /api/auth/me. Views personalize their age-group / league / division defaults
  // from this instead of falling back to the app-wide U14 constant (SB-599).
  // `current_teams` is ordered newest season first, so the first entry wins for
  // players on more than one team (e.g. outdoor + futsal).
  const currentTeam = computed(() => state.profile?.current_teams?.[0] || null);
  // Falls back to profile.team_id, which invite-code signup sets but the roster
  // manager does not.
  const userCurrentTeamId = computed(
    () => currentTeam.value?.team_id ?? state.profile?.team_id ?? null
  );
  const userAgeGroupId = computed(
    () => currentTeam.value?.age_group?.id ?? null
  );
  // The age group this account chose to open Table/Matches on (SB-1286).
  // null = no preference: views fall back to the team's, then U14.
  const preferredAgeGroupId = computed(
    () => state.profile?.preferences?.default_age_group_id ?? null
  );
  const userLeagueId = computed(() => currentTeam.value?.league?.id ?? null);
  const userDivisionId = computed(
    () => currentTeam.value?.division?.id ?? null
  );
 
  // Actions
  const setLoading = loading => {
    state.loading = loading;
  };
 
  const setError = error => {
    state.error = error;
  };
 
  const clearError = () => {
    state.error = null;
  };
 
  const setUser = user => {
    state.user = user;
  };
 
  const setSession = session => {
    state.session = session;
    if (session?.access_token) {
      localStorage.setItem('auth_token', session.access_token);
      if (session.refresh_token) {
        localStorage.setItem('refresh_token', session.refresh_token);
      }
      // Resolve token expiry (epoch seconds): prefer the explicit value from the
      // login/refresh response, else decode it from the JWT. Persist it so a
      // proactive refresh can be scheduled even after a page reload.
      const expiresAt =
        session.expires_at || decodeJwtExp(session.access_token);
      if (expiresAt) {
        state.session.expires_at = expiresAt;
        localStorage.setItem('token_expires_at', String(expiresAt));
      }
      startTokenRefreshTimer();
    } else {
      localStorage.removeItem('auth_token');
      localStorage.removeItem('refresh_token');
      localStorage.removeItem('token_expires_at');
      stopTokenRefreshTimer();
    }
  };
 
  // Proactive silent refresh: poll once a minute and refresh the token a few
  // minutes before it expires, so an active session never lapses to a 401.
  const startTokenRefreshTimer = () => {
    if (refreshTimer) return;
    bindResumeListeners();
    refreshTimer = setInterval(() => {
      if (state.session && isTokenExpiringSoon()) {
        refreshSession();
      }
    }, 60 * 1000);
  };
 
  const stopTokenRefreshTimer = () => {
    if (refreshTimer) {
      clearInterval(refreshTimer);
      refreshTimer = null;
    }
  };
 
  // Mobile fix: PWAs/Safari freeze timers while backgrounded, so the interval
  // above won't fire across a long suspend. Refresh on resume (tab focus /
  // becoming visible) when the token is expiring or already expired.
  const bindResumeListeners = () => {
    if (resumeListenersBound || typeof window === 'undefined') return;
    resumeListenersBound = true;
    const maybeRefresh = () => {
      if (
        typeof document !== 'undefined' &&
        document.visibilityState !== 'visible'
      ) {
        return;
      }
      if (!localStorage.getItem('refresh_token')) return;
      if (state.session && isTokenExpiringSoon()) {
        refreshSession();
      }
    };
    window.addEventListener('focus', maybeRefresh);
    if (typeof document !== 'undefined') {
      document.addEventListener('visibilitychange', maybeRefresh);
    }
  };
 
  const setProfile = profile => {
    if (profile) {
      // If profile.team is null but current_teams has entries (from player_team_history),
      // populate profile.team from the first current team so all components that check
      // profile.team work for players added via roster manager.
      if (!profile.team && profile.current_teams?.length > 0) {
        profile.team = profile.current_teams[0].team;
      }
      // Derive club_id from current_teams for roster-managed players
      // whose user_profiles.club_id was never set
      if (!profile.club_id && profile.current_teams?.length > 0) {
        const club = profile.current_teams[0].team?.club;
        if (club?.id) {
          profile.club_id = club.id;
        }
      }
      localStorage.setItem('auth_profile', JSON.stringify(profile));
    } else {
      localStorage.removeItem('auth_profile');
    }
    state.profile = profile;
  };
 
  const signup = async (username, password, displayName, email = null) => {
    try {
      setLoading(true);
      clearError();
 
      const response = await fetch(`${getApiBaseUrl()}/api/auth/signup`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getTraceHeaders(),
        },
        body: JSON.stringify({
          username,
          password,
          display_name: displayName || username,
          email, // Optional email for notifications
        }),
      });
 
      if (!response.ok) {
        const errorData = await response.json();
        recordSignup(false, 'signup', { error_type: 'signup_failed' });
        throw new Error(errorMessage(errorData, 'Signup failed'));
      }
 
      const data = await response.json();
      recordSignup(true, 'signup');
      return { success: true, message: data.message || 'Signup successful!' };
    } catch (error) {
      setError(error.message);
      recordSignup(false, 'signup', { error_type: 'exception' });
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  const signupWithInvite = async (
    username,
    password,
    displayName,
    inviteCode,
    email = null
  ) => {
    try {
      setLoading(true);
      clearError();
 
      const response = await fetch(`${getApiBaseUrl()}/api/auth/signup`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getTraceHeaders(),
        },
        body: JSON.stringify({
          username,
          password,
          display_name: displayName || username,
          invite_code: inviteCode,
          email, // Optional email for notifications
        }),
      });
 
      if (!response.ok) {
        const errorData = await response.json();
        recordSignup(false, 'signup_with_invite', {
          error_type: 'signup_failed',
        });
        throw new Error(errorMessage(errorData, 'Signup failed'));
      }
 
      const data = await response.json();
      recordSignup(true, 'signup_with_invite');
      return { success: true, message: data.message || 'Signup successful!' };
    } catch (error) {
      setError(error.message);
      recordSignup(false, 'signup_with_invite', { error_type: 'exception' });
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  const login = async (username, password) => {
    const startTime = performance.now();
    try {
      setLoading(true);
      clearError();
 
      const response = await fetch(`${getApiBaseUrl()}/api/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getTraceHeaders(),
        },
        body: JSON.stringify({ username, password }),
      });
 
      const duration = performance.now() - startTime;
 
      if (!response.ok) {
        const errorData = await response.json();
        recordLogin(false, { error_type: 'invalid_credentials' });
        recordLoginDuration(duration, false);
        throw new Error(errorMessage(errorData, 'Login failed'));
      }
 
      const data = await response.json();
 
      setUser(data.user);
      setSession({
        access_token: data.access_token,
        refresh_token: data.refresh_token,
        expires_at: data.expires_at,
      });
      // Login endpoint returns basic user info
      setProfile(data.user);
 
      // Store tokens for API calls
      localStorage.setItem('auth_token', data.access_token);
      localStorage.setItem('refresh_token', data.refresh_token);
 
      console.log('Login successful - Basic profile set:', data.user);
 
      // Fetch complete profile (includes photos, personal info, etc.)
      await fetchProfile();
      console.log('Complete profile fetched:', state.profile);
 
      // Record successful login metrics and set user context for observability
      recordLogin(true, { user_role: data.user.role || 'team-fan' });
      recordLoginDuration(duration, true);
      setFaroUser(data.user.id, { role: data.user.role || 'team-fan' });
 
      return { success: true, user: data.user };
    } catch (error) {
      const duration = performance.now() - startTime;
      setError(error.message);
      recordLogin(false, { error_type: 'exception' });
      recordLoginDuration(duration, false);
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  // OAuth Social Login with Google (requires invite code for signup)
  const signInWithGoogle = async (inviteCode = null, displayName = null) => {
    try {
      setLoading(true);
      clearError();
 
      const redirectTo = getOAuthRedirectUrl();
      console.log('Starting Google OAuth, redirect URL:', redirectTo);
 
      // Store invite code and display name in localStorage to retrieve after OAuth callback
      // (OAuth state parameter is limited and can be unreliable across redirects)
      // For LOGIN flow (no invite code), we store a marker to indicate this is a login attempt
      if (inviteCode) {
        localStorage.setItem('oauth_invite_code', inviteCode);
        localStorage.setItem('oauth_flow_type', 'signup');
      } else {
        localStorage.removeItem('oauth_invite_code');
        localStorage.setItem('oauth_flow_type', 'login');
      }
      if (displayName) {
        localStorage.setItem('oauth_display_name', displayName);
      }
 
      const { data, error } = await supabase.auth.signInWithOAuth({
        provider: 'google',
        options: {
          redirectTo,
          queryParams: {
            access_type: 'offline',
            prompt: 'consent',
          },
        },
      });
 
      if (error) {
        localStorage.removeItem('oauth_invite_code');
        localStorage.removeItem('oauth_display_name');
        recordLogin(false, { error_type: 'oauth_initiation_failed' });
        throw new Error(error.message);
      }
 
      // User will be redirected to Google, then back to our callback URL
      // The callback handler will complete the authentication
      return { success: true, url: data.url };
    } catch (error) {
      setError(error.message);
      recordLogin(false, { error_type: 'oauth_exception' });
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  // Handle OAuth callback - called after redirect back from Google
  const handleOAuthCallback = async () => {
    try {
      setLoading(true);
      clearError();
 
      // Retrieve invite code, flow type, and display name stored before OAuth redirect
      const inviteCode = localStorage.getItem('oauth_invite_code');
      const flowType = localStorage.getItem('oauth_flow_type') || 'signup';
      const customDisplayName = localStorage.getItem('oauth_display_name');
 
      // Clean up immediately
      localStorage.removeItem('oauth_invite_code');
      localStorage.removeItem('oauth_flow_type');
      localStorage.removeItem('oauth_display_name');
 
      const isLoginFlow = flowType === 'login' || !inviteCode;
 
      // Get the session from the URL hash (Supabase puts tokens there)
      const { data, error } = await supabase.auth.getSession();
 
      if (error) {
        throw new Error(error.message);
      }
 
      if (!data.session) {
        throw new Error('No session found after OAuth callback');
      }
 
      // DO NOT set session yet - wait for backend validation
      // The backend will verify the invite code (signup) or find existing user (login)
 
      // Verify with our backend and get/create user profile
      // For LOGIN: invite_code will be null, backend finds existing user
      // For SIGNUP: invite_code validates invite and creates profile
      const requestBody = {
        access_token: data.session.access_token,
        refresh_token: data.session.refresh_token,
        provider: 'google',
      };
 
      // Only include invite_code and display_name for signup flow
      if (!isLoginFlow && inviteCode) {
        requestBody.invite_code = inviteCode;
        requestBody.display_name = customDisplayName;
      }
 
      console.log(
        `OAuth callback: ${isLoginFlow ? 'LOGIN' : 'SIGNUP'} flow`,
        isLoginFlow ? '' : `invite_code: ${inviteCode}`
      );
 
      const response = await fetch(
        `${getApiBaseUrl()}/api/auth/oauth/callback`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${data.session.access_token}`,
            ...getTraceHeaders(),
          },
          body: JSON.stringify(requestBody),
        }
      );
 
      if (!response.ok) {
        const errorData = await response.json();
        // Backend rejected - sign out of Supabase to clean up
        // This removes the Supabase user created during OAuth
        try {
          await supabase.auth.signOut();
        } catch (signOutError) {
          console.warn(
            'Failed to sign out of Supabase after rejection:',
            signOutError
          );
        }
        throw new Error(errorMessage(errorData, 'OAuth callback failed'));
      }
 
      const userData = await response.json();
 
      // Only NOW set the session - after backend validation succeeded
      setSession({
        access_token: data.session.access_token,
        refresh_token: data.session.refresh_token,
      });
 
      setUser(userData.user);
      setProfile(userData.user);
 
      // Record successful OAuth login
      recordLogin(true, {
        user_role: userData.user.role || 'team-fan',
        provider: 'google',
      });
      setFaroUser(userData.user.id, { role: userData.user.role || 'team-fan' });
 
      return { success: true, user: userData.user };
    } catch (error) {
      setError(error.message);
      recordLogin(false, { error_type: 'oauth_callback_failed' });
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  const logout = async () => {
    try {
      setLoading(true);
 
      // Call backend logout endpoint using plain fetch (not apiCall to avoid infinite loop)
      const token = localStorage.getItem('auth_token');
      if (token) {
        try {
          await fetch(`${getApiBaseUrl()}/api/auth/logout`, {
            method: 'POST',
            headers: {
              Authorization: `Bearer ${token}`,
              'Content-Type': 'application/json',
            },
          });
        } catch (e) {
          // Ignore logout endpoint errors - we'll clear local state anyway
          console.warn('Logout endpoint error (ignored):', e);
        }
      }
 
      // Clear local state regardless of API response
      stopTokenRefreshTimer();
      setUser(null);
      setSession(null);
      setProfile(null);
      localStorage.removeItem('auth_token');
      localStorage.removeItem('refresh_token');
      localStorage.removeItem('token_expires_at');
      localStorage.removeItem('sb-localhost-auth-token');
      clearCSRFToken();
 
      // Record logout metric and clear user context
      recordLogout();
      clearFaroUser();
 
      return { success: true };
    } catch (error) {
      // Still clear local state on error
      setUser(null);
      setSession(null);
      setProfile(null);
      localStorage.clear();
      setError(error.message);
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  const forceLogout = () => {
    // Force clear all auth state without async calls
    stopTokenRefreshTimer();
    state.user = null;
    state.session = null;
    state.profile = null;
    state.loading = false;
    state.error = null;
    localStorage.clear();
    sessionStorage.clear();
  };
 
  const fetchProfile = async () => {
    try {
      if (!state.session) return;
 
      const response = await apiCall(`${getApiBaseUrl()}/api/auth/me`);
      if (response && response.success) {
        setProfile(response.user.profile);
        return response.user.profile;
      } else {
        console.warn('No profile found for user');
        return null;
      }
    } catch (error) {
      console.error('Error fetching profile:', error);
      setError(error.message);
    }
  };
 
  // Save a partial preferences update (null clears a key). Deliberately does
  // not toggle state.loading: ProfileRouter swaps the whole page for a spinner
  // on that flag, which a single dropdown change should not do (SB-1286).
  const updatePreferences = async changes => {
    try {
      const response = await apiCall(`${getApiBaseUrl()}/api/auth/profile`, {
        method: 'PUT',
        body: JSON.stringify({ preferences: changes }),
      });
      if (!response?.success) {
        throw new Error(errorMessage(response, 'Could not save preferences'));
      }
      const merged = { ...(state.profile?.preferences || {}) };
      for (const [key, value] of Object.entries(changes)) {
        if (value === null || value === undefined) delete merged[key];
        else merged[key] = value;
      }
      if (state.profile) state.profile.preferences = merged;
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  };
 
  const updateProfile = async updates => {
    try {
      setLoading(true);
      clearError();
 
      const response = await apiCall(`${getApiBaseUrl()}/api/auth/profile`, {
        method: 'PUT',
        body: JSON.stringify({
          ...updates,
          updated_at: new Date().toISOString(),
        }),
      });
 
      if (response && response.success) {
        // Refresh profile
        await fetchProfile();
        return { success: true, data: response.data };
      } else {
        throw new Error(errorMessage(response, 'Profile update failed'));
      }
    } catch (error) {
      setError(error.message);
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  const initialize = async () => {
    try {
      setLoading(true);
 
      // Check for existing token
      const token = localStorage.getItem('auth_token');
      if (!token) {
        return;
      }
 
      // Don't set session until verification succeeds
      // This prevents showing authenticated content while verifying
 
      // Get current user info from backend (verify token)
      const response = await fetch(`${getApiBaseUrl()}/api/auth/me`, {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
          ...getTraceHeaders(),
        },
      });
 
      if (response.ok) {
        const data = await response.json();
        if (data && data.success) {
          setUser(data.user);
          // /api/auth/me returns role/team_id nested in user.profile
          const profileData = data.user.profile || data.user;
          setProfile(profileData);
          setSession({ access_token: token }); // Only set session after verification
          console.log('Initialize - Profile loaded:', profileData);
        } else {
          // Invalid response, clear storage
          localStorage.clear();
        }
      } else if (response.status === 401) {
        // Token expired, try to refresh
        const refreshToken = localStorage.getItem('refresh_token');
        if (refreshToken) {
          const refreshResult = await refreshSession();
          if (refreshResult.success) {
            // Retry initialization with new token
            const newToken = localStorage.getItem('auth_token');
            const retryResponse = await fetch(
              `${getApiBaseUrl()}/api/auth/me`,
              {
                headers: {
                  Authorization: `Bearer ${newToken}`,
                  'Content-Type': 'application/json',
                  ...getTraceHeaders(),
                },
              }
            );
            if (retryResponse.ok) {
              const retryData = await retryResponse.json();
              if (retryData && retryData.success) {
                setUser(retryData.user);
                const profileData = retryData.user.profile || retryData.user;
                setProfile(profileData);
                setSession({ access_token: newToken });
                console.log(
                  'Initialize - Profile loaded after refresh:',
                  profileData
                );
                return;
              }
            }
          }
          if (refreshResult.transient) {
            // Server unreachable on boot (offline / waking). Keep the
            // still-valid tokens so a later reload restores the session rather
            // than forcing a needless re-login.
            return;
          }
        }
        // Genuine auth failure or no refresh token — clear storage.
        localStorage.clear();
      } else {
        // Other error, clear storage
        localStorage.clear();
      }
    } catch (error) {
      console.error('Auth initialization error:', error);
      localStorage.clear();
    } finally {
      setLoading(false);
    }
  };
 
  // API helpers with auth headers
  const getAuthHeaders = () => {
    const token = localStorage.getItem('auth_token');
    return {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
      ...getTraceHeaders(), // Include session_id and request_id for distributed tracing
    };
  };
 
  // SB-118: abort hung requests (e.g. dead mobile signal) so callers fail
  // fast instead of leaving saving/loading spinners stuck indefinitely.
  const API_TIMEOUT_MS = 30000;
 
  const fetchWithTimeout = async (endpoint, options = {}) => {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), API_TIMEOUT_MS);
    try {
      // Caller-supplied signal (spread after ours) takes precedence
      return await fetch(endpoint, { signal: controller.signal, ...options });
    } catch (err) {
      if (err.name === 'AbortError') {
        throw new Error(
          'Request timed out. Check your connection and try again.'
        );
      }
      throw err;
    } finally {
      clearTimeout(timer);
    }
  };
 
  // NEW: Simple API call helper with auth headers
  const apiCall = async (endpoint, options = {}) => {
    const startTime = performance.now();
    const method = options.method || 'GET';
    const token = localStorage.getItem('auth_token');
    const traceHeaders = getTraceHeaders(); // Generate trace IDs for this request
    const defaultHeaders = { ...traceHeaders };
 
    // Only set Content-Type for non-FormData requests
    // FormData needs the browser to set Content-Type with boundary automatically
    if (!(options.body instanceof FormData)) {
      defaultHeaders['Content-Type'] = 'application/json';
    }
 
    if (token) {
      defaultHeaders.Authorization = `Bearer ${token}`;
    }
 
    let response = await fetchWithTimeout(endpoint, {
      ...options,
      cache: 'no-store',
      headers: {
        ...defaultHeaders,
        ...options.headers,
      },
    });
 
    let duration = performance.now() - startTime;
 
    if (response.status === 401) {
      // Token expired, try refresh
      const refreshResult = await refreshSession();
      const retryToken = refreshResult.success
        ? localStorage.getItem('auth_token')
        : null;
      if (retryToken) {
        // Retry original request. The refreshed token must win over the
        // caller's headers: apiRequest passes the expired Authorization in
        // options.headers, and letting it override would 401 the retry.
        response = await fetchWithTimeout(endpoint, {
          ...options,
          cache: 'no-store',
          headers: {
            ...defaultHeaders,
            ...options.headers,
            Authorization: `Bearer ${retryToken}`,
          },
        });
        duration = performance.now() - startTime;
        if (response.status === 401) {
          // The refresh succeeded, so the session is valid — a 401 here is
          // not "your session expired" (e.g. a transient backend failure
          // verifying the token). Surface it without destroying the session.
          recordHttpRequest(endpoint, method, 401, duration);
          const err = new Error(
            'Could not authorize this request. Please try again.'
          );
          err.status = 401;
          throw err;
        }
        // Any other retry outcome goes through the normal handling below.
      } else {
        recordHttpRequest(endpoint, method, 401, duration);
        // A transient refresh failure (network/5xx) leaves the refresh token
        // intact — don't destroy the session over a blip; surface a retryable
        // error so the caller can try again once connectivity returns.
        if (refreshResult.transient) {
          throw new Error('Could not reach the server. Please try again.');
        }
        // Genuine auth failure — refreshSession already cleared state; finish the
        // logout for CSRF/Faro cleanup, then send the user back to login.
        await logout();
        throw new Error('Session expired. Please log in again.');
      }
    }
 
    // Record HTTP request metrics
    recordHttpRequest(endpoint, method, response.status, duration);
 
    if (!response.ok) {
      const error = await response
        .json()
        .catch(() => ({ message: 'Network error' }));
      // Handle FastAPI validation errors (422) where detail is an array
      let errorMessage = 'Request failed';
      if (Array.isArray(error.detail)) {
        // Extract message(s) from validation error array
        errorMessage = error.detail
          .map(e => e.msg || e.message || JSON.stringify(e))
          .join('; ');
      } else if (typeof error.detail === 'string') {
        errorMessage = error.detail;
      } else if (error.message) {
        errorMessage = error.message;
      }
      // Callers that word errors by status (chat posting, SB-1324) read it here.
      const err = new Error(errorMessage);
      err.status = response.status;
      throw err;
    }
 
    // The service worker serves the read APIs with StaleWhileRevalidate, so a
    // re-fetch that follows a write would be answered from the pre-write cache
    // — the admin's own change would not show up until a reload (SB-902).
    if (method !== 'GET') await bustApiCache();
 
    if (
      response.status === 204 ||
      response.headers.get('content-length') === '0'
    ) {
      return null;
    }
    return response.json();
  };
 
  const isTokenExpiringSoon = () => {
    if (!state.session?.expires_at) return false;
    const expiresAt = new Date(state.session.expires_at * 1000);
    const now = new Date();
    const timeUntilExpiry = expiresAt.getTime() - now.getTime();
    // Return true if token expires in less than 5 minutes
    return timeUntilExpiry < 5 * 60 * 1000;
  };
 
  // Hard-clear all auth state. Only ever called on a *genuine* auth failure
  // (missing or server-rejected refresh token) — never on a transient
  // network/server blip, which would otherwise throw away a still-valid token.
  const clearAuthState = () => {
    setUser(null);
    setSession(null);
    setProfile(null);
    localStorage.clear();
  };
 
  // Refresh the access token. Returns:
  //   { success: true }
  //   { success: false, transient: true }  — network down / 5xx / 429; the
  //       refresh token is untouched so a later attempt can recover.
  //   { success: false, transient: false } — refresh token genuinely rejected;
  //       auth state is cleared and the user must log in again.
  // The transient/genuine split exists because the proactive timer (and resume
  // listeners) can fire on wake-from-sleep *before* connectivity is restored:
  // a thrown fetch must NOT be mistaken for "your session is invalid". (SB-78)
  const refreshSession = async () => {
    // Single-flight: with refresh-token rotation enabled, two concurrent
    // refreshes would send the same token twice — the second send uses an
    // already-rotated token and gets rejected, forcing a spurious logout.
    // Share one in-flight promise so parallel callers await the same result.
    if (refreshInFlight) return refreshInFlight;
 
    refreshInFlight = (async () => {
      try {
        const refreshToken = localStorage.getItem('refresh_token');
        if (!refreshToken) {
          // Nothing to refresh with — genuinely unauthenticated.
          clearAuthState();
          recordSessionRefresh(false);
          return {
            success: false,
            transient: false,
            error: 'No refresh token',
          };
        }
 
        let response;
        try {
          response = await fetch(`${getApiBaseUrl()}/api/auth/refresh`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              ...getTraceHeaders(),
            },
            body: JSON.stringify({ refresh_token: refreshToken }),
          });
        } catch (networkError) {
          // No response at all — almost always transient connectivity (e.g. the
          // proactive timer firing on wake-from-sleep before wifi reconnects).
          // Keep the still-valid refresh token; the next attempt recovers.
          recordSessionRefresh(false);
          return {
            success: false,
            transient: true,
            error: networkError.message,
          };
        }
 
        if (response.ok) {
          const data = await response.json();
          setSession(data.session);
          recordSessionRefresh(true);
          return { success: true };
        }
 
        recordSessionRefresh(false);
        // Only a real auth rejection means the refresh token is dead. 5xx / 429
        // are server-side hiccups, not the token's fault — retry later.
        if (response.status === 401 || response.status === 403) {
          clearAuthState();
          return {
            success: false,
            transient: false,
            error: 'Refresh token rejected',
          };
        }
        return {
          success: false,
          transient: true,
          error: `Token refresh failed: ${response.status}`,
        };
      } finally {
        refreshInFlight = null;
      }
    })();
 
    return refreshInFlight;
  };
 
  const apiRequest = async (url, options = {}) => {
    // For FormData, don't set Content-Type - browser sets it with boundary
    const isFormData = options.body instanceof FormData;
    const token = localStorage.getItem('auth_token');
 
    let headers = {
      Authorization: `Bearer ${token}`,
      ...getTraceHeaders(), // Include trace IDs for distributed tracing
      ...options.headers,
    };
 
    // Only add Content-Type for non-FormData requests
    if (!isFormData) {
      headers['Content-Type'] = 'application/json';
    }
 
    if (
      ['POST', 'PUT', 'DELETE', 'PATCH'].includes(options.method?.toUpperCase())
    ) {
      headers = await addCSRFHeader(headers);
    }
 
    // Use the simpler apiCall helper
    return apiCall(url, { ...options, headers });
  };
 
  // Takes only the identifier. It used to accept an email for an account
  // that had none, which the API would store and send the reset link to —
  // an account takeover for anyone who knew a username (SB-1129).
  const requestPasswordReset = async identifier => {
    try {
      setLoading(true);
      clearError();
 
      const body = { identifier };
 
      const response = await fetch(
        `${getApiBaseUrl()}/api/auth/forgot-password`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...getTraceHeaders(),
          },
          body: JSON.stringify(body),
        }
      );
 
      const data = await response.json();
 
      if (!response.ok) {
        throw new Error(errorMessage(data, 'Request failed'));
      }
 
      return {
        success: true,
        message: data.message,
      };
    } catch (error) {
      setError(error.message);
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  const resetPassword = async (token, newPassword) => {
    try {
      setLoading(true);
      clearError();
 
      const response = await fetch(
        `${getApiBaseUrl()}/api/auth/reset-password`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...getTraceHeaders(),
          },
          body: JSON.stringify({ token, new_password: newPassword }),
        }
      );
 
      const data = await response.json();
 
      if (!response.ok) {
        throw new Error(errorMessage(data, 'Password reset failed'));
      }
 
      return { success: true, message: data.message };
    } catch (error) {
      setError(error.message);
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };
 
  const checkUsernameAvailability = async username => {
    try {
      const response = await fetch(
        `${getApiBaseUrl()}/api/auth/username-available/${username}`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            ...getTraceHeaders(),
          },
        }
      );
 
      if (!response.ok) {
        throw new Error('Failed to check username availability');
      }
 
      const data = await response.json();
      return data; // Returns { available, message, suggestions? }
    } catch (error) {
      console.error('Username availability check error:', error);
      return { available: false, message: 'Error checking username' };
    }
  };
 
  return {
    // State
    state,
 
    // Computed
    isAuthenticated,
    isAdmin,
    isClubManager,
    isClubFan,
    hasClubAccess,
    isTeamManager,
    isPlayer,
    canBrowseAll,
    canManageTeam,
    canManageClub,
    userRole,
    userTeamId,
    userClubId,
    currentTeam,
    userCurrentTeamId,
    userAgeGroupId,
    preferredAgeGroupId,
    userLeagueId,
    userDivisionId,
 
    // Actions
    signup,
    signupWithInvite,
    login,
    signInWithGoogle,
    handleOAuthCallback,
    logout,
    forceLogout,
    fetchProfile,
    updatePreferences,
    updateProfile,
    initialize,
    setError,
    clearError,
 
    // Helpers
    getAuthHeaders,
    apiRequest,
    apiCall,
    setSession,
    refreshSession,
    isTokenExpiringSoon,
    checkUsernameAvailability,
    requestPasswordReset,
    resetPassword,
  };
};