const API_BASE_URL = '/smart_football/api/v1';

async function request(endpoint, method = 'GET', data = null) {
    const config = {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        }
    };

    const token = localStorage.getItem('jwt_token');
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }

    if (data) {
        config.body = JSON.stringify(data);
    }

    try {
        const response = await fetch(`${API_BASE_URL}${endpoint}`, config);
        const responseData = await response.json();
        if (!response.ok) {
            throw new Error(responseData.message || 'An API error occurred.');
        }
        return responseData;
    } catch (error) {
        console.error('API Error:', error);
        // You can add global error handling here, e.g., show a toast notification
        throw error;
    }
}

// --- Auth Functions ---
export const login = (email, password) => request('/auth/login.php', 'POST', { email, password });
export const getUser = () => request('/auth/get_user.php', 'GET');

// --- Public Functions ---
export const getLeagues = () => request('/leagues/index.php');

// We will add more functions here (e.g., getLeagueTable) as we build
export const getFixturesByLeague = (leagueId, gameweek = null) => request(`/fixtures/index.php?league_id=${leagueId}${gameweek ? `&gameweek=${gameweek}` : ''}`);
export const getLeagueTable = (leagueId, type = 'full') => request(`/leagues/table.php?league_id=${leagueId}&type=${type}`);
export const getFixturesByGameweek = (leagueId, gameweek) => request(`/fixtures/by_gameweek.php?league_id=${leagueId}&gameweek=${gameweek}`);
export const getFixtureById = (fixtureId) => request(`/fixtures/show.php?id=${fixtureId}`);
export const getLiveLeagueTable = (fixtureId) => request(`/leagues/live_table.php?fixture_id=${fixtureId}`);
export const getLineup = (fixtureId) => request(`/lineups/get.php?fixture_id=${fixtureId}`);
export const getMatchEvents = (fixtureId) => request(`/gameday/get_events.php?fixture_id=${fixtureId}`);
export const getMatchUpdates = (fixtureId) => request(`/gameday/get_match_updates.php?fixture_id=${fixtureId}`);
export const getMatchComments = (fixtureId) => request(`/gameday/get_comments.php?fixture_id=${fixtureId}`);
export const submitComment = (fixtureId, comment) => request('/gameday/submit_comment.php', 'POST', { fixture_id: fixtureId, comment: comment });
export const getTopScorers = (leagueId) => request(`/stats/leaders.php?league_id=${leagueId}&type=goals`);
export const getTopAssists = (leagueId) => request(`/stats/leaders.php?league_id=${leagueId}&type=assists`);
export const getMostCleanSheets = (leagueId) => request(`/stats/leaders.php?league_id=${leagueId}&type=clean_sheets`);
export const getMostCards = (leagueId) => request(`/stats/leaders.php?league_id=${leagueId}&type=cards`);
export const getMostFouls = (leagueId) => request(`/stats/leaders.php?league_id=${leagueId}&type=fouls`);
export const getTeamStats = (leagueId) => request(`/stats/leaders.php?league_id=${leagueId}&type=team`);

// --- Gameday/Livescorer Functions ---
export const logMatchEvent = (data) => request('/gameday/log_event.php', 'POST', data);
export const updateMatchStatus = (data) => request('/gameday/update_match.php', 'POST', data);

// --- Fantasy Functions ---
export const getFantasyTeamForUser = (season) => request(`/fantasy/get_team.php?season=${season}`);
export const createFantasyTeam = (name, season) => request('/fantasy/create_team.php', 'POST', { name, season });
export const getAllPlayersForSelection = () => request('/fantasy/get_players_for_selection.php');

export const selectSquad = (fantasyTeamId, playerIds) => request('/fantasy/select_squad.php', 'POST', { fantasy_team_id: fantasyTeamId, player_ids: playerIds });
export const getFantasySquad = (fantasyTeamId) => request(`/fantasy/get_squad.php?id=${fantasyTeamId}`);
export const getFantasyLeagues = () => request('/fantasy/leagues/index.php');
export const createFantasyLeague = (name) => request('/fantasy/leagues/create.php', 'POST', { name });
export const joinFantasyLeague = (inviteCode) => request('/fantasy/leagues/join.php', 'POST', { invite_code: inviteCode });

export const makeSubstitution = (fantasyTeamId, playerOutId, playerInId) => request('/fantasy/make_substitution.php', 'POST', { fantasy_team_id: fantasyTeamId, player_out_id: playerOutId, player_in_id: playerInId });
export const getLatestDashboardData = (leagueId) => request(`/dashboard/latest.php?league_id=${leagueId}`);

// --- Commissioner Functions ---
export const getMyAssignedGames = () => request('/commissioner/my_games.php');

// --- Manager Functions ---
export const getManagerTeamData = () => request('/manager/my_team_data.php');
export const getManagerUpcomingFixtures = () => request('/manager/get_upcoming_fixtures.php');
export const submitLineup = (fixtureId, starters) => request('/manager/submit_lineup.php', 'POST', { fixture_id: fixtureId, starters: starters });

// --- Search Functions ---
export const globalSearch = (query) => request(`/search/global.php?query=${query}`);

// --- Player Functions ---
export const getPlayerDetails = (playerId) => request(`/players/show.php?id=${playerId}`);

// --- Club Functions ---
export const getClubDetails = (clubId) => request(`/clubs/show.php?id=${clubId}`);

// --- Follow Functions ---
export const toggleFollow = (type, id) => request('/follow/toggle.php', 'POST', { type, id });
export const getMyFollows = () => request('/follow/index.php');
