<?php
require_once '../core/bootstrap.php';

// --- Authentication ---
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$fantasyModel = new Fantasy();
$seasonModel = new Season();
$fantasySquadModel = new FantasySquad();
$fixtureModel = new Fixture();
$gameweekModel = new Gameweek();
$fantasyPointsModel = new FantasyPoints();
$fantasyLeagueModel = new FantasyLeague();
$playerModel = new Player();
$leagueModel = new League();

// --- Determine Active Tab ---
$active_tab = $_GET['tab'] ?? 'pitch';
$allowed_tabs = ['points', 'pitch', 'transfers', 'leagues'];
if (!in_array($active_tab, $allowed_tabs)) {
    $active_tab = 'pitch';
}

// --- Determine League Context ---
$leagues = $leagueModel->getAll();
$selected_league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);
if (!$selected_league_id && !empty($leagues)) {
    $selected_league_id = $leagues[0]->id;
}

// --- Auto-Migration for Chips ---
$db = new Database();
try {
    $db->query("SELECT active_chip FROM fantasy_teams LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    $db->query("ALTER TABLE fantasy_teams 
        ADD COLUMN active_chip VARCHAR(10) DEFAULT NULL,
        ADD COLUMN tc_played_gw INT DEFAULT NULL,
        ADD COLUMN bb_played_gw INT DEFAULT NULL,
        ADD COLUMN fh_played_gw INT DEFAULT NULL,
        ADD COLUMN wc_played_gw INT DEFAULT NULL");
    $db->execute();
}

// --- Get User's Fantasy Team & Squad ---
$latest_season = $seasonModel->getAll()[0]->name ?? date('Y') . '/' . (date('Y') + 1);
$user_fantasy_team = $fantasyModel->getTeamByUserIdAndLeague($user_id, $latest_season, $selected_league_id);

if (!$user_fantasy_team) {
    header('Location: fantasy.php?league_id=' . $selected_league_id); // Redirect to create team if none exists for this league
    exit();
}

// --- Fix Initial Bank Balance ---
// If the bank is still at the default 100.0 but players have been selected, update it.
if ((float)$user_fantasy_team->bank == 100.0 && (float)$user_fantasy_team->squad_value > 0) {
    $correct_bank = 100.0 - (float)$user_fantasy_team->squad_value;
    $fantasyModel->updateBank($user_fantasy_team->id, $correct_bank);
    $user_fantasy_team->bank = $correct_bank;
}

$squad = $fantasySquadModel->getSquadByTeamId($user_fantasy_team->id);

// --- Safety Check: Malformed Squad ---
if (count($squad) !== 15) {
    // If squad size is wrong (e.g. due to a previous bug), force a reset
    $fantasySquadModel->deleteSquad($user_fantasy_team->id);
    header('Location: fantasy.php?error=squad_reset_required');
    exit();
}

if (empty($squad)) {
    header('Location: fantasy.php'); // Redirect to pick squad if it's empty
    exit();
}

$pageTitle = 'My Fantasy Lineup';
include 'includes/header.php';

// --- Determine Current Gameweek & Deadline ---
$current_gameweek = 1;
$league_id_for_gameweek = $selected_league_id;
$latest_finished_gameweek = $fixtureModel->getLatestFinishedGameweek($league_id_for_gameweek);
if ($latest_finished_gameweek) {
    $current_gameweek = $latest_finished_gameweek + 1;
} else {
    $next_fixture = $fixtureModel->getNextUpcomingFixture($league_id_for_gameweek);
    if ($next_fixture) $current_gameweek = $next_fixture->gameweek;
}

$deadline_passed = $gameweekModel->hasDeadlinePassed($current_gameweek, $selected_league_id, $latest_season);
$deadline_time = $gameweekModel->getDeadlineTime($current_gameweek, $league_id_for_gameweek, $latest_season);

// --- Logic: Earn 1 free transfer every week, max 4, then reset to 1 ---
$db = new Database();
$last_gw_update = $user_fantasy_team->last_gw_update ?? ($current_gameweek - 1);
$current_ft = $user_fantasy_team->free_transfers ?? 1;

if ($current_gameweek > $last_gw_update) {
    $weeks_passed = $current_gameweek - $last_gw_update;
    for ($i = 0; $i < $weeks_passed; $i++) {
        if ($current_ft < 4) {
            $current_ft++;
        } else {
            $current_ft = 1;
        }
    }
    // Update DB
    $db->query("UPDATE fantasy_teams SET free_transfers = :ft, last_gw_update = :gw WHERE id = :id");
    $db->bind(':ft', $current_ft);
    $db->bind(':gw', $current_gameweek);
    $db->bind(':id', $user_fantasy_team->id);
    $db->execute();
    $user_fantasy_team->free_transfers = $current_ft; // Update local object
}

// --- Get Currency Symbol ---
$settings = (new Setting())->getAll();
$currency_symbol = '$';
if (($settings['system_currency'] ?? 'USD') === 'ZMW') $currency_symbol = 'K';
elseif (($settings['system_currency'] ?? 'USD') === 'EUR') $currency_symbol = '€';
$primary_color = $settings['primary_color'] ?? '#37003c';
$secondary_color = $settings['secondary_color'] ?? '#580a66';

// --- Fetch Data for Transfers Tab ---
$all_players = $playerModel->getPlayersForFantasySelection($selected_league_id);
$player_form = $fantasyPointsModel->getPlayerForm($selected_league_id, $current_gameweek);
$current_squad_ids = array_map(fn($p) => $p->player_id, $squad);

// Prepare all players data for JS
$all_players_js = [];
foreach ($all_players as $p) {
    $all_players_js[] = [
        'id' => $p->id,
        'name' => $p->first_name . ' ' . $p->last_name,
        'club' => $p->club_short_name,
        'profile_picture' => $p->profile_picture,
        'club_logo' => $p->club_logo,
        'position' => $p->position,
        'price' => (float)$p->fantasy_price,
        'form' => $player_form[$p->id] ?? '0.0',
    ];
}

// Fetch points for current squad for the previous gameweek
$previous_gw_for_points = $latest_finished_gameweek ?: ($current_gameweek > 1 ? $current_gameweek - 1 : 1);
$previous_gw_points = $fantasyPointsModel->getPointsForPlayers($current_squad_ids, $previous_gw_for_points);

// Create squad data for JS action modal
$squad_js = [];
foreach ($squad as $p) {
    $squad_js[$p->player_id] = [
        'name' => $p->first_name . ' ' . $p->last_name,
        'position' => $p->position,
        'club_name' => $p->club_name,
        'profile_picture' => $p->profile_picture ?: $p->club_logo,
        'price' => (float)$p->fantasy_price,
        'team_id' => $p->team_id,
        'points' => $previous_gw_points[$p->player_id] ?? 0,
    ];
}

// --- Fetch League Data for Tab ---
$leagues_data = [];

// 1. Add Global League (Public)
$global_rank = $fantasyModel->getGlobalRank($user_fantasy_team->id, $selected_league_id);
$leagues_data[] = [
    'id' => 0,
    'name' => 'Global League',
    'rank' => $global_rank,
    'url' => 'fantasy_global_league.php?league_id=' . $selected_league_id
];

if ($user_fantasy_team) {
    $my_leagues = $fantasyLeagueModel->getLeaguesForUser($user_fantasy_team->id);
    foreach ($my_leagues as $league) {
        $rank = $fantasyLeagueModel->getUserRank($league->id, $user_fantasy_team->id);
        $leagues_data[] = [
            'id' => $league->id,
            'name' => $league->name,
            'rank' => $rank,
            'url' => 'fantasy_league_view.php?id=' . $league->id . '&league_id=' . $selected_league_id
        ];
    }
}

// --- Fetch Points for Points Tab (Previous/Latest Finished Gameweek) ---
$requested_gw = filter_input(INPUT_GET, 'gw', FILTER_VALIDATE_INT);
$points_view_gameweek = $requested_gw ?: ($latest_finished_gameweek ?: ($current_gameweek > 1 ? $current_gameweek - 1 : 1));
$points_view_gameweek = max(1, min($points_view_gameweek, $current_gameweek)); // Clamp

// Determine if TC was active for this historical gameweek
$points_view_active_chip = null;
if (isset($user_fantasy_team->tc_played_gw) && $user_fantasy_team->tc_played_gw == $points_view_gameweek) {
    $points_view_active_chip = 'TC';
}

// --- Fetch Squad for Points View (Historical) ---
$db = new Database();
$db->query("
    SELECT fp.*, u.first_name, u.last_name, p.position, t.club_id, u.profile_picture, 
           c.name as club_name, c.logo as club_logo,
           p.fantasy_price
    FROM fantasy_picks fp
    JOIN players p ON fp.player_id = p.user_id
    JOIN users u ON p.user_id = u.id
    LEFT JOIN teams t ON p.team_id = t.id
    LEFT JOIN clubs c ON t.club_id = c.id
    WHERE fp.fantasy_team_id = :team_id AND fp.gameweek = :gw
    ORDER BY fp.bench_order ASC
");
$db->bind(':team_id', $user_fantasy_team->id);
$db->bind(':gw', $points_view_gameweek);
$points_squad_raw = $db->resultSet();

// If no squad found for that gameweek (e.g. before team creation), fallback to empty
if (empty($points_squad_raw)) {
    if ($points_view_gameweek == $current_gameweek && !empty($squad)) {
        $points_squad_raw = $squad;
    } else {
        $points_squad_raw = [];
    }
}

// Fetch points for the players in the historical squad
$points_view_player_ids = array_map(fn($p) => $p->player_id, $points_squad_raw);
$points_view_player_points = $fantasyPointsModel->getPointsForPlayers($points_view_player_ids, $points_view_gameweek);

// Fetch points for current squad (for the pick team tab)
$gameweek_player_points = $fantasyPointsModel->getPointsForPlayers(array_map(fn($p) => $p->player_id, $squad), $current_gameweek);

// --- Organize Squad ---
$starters = [];
$bench = [];
$captain_id = null;
$vice_captain_id = null;
$formation = '4-4-2'; // Default

foreach ($squad as $player) {
    if ($player->is_starter) {
        $starters[] = $player;
    } else {
        $bench[] = $player;
    }
    if ($player->is_captain) $captain_id = $player->player_id;
    if ($player->is_vice_captain) $vice_captain_id = $player->player_id;
    if ($player->formation) $formation = $player->formation;
}

// --- Enforce 1 GK Rule (Auto-correct bad data) ---
$gk_starters = [];
foreach ($starters as $key => $player) {
    if ($player->position === 'Goalkeeper') {
        $gk_starters[$key] = $player;
    }
}

if (count($gk_starters) > 1) {
    // Keep the first one, move others to bench
    array_shift($gk_starters); // Remove first from the "to move" list
    foreach ($gk_starters as $key => $player) {
        unset($starters[$key]);
        $player->is_starter = 0;
        $bench[] = $player;
    }
    $starters = array_values($starters); // Re-index
}

// --- Auto-Select Captain if None Set ---
if (!$captain_id) {
    // Sort squad by price descending to pick the most valuable player as captain
    usort($squad, function($a, $b) {
        return $b->fantasy_price <=> $a->fantasy_price;
    });

    if (!empty($squad)) {
        $captain_id = $squad[0]->player_id;
        $squad[0]->is_captain = 1;
        
        // Set Vice Captain (2nd most valuable)
        if (isset($squad[1])) {
            $vice_captain_id = $squad[1]->player_id;
            $squad[1]->is_vice_captain = 1;
        }
        // Save this auto-selection to DB so it persists
        $fantasySquadModel->setCaptains($user_fantasy_team->id, $captain_id, $vice_captain_id ?? 0);
    }
}

// Sort bench by bench_order
usort($bench, fn($a, $b) => $a->bench_order <=> $b->bench_order);

function organize_by_position($players) {
    $organized = ['Goalkeeper' => [], 'Defender' => [], 'Midfielder' => [], 'Forward' => []];
    foreach ($players as $player) {
        $organized[$player->position][] = $player;
    }
    return $organized;
}

function get_player_points($player_id, $points_map) {
    return $points_map[$player_id] ?? 0;
}

// --- Organize Points View Squad ---
$points_starters = [];
$points_bench = [];
$points_captain_id = null;
$points_vice_captain_id = null;

foreach ($points_squad_raw as $player) {
    if ($player->is_starter) $points_starters[] = $player;
    else $points_bench[] = $player;
    
    if ($player->is_captain) $points_captain_id = $player->player_id;
    if ($player->is_vice_captain) $points_vice_captain_id = $player->player_id;
}

// Calculate total for the Points view
$points_view_total = 0;
foreach ($points_starters as $player) {
    $pts = get_player_points($player->player_id, $points_view_player_points);
    
    $is_triple_captain = ($points_view_active_chip === 'TC' && $player->player_id == $points_captain_id);
    if ($player->player_id == $points_captain_id) $pts *= ($is_triple_captain ? 3 : 2);
    $points_view_total += $pts;
}

$points_starters_by_pos = organize_by_position($points_starters);
$starters_by_pos = organize_by_position($starters); // For Pick Team tab

// --- Fetch Fixtures for Opponent Display (Current Gameweek) ---
$gw_fixtures = $fixtureModel->getFixturesByGameweek($selected_league_id, $current_gameweek);
$team_fixture_map = [];
foreach ($gw_fixtures as $f) {
    $home_short = strtoupper(substr($f->home_team_name, 0, 3));
    $away_short = strtoupper(substr($f->away_team_name, 0, 3));
    $team_fixture_map[$f->home_team_id] = ['opp' => $away_short, 'loc' => 'H'];
    $team_fixture_map[$f->away_team_id] = ['opp' => $home_short, 'loc' => 'A'];
}

?>

    <!-- New Fantasy Hero Section -->
    <div class="fantasy-hero-wrapper">
        <div class="fantasy-hero-content">
            <div class="team-identity">
                <div class="team-kit-icon"><i class="fa-solid fa-shirt"></i></div>
                <div class="team-text">
                    <h1 class="team-name"><?php echo htmlspecialchars($user_fantasy_team->name); ?></h1>
                    <span class="manager-name"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Manager'); ?></span>
                </div>
            </div>
            <div class="fantasy-league-selector">
                <form action="fantasy_lineup.php" method="GET" class="selectors-form">
                    <input type="hidden" name="tab" value="<?php echo $active_tab; ?>">
                    <select name="league_id" onchange="this.form.submit()">
                        <?php foreach ($leagues as $league): ?>
                            <option value="<?php echo $league->id; ?>" <?php echo ($league->id == $selected_league_id) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($league->name); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </form>
            </div>
            <div class="gameweek-badge">
                <span class="gw-label">Gameweek</span>
                <span class="gw-number"><?php echo $current_gameweek; ?></span>
            </div>
        </div>
        
        <div class="fantasy-stats-strip">
            <div class="stat-box">
                <span class="label">Total Points</span>
                <span class="value"><?php echo $user_fantasy_team->total_points ?? 0; ?></span>
            </div>
            <div class="stat-box">
                <span class="label">GW Points</span>
                <span class="value"><?php echo $user_fantasy_team->gameweek_points ?? 0; ?></span>
            </div>
            <div class="stat-box">
                <span class="label">Team Value</span>
                <span class="value"><?php echo $currency_symbol . number_format($user_fantasy_team->squad_value, 1); ?>m</span>
            </div>
            <div class="stat-box">
                <span class="label">In Bank</span>
                <span class="value"><?php echo $currency_symbol . number_format($user_fantasy_team->bank, 1); ?>m</span>
            </div>
        </div>

        <div class="fantasy-nav-bar fantasy-tabs">
            <a href="?tab=points&league_id=<?php echo $selected_league_id; ?>" class="nav-tab tab-link <?php echo $active_tab === 'points' ? 'active' : ''; ?>">Points</a>
            <a href="?tab=pitch&league_id=<?php echo $selected_league_id; ?>" class="nav-tab tab-link <?php echo $active_tab === 'pitch' ? 'active' : ''; ?>">Pick Team</a>
            <a href="?tab=transfers&league_id=<?php echo $selected_league_id; ?>" class="nav-tab tab-link <?php echo $active_tab === 'transfers' ? 'active' : ''; ?>">Transfers</a>
            <a href="?tab=leagues&league_id=<?php echo $selected_league_id; ?>" class="nav-tab tab-link <?php echo $active_tab === 'leagues' ? 'active' : ''; ?>">My Leagues</a>
        </div>
    </div>

<div class="page-content" id="fantasy-lineup-page">
    <?php if ($deadline_passed): ?>
        <div class="status-message info" style="background: #e1f5fe; color: #2c3e50; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #29b6f6;">The deadline for Gameweek <?php echo $current_gameweek; ?> has passed. Any changes made now will apply to <strong>Gameweek <?php echo $current_gameweek + 1; ?></strong>.</div>
    <?php endif; ?>

    <div id="pitch" class="tab-content <?php echo $active_tab === 'pitch' ? 'active' : ''; ?>">
        <!-- Gameweek Info Bar (Deadline & Chips) -->
        <div class="gameweek-status-bar">
            <div class="deadline-section">
                <span class="status-label">GW<?php echo $current_gameweek; ?> Deadline:</span>
                <div id="deadline-countdown" data-deadline="<?php echo $deadline_time; ?>">
                    <!-- Countdown JS injects here -->
                </div>
            </div>
            <div class="chips-section">
                <span class="status-label">Chips:</span>
                <div class="chips-list">
                    <?php
                    $tc_played = !is_null($user_fantasy_team->tc_played_gw ?? null);
                    $bb_played = !is_null($user_fantasy_team->bb_played_gw ?? null);
                    $fh_played = !is_null($user_fantasy_team->fh_played_gw ?? null);
                    $wc_played = !is_null($user_fantasy_team->wc_played_gw ?? null);
                    $active_chip = $user_fantasy_team->active_chip ?? null;
                    ?>
                    <button type="button" class="chip-btn <?php echo $bb_played ? 'used' : ($active_chip === 'BB' ? 'active' : ''); ?>" onclick="toggleChip('BB', this)" <?php echo $bb_played ? 'disabled' : ''; ?> title="Bench Boost">BB</button>
                    <button type="button" class="chip-btn <?php echo $tc_played ? 'used' : ($active_chip === 'TC' ? 'active' : ''); ?>" onclick="toggleChip('TC', this)" <?php echo $tc_played ? 'disabled' : ''; ?> title="Triple Captain">TC</button>
                    <button type="button" class="chip-btn <?php echo $fh_played ? 'used' : ($active_chip === 'FH' ? 'active' : ''); ?>" onclick="toggleChip('FH', this)" <?php echo $fh_played ? 'disabled' : ''; ?> title="Free Hit">FH</button>
                    <button type="button" class="chip-btn <?php echo $wc_played ? 'used' : ($active_chip === 'WC' ? 'active' : ''); ?>" onclick="toggleChip('WC', this)" <?php echo $wc_played ? 'disabled' : ''; ?> title="Wildcard">WC</button>
                </div>
            </div>
        </div>

        <div class="lineup-builder-container fantasy-pitch-container">
            <!-- Pitch Area -->
            <div class="pitch-area fantasy-pitch">
                <div class="pitch">
                    <!-- Forwards -->
                    <div class="pitch-row forwards">
                        <?php foreach ($starters_by_pos['Forward'] as $player): ?>
                            <?php echo render_player_card($player, $captain_id, $vice_captain_id, $gameweek_player_points, true, 'pick', $team_fixture_map, $active_chip); ?>
                        <?php endforeach; ?>
                    </div>
                    <!-- Midfielders -->
                    <div class="pitch-row midfielders">
                        <?php foreach ($starters_by_pos['Midfielder'] as $player): ?>
                            <?php echo render_player_card($player, $captain_id, $vice_captain_id, $gameweek_player_points, true, 'pick', $team_fixture_map, $active_chip); ?>
                        <?php endforeach; ?>
                    </div>
                    <!-- Defenders -->
                    <div class="pitch-row defenders">
                        <?php foreach ($starters_by_pos['Defender'] as $player): ?>
                            <?php echo render_player_card($player, $captain_id, $vice_captain_id, $gameweek_player_points, true, 'pick', $team_fixture_map, $active_chip); ?>
                        <?php endforeach; ?>
                    </div>
                    <!-- Goalkeeper -->
                    <div class="pitch-row goalkeeper">
                        <?php foreach ($starters_by_pos['Goalkeeper'] as $player): ?>
                            <?php echo render_player_card($player, $captain_id, $vice_captain_id, $gameweek_player_points, true, 'pick', $team_fixture_map, $active_chip); ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Bench Area -->
            <div class="substitutes-bench-area">
                <h3>Bench</h3>
                <div class="substitutes-bench">
                    <?php foreach ($bench as $player): ?>
                        <?php echo render_player_card($player, $captain_id, $vice_captain_id, $gameweek_player_points, true, 'pick', $team_fixture_map, $active_chip); ?>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="lineup-footer-bar">
            <div style="display: flex; justify-content: space-between; width: 100%; max-width: 600px; margin: 0 auto;">
                <button type="button" id="save-lineup-btn" class="btn" style="width: 100%;">Save Lineup</button>
            </div>
        </div>

        <!-- Hidden Form for Saving Lineup -->
        <form id="save-lineup-form" action="fantasy_lineup_process.php" method="POST">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="league_id" value="<?php echo $selected_league_id; ?>">
            <input type="hidden" name="active_chip" id="active_chip_input" value="<?php echo htmlspecialchars($active_chip ?? ''); ?>">
            <div id="hidden-inputs-container"></div>
        </form>
    </div>

    <div id="points" class="tab-content <?php echo $active_tab === 'points' ? 'active' : ''; ?>">
        <div class="dashboard-section">
            <div class="points-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                <div class="gw-nav-controls" style="display: flex; align-items: center; gap: 10px;">
                    <?php if ($points_view_gameweek > 1): ?><a href="?tab=points&league_id=<?php echo $selected_league_id; ?>&gw=<?php echo $points_view_gameweek - 1; ?>" class="btn-sm btn-secondary"><i class="fa-solid fa-chevron-left"></i></a>
                    <?php endif; ?>
                    <h3 class="dashboard-title" style="margin: 0;">Gameweek <?php echo $points_view_gameweek; ?></h3>
                    <?php if ($points_view_gameweek < $current_gameweek): ?><a href="?tab=points&league_id=<?php echo $selected_league_id; ?>&gw=<?php echo $points_view_gameweek + 1; ?>" class="btn-sm btn-secondary"><i class="fa-solid fa-chevron-right"></i></a>
                    <?php endif; ?>
                </div>
                <div class="gameweek-score" style="background: #37003c; color: #fff; padding: 10px 20px; border-radius: 8px;">
                    <span class="label" style="font-size: 0.8rem; text-transform: uppercase;">GW Score</span>
                    <span class="value" style="font-size: 1.5rem; font-weight: bold; margin-left: 10px;"><?php echo $points_view_total; ?></span>
                </div>
            </div>
            
            <div class="lineup-builder-container fantasy-pitch-container points-view-container">
                <!-- Pitch Area -->
                <div class="pitch-area fantasy-pitch">
                    <div class="pitch">
                        <!-- Forwards -->
                        <div class="pitch-row forwards">
                        <?php foreach ($points_starters_by_pos['Forward'] as $player): ?>
                            <?php echo render_player_card($player, $points_captain_id, $points_vice_captain_id, $points_view_player_points, false, 'points', [], $points_view_active_chip); ?>
                            <?php endforeach; ?>
                        </div>
                        <!-- Midfielders -->
                        <div class="pitch-row midfielders">
                        <?php foreach ($points_starters_by_pos['Midfielder'] as $player): ?>
                            <?php echo render_player_card($player, $points_captain_id, $points_vice_captain_id, $points_view_player_points, false, 'points', [], $points_view_active_chip); ?>
                            <?php endforeach; ?>
                        </div>
                        <!-- Defenders -->
                        <div class="pitch-row defenders">
                        <?php foreach ($points_starters_by_pos['Defender'] as $player): ?>
                            <?php echo render_player_card($player, $points_captain_id, $points_vice_captain_id, $points_view_player_points, false, 'points', [], $points_view_active_chip); ?>
                            <?php endforeach; ?>
                        </div>
                        <!-- Goalkeeper -->
                        <div class="pitch-row goalkeeper">
                        <?php foreach ($points_starters_by_pos['Goalkeeper'] as $player): ?>
                            <?php echo render_player_card($player, $points_captain_id, $points_vice_captain_id, $points_view_player_points, false, 'points', [], $points_view_active_chip); ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Bench Area -->
                <div class="substitutes-bench-area">
                    <h3>Bench</h3>
                    <div class="substitutes-bench">
                        <?php foreach ($points_bench as $player): ?>
                            <?php echo render_player_card($player, $points_captain_id, $points_vice_captain_id, $points_view_player_points, false, 'points', [], $points_view_active_chip); ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="transfers" class="tab-content <?php echo $active_tab === 'transfers' ? 'active' : ''; ?>">
        <?php if ($deadline_passed): ?>
            <div class="status-message info" style="background: #e1f5fe; color: #2c3e50; padding: 10px; border-radius: 8px; margin-bottom: 15px; font-size: 0.9rem; border-left: 4px solid #29b6f6;">
                <i class="fa-solid fa-circle-info"></i> Transfers made now will apply to <strong>Gameweek <?php echo $current_gameweek + 1; ?></strong>.
            </div>
        <?php endif; ?>
        <div class="transfers-header-bar">
            <div class="info-item">
                <span class="info-label">Free Transfers</span>
                <span class="info-value" id="free-transfers-count"><?php echo $user_fantasy_team->free_transfers ?? 1; ?></span>
            </div>
            <div class="info-item">
                <span class="info-label">Cost</span>
                <span class="info-value" id="points-cost">0</span>
            </div>
            <div class="info-item">
                <span class="info-label">Bank</span>
                <span class="info-value" id="transfer-bank-display"><?php echo $currency_symbol . number_format($user_fantasy_team->bank, 1); ?>m</span>
            </div>
        </div>

        <div class="lineup-builder-container fantasy-pitch-container transfer-pitch-container">
            <!-- Pitch Area -->
            <div class="pitch-area fantasy-pitch">
                <div class="pitch">
                    <!-- Forwards -->
                    <div class="pitch-row forwards">
                        <?php foreach ($starters_by_pos['Forward'] as $player): ?>
                            <?php echo render_player_card($player, null, null, [], true, 'transfer'); ?>
                        <?php endforeach; ?>
                    </div>
                    <!-- Midfielders -->
                    <div class="pitch-row midfielders">
                        <?php foreach ($starters_by_pos['Midfielder'] as $player): ?>
                            <?php echo render_player_card($player, null, null, [], true, 'transfer'); ?>
                        <?php endforeach; ?>
                    </div>
                    <!-- Defenders -->
                    <div class="pitch-row defenders">
                        <?php foreach ($starters_by_pos['Defender'] as $player): ?>
                            <?php echo render_player_card($player, null, null, [], true, 'transfer'); ?>
                        <?php endforeach; ?>
                    </div>
                    <!-- Goalkeeper -->
                    <div class="pitch-row goalkeeper">
                        <?php foreach ($starters_by_pos['Goalkeeper'] as $player): ?>
                            <?php echo render_player_card($player, null, null, [], true, 'transfer'); ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Bench Area -->
            <div class="substitutes-bench-area">
                <h3>Bench</h3>
                <div class="substitutes-bench">
                    <?php foreach ($bench as $player): ?>
                        <?php echo render_player_card($player, null, null, [], true, 'transfer'); ?>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="transfers-footer-bar">
            <div class="transfers-summary">
                <span>Transfers: <strong id="transfers-count">0</strong></span>
            </div>
            <button type="button" id="reset-transfers-btn" class="btn btn-secondary">Reset</button>
            <button type="button" id="confirm-transfers-btn" class="btn" disabled>Make Transfers</button>
        </div>
    </div>

    <div id="leagues" class="tab-content <?php echo $active_tab === 'leagues' ? 'active' : ''; ?>">
        <div class="dashboard-section">
            <div class="leagues-header-row">
                <h3 class="dashboard-title">My Leagues</h3>
                <div class="league-buttons">
                    <a href="fantasy_leagues.php?mode=create&league_id=<?php echo $selected_league_id; ?>" class="btn-sm btn-primary"><i class="fa-solid fa-plus"></i> Create League</a>
                    <a href="fantasy_leagues.php?mode=join&league_id=<?php echo $selected_league_id; ?>" class="btn-sm btn-outline"><i class="fa-solid fa-sign-in-alt"></i> Join League</a>
                </div>
            </div>
            
            <div class="leagues-grid-container">
                <?php foreach ($leagues_data as $league): ?>
                    <a href="<?php echo $league['url']; ?>" class="league-card">
                        <div class="league-icon">
                            <i class="fa-solid fa-trophy"></i>
                        </div>
                        <div class="league-details">
                            <h4 class="league-name"><?php echo htmlspecialchars($league['name']); ?></h4>
                            <div class="league-rank-badge">
                                <span class="rank-label">Rank</span>
                                <span class="rank-value">#<?php echo $league['rank']; ?></span>
                            </div>
                        </div>
                        <div class="league-arrow">
                            <i class="fa-solid fa-chevron-right"></i>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- Transfer Market Modal -->
<div id="transfer-market-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="transfer-modal-title">Select Replacement</h3>
            <button type="button" class="modal-close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <div class="filters-container" style="display: flex; gap: 10px; margin-bottom: 15px; flex-wrap: wrap;">
                <div style="flex: 1; min-width: 120px;">
                    <select id="transfer-filter-position" class="player-search-input" style="margin-bottom: 0;" disabled>
                        <option value="Goalkeeper">Goalkeeper</option>
                        <option value="Defender">Defender</option>
                        <option value="Midfielder">Midfielder</option>
                        <option value="Forward">Forward</option>
                    </select>
                </div>
                <div style="flex: 1; min-width: 120px;">
                    <select id="transfer-filter-club" class="player-search-input" style="margin-bottom: 0;"><option value="">All Clubs</option></select>
                </div>
                <div style="flex: 1; min-width: 100px;">
                    <input type="number" id="transfer-filter-max-price" class="player-search-input" placeholder="Max Price" step="0.1" style="margin-bottom: 0;">
                </div>
            </div>
            <input type="text" id="transfer-player-search" placeholder="Search player..." class="player-search-input">
            <div id="transfer-player-list" class="modal-player-list"></div>
        </div>
    </div>
</div>

<!-- Player Action Modal -->
<div id="player-action-modal" class="modal">
    <div class="modal-content" style="max-width: 350px;">
        <div class="modal-header">
            <h3 id="action-modal-title">Player Options</h3>
            <button type="button" class="modal-close-btn">&times;</button>
        </div>
        <div class="modal-body action-options">
            <div class="player-info-summary" style="text-align: center; margin-bottom: 1rem;">
                <!-- Populated by JS -->
            </div>
            <button type="button" class="btn btn-block" id="action-sub-btn">
                <i class="fa-solid fa-right-left"></i> Switch / Substitute
            </button>
            <div class="captain-btn-group" style="display: flex; gap: 10px; margin-top: 10px;">
                <button type="button" class="btn btn-secondary" style="flex: 1;" id="action-captain-btn">
                    <i class="fa-solid fa-copyright"></i> Make Captain
                </button>
                <button type="button" class="btn btn-secondary" style="flex: 1;" id="action-vice-btn">
                    <i class="fa-solid fa-v"></i> Make Vice
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Points Breakdown Modal -->
<div id="points-breakdown-modal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3 id="breakdown-modal-title">Points Breakdown</h3>
            <button type="button" class="modal-close-btn">&times;</button>
        </div>
        <div class="modal-body" id="breakdown-modal-body">
            <!-- Content injected by JS -->
            <div style="text-align:center; padding: 20px;"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>
        </div>
    </div>
</div>

<!-- Generic Confirmation Modal -->
<div id="generic-confirmation-modal" class="modal">
    <div class="modal-content" style="max-width: 400px; text-align: center;">
        <div class="modal-header" style="justify-content: center; border-bottom: none; padding-bottom: 0;">
            <h3 id="confirmation-title">Confirm Action</h3>
        </div>
        <div class="modal-body">
            <p id="confirmation-text" style="margin-bottom: 20px; color: #666;">Are you sure?</p>
            <div class="modal-actions" style="display: flex; gap: 10px; justify-content: center;">
                <button type="button" class="btn btn-secondary modal-close-btn-action">Cancel</button>
                <button type="button" id="confirmation-confirm-btn" class="btn">Confirm</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div id="toast-container"></div>

<style>
/* === Fantasy Lineup Styles === */
.tab-content {
    display: none;
}
.tab-content.active {
    display: block;
}

/* Transparent Header Override */
header {
    background: transparent !important;
    box-shadow: none !important;
    position: absolute;
    width: 100%;
    top: 0;
    z-index: 1000;
}
.fantasy-league-selector {
    position: absolute;
    top: 15px;
    right: 20px;
}
.fantasy-league-selector select {
    background: rgba(255,255,255,0.2);
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 0.9rem;
    cursor: pointer;
    outline: none;
}

.fantasy-hero-wrapper {
    background: linear-gradient(135deg, <?php echo $primary_color; ?> 0%, <?php echo $secondary_color; ?> 100%);
    color: white;
    padding: 6rem 20px 3rem 20px;
    border-radius: 0 0 30px 30px;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
.fantasy-hero-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.team-identity {
    display: flex;
    align-items: center;
    gap: 15px;
}
.team-kit-icon {
    font-size: 2.5rem;
    background: rgba(255,255,255,0.1);
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}
.team-text h1 { margin: 0; font-size: 1.5rem; }
.manager-name { opacity: 0.8; font-size: 0.9rem; }
.gameweek-badge {
    text-align: center;
    background: rgba(255,255,255,0.1);
    padding: 5px 15px;
    border-radius: 8px;
}
.gw-label { display: block; font-size: 0.7rem; text-transform: uppercase; }
.gw-number { font-size: 1.5rem; font-weight: bold; }

.fantasy-stats-strip {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    overflow-x: auto;
}
.fantasy-stats-strip .stat-box {
    background: rgba(255,255,255,0.1);
    padding: 10px 15px;
    border-radius: 8px;
    flex: 1;
    min-width: 100px;
    text-align: center;
}
.fantasy-stats-strip .label { display: block; font-size: 0.7rem; opacity: 0.8; }
.fantasy-stats-strip .value { font-size: 1.1rem; font-weight: bold; }

.fantasy-nav-bar {
    display: flex;
    gap: 5px;
    background: rgba(0,0,0,0.2);
    padding: 5px;
    border-radius: 30px;
}
.nav-tab {
    flex: 1;
    text-align: center;
    padding: 8px 15px;
    color: rgba(255,255,255,0.7);
    text-decoration: none;
    border-radius: 25px;
    font-size: 0.9rem;
    transition: all 0.2s;
}
.nav-tab:hover { color: white; background: rgba(255,255,255,0.1); }
.nav-tab.active { background: #00ff85; color: #37003c; font-weight: bold; }

/* Gameweek Status Bar */
.gameweek-status-bar {
    background: #fff;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    flex-wrap: wrap;
    gap: 10px;
}
.deadline-section, .chips-section { display: flex; align-items: center; gap: 10px; }
.status-label { font-weight: bold; color: #555; font-size: 0.9rem; }
#deadline-countdown { display: flex; gap: 5px; }
.countdown-item { background: #37003c; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.8rem; }
.countdown-item span { font-weight: bold; margin-right: 2px; }
.chips-list { display: flex; gap: 5px; }
.chip-btn {
    border: 1px solid #ddd;
    background: #f9f9f9;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.75rem;
    cursor: pointer;
}
.chip-btn.active {
    background-color: #37003c;
    color: #fff;
    border-color: #37003c;
}
.chip-btn.used { opacity: 0.5; cursor: not-allowed; text-decoration: line-through; }
.chip-btn:hover:not(.used):not(.active) { background-color: #e0e0e0; }

/* Pitch */
.pitch-area {
    background-image: url('<?php echo URL_ROOT; ?>/public/assets/images/pitch.svg');
    background-size: cover;
    background-position: center;
    background-color: #27ae60;
    border-radius: 8px;
    padding: 20px 10px;
    min-height: 600px;
    position: relative;
    border: 2px solid #fff;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}
.pitch {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    min-height: 550px;
}
.pitch-row {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 10px;
}

/* Player Card on Pitch */
.player-slot {
    position: relative;
    width: 18%;
    max-width: 90px;
    cursor: pointer;
    transition: transform 0.2s;
}
.player-slot:hover { transform: scale(1.05); z-index: 10; }
.player-slot.selected .player-card,
.player-slot.sub-out .player-card {
    background-color: rgba(231, 76, 60, 0.8);
    border-radius: 6px;
    border: 2px solid #c0392b;
}
.player-slot.sub-in-target .player-card {
    background-color: rgba(46, 204, 113, 0.8);
    border-radius: 6px;
    border: 2px solid #27ae60;
    cursor: pointer;
}
.player-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
}
.player-image-frame {
    position: relative;
    width: 50px;
    height: 50px;
    margin-bottom: 5px;
}
.player-image-frame img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #fff;
    background: #fff;
}
.captain-badge {
    position: absolute;
    bottom: -2px;
    right: -2px;
    background: #37003c;
    color: white;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    font-size: 0.7rem;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    border: 1px solid #fff;
}
.captain-badge.vice { background: #aaa; color: #333; }
.fixture-badge {
    position: absolute;
    top: -5px;
    left: 50%;
    transform: translateX(-50%);
    background: #fff;
    color: #333;
    font-size: 0.6rem;
    padding: 1px 4px;
    border-radius: 4px;
    white-space: nowrap;
    box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}
.auto-sub-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background: #e67e22;
    color: white;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    font-size: 0.6rem;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #fff;
    z-index: 5;
}
.player-info-block {
    background: rgba(55, 0, 60, 0.9);
    color: white;
    width: 100%;
    border-radius: 4px;
    overflow: hidden;
}
.player-name-row {
    font-size: 0.7rem;
    padding: 2px 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    background: #37003c;
}
.player-stats-row {
    display: flex;
    justify-content: space-between;
    padding: 2px 4px;
    font-size: 0.7rem;
    background: rgba(255,255,255,0.1);
}
.pos-tag { opacity: 0.8; font-size: 0.6rem; }

/* Bench */
.substitutes-bench-area {
    margin-top: 20px;
    background: #f0f2f5;
    padding: 15px;
    border-radius: 8px;
}
.substitutes-bench-area h3 { margin: 0 0 10px 0; font-size: 1rem; color: #555; }
.substitutes-bench {
    display: flex;
    justify-content: center;
    gap: 10px;
}
.substitutes-bench .player-slot { width: 70px; }
.substitutes-bench .player-info-block { background: #888; }
.substitutes-bench .player-name-row { background: #666; }

/* Footer Bar */
.lineup-footer-bar {
    position: sticky;
    bottom: 0;
    background: #fff;
    padding: 15px;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
    text-align: center;
    z-index: 900;
}

/* Transfers Specific */
.transfers-header-bar {
    display: flex;
    justify-content: space-around;
    background: #37003c;
    color: white;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}
.transfers-header-bar .info-item { text-align: center; }
.transfers-header-bar .info-label { display: block; font-size: 0.7rem; opacity: 0.8; }
.transfers-header-bar .info-value { font-size: 1.2rem; font-weight: bold; }

.transfer-player-slot .player-info-block { background: #fff; color: #333; border: 1px solid #ddd; }
.transfer-player-slot .player-name-row { background: #f9f9f9; color: #333; }
.transfer-player-slot .player-stats-row { background: #fff; color: #333; }
.transfer-player-slot.selected-for-transfer .player-image-frame { border-color: #e74c3c; box-shadow: 0 0 10px #e74c3c; }

.transfers-footer-bar {
    position: sticky;
    bottom: 0;
    background: #fff;
    padding: 15px;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    z-index: 900;
}

/* Leagues */
.leagues-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
.leagues-grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 15px;
}
.league-card {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    text-decoration: none;
    color: inherit;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    transition: transform 0.2s;
    border: 1px solid #eee;
}
.league-card:hover { transform: translateY(-3px); border-color: #37003c; }
.league-icon {
    width: 50px;
    height: 50px;
    background: #f0f2f5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: #37003c;
}
.league-details { flex: 1; }
.league-name { margin: 0 0 5px 0; font-size: 1.1rem; }
.league-rank-badge { font-size: 0.85rem; color: #555; }
.league-rank-badge .rank-value { font-weight: bold; color: #37003c; }
.league-arrow { color: #ccc; }

/* Modals */
.modal,
.modal-overlay {
    display: none;
    /* Hidden by default */
    position: fixed;
    z-index: 2000;
    /* High z-index to sit on top of everything */
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    /* Prevent body scroll */
    background-color: rgba(0, 0, 0, 0.5);
    /* Flexbox centering */
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    pointer-events: none;
}

.modal.show,
.modal-overlay[style*="display: flex"] {
    display: flex !important;
    opacity: 1;
    pointer-events: auto;
}

.modal-content {
    background-color: #fff;
    margin: auto;
    padding: 25px;
    border: none;
    width: 90%;
    max-width: 500px;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
    position: relative;
    max-height: 90vh;
    overflow-y: auto;
    transform: scale(0.95);
    transition: transform 0.3s ease;
}

.modal.show .modal-content,
.modal-overlay[style*="display: flex"] .modal-content {
    transform: scale(1);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
}

.modal-close-btn {
    background: none;
    border: none;
    font-size: 1.5rem;
    line-height: 1;
    color: #999;
    cursor: pointer;
    transition: color 0.2s;
    padding: 0;
}

.modal-close-btn:hover {
    color: #333;
}

.btn-block {
    width: 100%;
    display: block;
    margin-top: 10px;
}

.modal-player-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #eee;
}

.modal-player-item:hover {
    background-color: #f0f4f8;
}

.player-info {
    display: flex;
    align-items: center;
}

.modal-player-img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 10px;
}

.modal-player-photo {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    margin-bottom: 10px;
    border: 3px solid #eee;
}
.player-modal-stats {
    display: flex;
    justify-content: space-around;
    text-align: center;
    background: #f8f9fa;
    padding: 10px;
    border-radius: 8px;
    margin-top: 1rem;
}
.player-modal-stats div span { display: block; font-size: 0.75rem; color: #666; }
.player-modal-stats div strong { font-size: 1rem; }

/* --- Toast Notification Styles --- */
#toast-container {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 10000;
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.toast {
    background-color: #333;
    color: #fff;
    padding: 12px 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    opacity: 1;
    transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
    transform: translateY(0);
    min-width: 250px;
    display: flex;
    align-items: center;
    font-size: 0.95rem;
}
.toast.hide {
    opacity: 0;
    transform: translateY(20px);
}
.toast-success { background-color: #28a745; }
.toast-error { background-color: #dc3545; }
.toast-info { background-color: #17a2b8; }

/* Points Breakdown Styles */
.points-player-slot {
    cursor: pointer;
}
.match-breakdown-card {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    border: 1px solid #eee;
}
.match-breakdown-card:last-child { margin-bottom: 0; }
.match-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    border-bottom: 1px solid #e0e0e0;
    padding-bottom: 8px;
    margin-bottom: 10px;
    font-size: 0.9rem;
}
.match-points-badge { background: #37003c; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8rem; }
.points-list { list-style: none; padding: 0; margin: 0; }
.points-list li { display: flex; justify-content: space-between; padding: 4px 0; font-size: 0.9rem; color: #555; }
.points-list li span:last-child { font-weight: bold; color: #333; }

.player-slot.auto-sub-in .player-image-frame img {
    border-color: #e67e22;
    box-shadow: 0 0 8px rgba(230, 126, 34, 0.6);
}
</style>

<?php
function render_player_card($player, $captain_id, $vice_captain_id, $points_map, $is_interactive = true, $mode = 'points', $fixtures_map = [], $active_chip = null) {
    global $currency_symbol;
    $captain_badge = '';
    if ($mode !== 'transfer' && $player->player_id == $captain_id) {
        if ($active_chip === 'TC') {
            $captain_badge = '<span class="captain-badge triple-captain">3x</span>';
        } else {
            $captain_badge = '<span class="captain-badge">C</span>';
        }
    } elseif ($mode !== 'transfer' && $player->player_id == $vice_captain_id) {
        $captain_badge = '<span class="captain-badge vice">V</span>';
    }

    $bottom_label = '';
    if ($mode === 'transfer') {
        $bottom_label = "<span class='player-price-label'>{$currency_symbol}" . number_format($player->fantasy_price, 1) . "m</span>";
    } else {
        $points = get_player_points($player->player_id, $points_map);
        if ($player->player_id == $captain_id) $points *= 2;
        $bottom_label = "<span class='player-points-label'>{$points}</span>";
    }

    $fixture_badge = '';
    if ($mode === 'pick' && isset($fixtures_map[$player->team_id])) {
        $fix = $fixtures_map[$player->team_id];
        $fixture_badge = "<div class='fixture-badge'>{$fix['opp']} ({$fix['loc']})</div>";
    }

    $is_auto_sub = !empty($player->is_auto_sub);
    $auto_sub_icon = '';
    if ($is_auto_sub) {
        $auto_sub_icon = '<div class="auto-sub-badge" title="Automatic Substitution"><i class="fa-solid fa-rotate"></i></div>';
    }

    $image_src = !empty($player->profile_picture) ? htmlspecialchars($player->profile_picture) : htmlspecialchars($player->club_logo);
    $slot_class = $is_interactive ? 'fantasy-player-slot' : 'points-player-slot';
    if ($mode === 'transfer') $slot_class = 'transfer-player-slot';
    if ($is_auto_sub) $slot_class .= ' auto-sub-in';
    
    // Position mapping
    $pos_map = ['Goalkeeper' => 'GK', 'Defender' => 'DEF', 'Midfielder' => 'MID', 'Forward' => 'FWD'];
    $short_pos = $pos_map[$player->position] ?? substr($player->position, 0, 3);
    $short_pos = strtoupper($short_pos);
    
    $output = "
    <div class='player-slot {$slot_class}' data-player-id='{$player->player_id}' data-position='{$player->position}' data-is-starter='" . ($player->is_starter ? '1' : '0') . "'>
        <div class='player-card'>
            <div class='player-image-frame'>
                <img src='{$image_src}' alt='Player'>
                {$captain_badge}
                {$fixture_badge}
                {$auto_sub_icon}
            </div>
            <div class='player-info-block'>
                <div class='player-name-row'>" . htmlspecialchars($player->last_name) . "</div>
                <div class='player-stats-row'>
                    <span class='pos-tag'>{$short_pos}</span>
                    {$bottom_label}
                </div>
            </div>
        </div>
    </div>";
    return $output;
}
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const lineupPage = document.getElementById('fantasy-lineup-page');
    if (!lineupPage) return;

    const deadlinePassed = <?php echo json_encode($deadline_passed); ?>;
    const deadlineCountdownEl = document.getElementById('deadline-countdown');
    
    const teamFixtureMap = <?php echo json_encode($team_fixture_map); ?>;
    const squadData = <?php echo json_encode($squad_js); ?>;
    // Transfers Variables
    const allPlayersData = <?php echo json_encode($all_players_js); ?>;
    // Use integers (x10) for money to avoid floating point issues
    const initialBank = Math.round(parseFloat(<?php echo $user_fantasy_team->bank; ?>) * 10);
    const freeTransfersAvailable = <?php echo $user_fantasy_team->free_transfers ?? 1; ?>;
    const currencySymbol = '<?php echo $currency_symbol; ?>';
    let bank = initialBank;
    let pendingTransfers = [];
    let playerToRemove = null;
    
    // Transfer Modal Elements
    const transferModal = document.getElementById('transfer-market-modal');
    const transferPlayerList = document.getElementById('transfer-player-list');
    const transferSearchInput = document.getElementById('transfer-player-search');
    const filterPosition = document.getElementById('transfer-filter-position');
    const filterClub = document.getElementById('transfer-filter-club');
    const filterMaxPrice = document.getElementById('transfer-filter-max-price');
    
    // State for substitution
    let swapSource = null;
    
    // Modal Elements
    const actionModal = document.getElementById('player-action-modal');
    const actionModalTitle = document.getElementById('action-modal-title');
    const actionModalClose = actionModal.querySelector('.modal-close-btn');
    let actionTargetSlot = null;

    // Confirmation Modal Elements
    const confirmModal = document.getElementById('generic-confirmation-modal');
    const confirmTitle = document.getElementById('confirmation-title');
    const confirmText = document.getElementById('confirmation-text');
    const confirmBtn = document.getElementById('confirmation-confirm-btn');
    const confirmCancelBtns = confirmModal.querySelectorAll('.modal-close-btn-action');
    let onConfirmCallback = null;
    
    // Points Breakdown Modal Elements
    const pointsModal = document.getElementById('points-breakdown-modal');
    const pointsModalBody = document.getElementById('breakdown-modal-body');
    const pointsModalTitle = document.getElementById('breakdown-modal-title');

    function showConfirmation(title, text, callback) {
        confirmTitle.textContent = title;
        confirmText.textContent = text;
        onConfirmCallback = callback;
        confirmModal.classList.add('show');
    }

    // --- Toast Notification Logic ---
    const toastContainer = document.getElementById('toast-container');

    function showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        toastContainer.appendChild(toast);
        setTimeout(() => {
            toast.classList.add('hide');
            toast.addEventListener('transitionend', () => toast.remove());
        }, 3000);
    }

    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('lineup_status') && urlParams.get('lineup_status') === 'success') {
        showToast('Lineup updated successfully!', 'success');
    } else if (urlParams.has('transfers_status') && urlParams.get('transfers_status') === 'success') {
        showToast('Transfers confirmed successfully!', 'success');
    } else if (urlParams.has('lineup_status') && urlParams.get('lineup_status') === 'error') {
        const reason = urlParams.get('reason') || 'Failed to save lineup.';
        showToast(reason, 'error');
    } else if (urlParams.has('error')) {
        showToast(urlParams.get('error'), 'error');
    }

    // Clean URL
    const newUrl = new URL(window.location);
    newUrl.searchParams.delete('lineup_status');
    newUrl.searchParams.delete('transfers_status');
    newUrl.searchParams.delete('error');
    window.history.replaceState({}, document.title, newUrl);

    // --- Confirmation Modal Listeners ---
    confirmBtn.addEventListener('click', function() {
        if (onConfirmCallback) onConfirmCallback();
        confirmModal.classList.remove('show');
    });
    confirmCancelBtns.forEach(btn => btn.addEventListener('click', () => confirmModal.classList.remove('show')));
    window.addEventListener('click', (e) => {
        if (e.target === confirmModal) confirmModal.classList.remove('show');
    });

    // --- Points Modal Close Logic ---
    if (pointsModal) {
        pointsModal.querySelector('.modal-close-btn').addEventListener('click', () => pointsModal.classList.remove('show'));
        window.addEventListener('click', (e) => { if (e.target === pointsModal) pointsModal.classList.remove('show'); });
    }

    // --- Points Breakdown Logic ---
    const pointsViewGameweek = <?php echo $points_view_gameweek; ?>;
    
    document.querySelectorAll('.points-player-slot').forEach(slot => {
        slot.addEventListener('click', function() {
            const playerId = this.dataset.playerId;
            const playerName = this.querySelector('.player-name-row').textContent;
            
            pointsModalTitle.textContent = `${playerName} - GW${pointsViewGameweek}`;
            pointsModalBody.innerHTML = '<div style="text-align:center; padding: 20px;"><i class="fa-solid fa-spinner fa-spin"></i> Loading...</div>';
            pointsModal.classList.add('show');

            fetch(`api/get_points_breakdown.php?player_id=${playerId}&gameweek=${pointsViewGameweek}`)
                .then(res => res.json())
                .then(data => {
                    if (data.error) {
                        pointsModalBody.innerHTML = `<p class="error-msg" style="color:red; text-align:center;">${data.error}</p>`;
                        return;
                    }
                    if (data.length === 0) {
                        pointsModalBody.innerHTML = '<p style="text-align:center; color:#666;">No points data available for this gameweek.</p>';
                        return;
                    }
                    
                    let html = '';
                    data.forEach(match => {
                        html += `
                            <div class="match-breakdown-card">
                                <div class="match-header">
                                    <span>${match.home_team_name} ${match.home_team_score} - ${match.away_team_score} ${match.away_team_name}</span>
                                    <span class="match-points-badge">${match.points} Pts</span>
                                </div>
                                <ul class="points-list">
                        `;
                        
                        const breakdown = match.breakdown || {};
                        const labels = {
                            'minutes': 'Minutes Played', 'goals': 'Goals', 'assists': 'Assists',
                            'clean_sheet': 'Clean Sheet', 'goals_conceded': 'Goals Conceded',
                            'cards': 'Cards', 'pen_save': 'Penalty Saved', 'pen_miss': 'Penalty Missed',
                            'bonus': 'Bonus'
                        };

                        for (const [key, value] of Object.entries(breakdown)) {
                            if (value !== 0) {
                                html += `<li><span>${labels[key] || key}</span> <span>${value > 0 ? '+' : ''}${value}</span></li>`;
                            }
                        }
                        html += `</ul></div>`;
                    });
                    pointsModalBody.innerHTML = html;
                })
                .catch(err => {
                    pointsModalBody.innerHTML = '<p class="error-msg" style="color:red; text-align:center;">Failed to load data.</p>';
                });
        });
    });

    // --- Click Handler for Players ---
    lineupPage.addEventListener('click', function(e) {
        const targetSlot = e.target.closest('.fantasy-player-slot');
        if (!targetSlot) return;

        if (deadlinePassed) {
            showToast("Gameweek is live. Lineup is locked.", "info");
            return;
        }

        if (swapSource) {
            // We are in swap mode, execute swap
            executeSwap(swapSource, targetSlot);
            clearSwapVisuals();
        } else {
            // Open action modal
            openActionModal(targetSlot);
        }
    });

    function openActionModal(slot) {
        actionTargetSlot = slot;
        const playerId = slot.dataset.playerId;
        const playerData = squadData[playerId];
        if (!playerData) return;

        const summaryDiv = actionModal.querySelector('.player-info-summary');
        const fixtureInfo = teamFixtureMap[playerData.team_id];
        let fixtureHTML = 'No upcoming match';
        if (fixtureInfo) {
            fixtureHTML = `${fixtureInfo.opp} (${fixtureInfo.loc})`;
        }

        summaryDiv.innerHTML = `
            <img src="${playerData.profile_picture || '<?php echo URL_ROOT; ?>/public/assets/images/default_avatar.png'}" alt="Player" class="modal-player-photo">
            <h4>${playerData.name}</h4>
            <p>${playerData.position} | ${playerData.club_name}</p>
            <div class="player-modal-stats">
                <div><span>Value</span><strong>${currencySymbol}${playerData.price.toFixed(1)}m</strong></div>
                <div><span>Next Match</span><strong>${fixtureHTML}</strong></div>
                <div><span>Last GW</span><strong>${playerData.points} Pts</strong></div>
            </div>
        `;
        actionModalTitle.textContent = "Player Options";
        actionModal.classList.add('show');
    }

    function closeActionModal() {
        actionModal.classList.remove('show');
        actionTargetSlot = null;
    }

    actionModalClose.onclick = closeActionModal;
    window.onclick = (e) => { if (e.target === actionModal) closeActionModal(); };

    // --- Action Buttons ---
    document.getElementById('action-sub-btn').onclick = function() {
        if (!actionTargetSlot) return;
        swapSource = actionTargetSlot;
        
        // Visual Indicators logic
        swapSource.classList.add('sub-out');
        highlightValidTargets(swapSource);
        
        closeActionModal();
    };

    document.getElementById('action-captain-btn').onclick = () => { setCaptaincy(actionTargetSlot, 'C'); closeActionModal(); };
    document.getElementById('action-vice-btn').onclick = () => { setCaptaincy(actionTargetSlot, 'V'); closeActionModal(); };

    function highlightValidTargets(sourceSlot) {
        const sourcePos = sourceSlot.dataset.position;
        const allSlots = document.querySelectorAll('.fantasy-player-slot');

        allSlots.forEach(slot => {
            if (slot === sourceSlot) return;

            const targetPos = slot.dataset.position;
            
            // Logic: GK can only swap with GK. Outfield can swap with any Outfield.
            if (sourcePos === 'Goalkeeper') {
                if (targetPos === 'Goalkeeper') slot.classList.add('sub-in-target');
            } else {
                // Source is outfield
                if (targetPos !== 'Goalkeeper') slot.classList.add('sub-in-target');
            }
        });
    }

    // --- Swap Logic ---
    function executeSwap(source, target) {
        // Clear selection style
        source.classList.remove('selected');
        swapSource = null;

        if (source === target) return; // Clicked same player, cancel swap

        const sourceIsStarter = source.dataset.isStarter === '1';
        const targetIsStarter = target.dataset.isStarter === '1';
        const sourcePos = source.dataset.position;
        const targetPos = target.dataset.position;

        // Case 1: Both on Pitch (Prevent swap)
        if (sourceIsStarter && targetIsStarter) {
            showToast("You cannot swap two players who are already on the pitch.", "error");
            return;
        }

        // Case 2: Both on Bench (Allow reorder)
        if (!sourceIsStarter && !targetIsStarter) {
            // Simple DOM swap for visual reordering
            const parent = source.parentNode;
            const next = (target.nextSibling === source) ? target : target.nextSibling;
            parent.insertBefore(source, next);
            return;
        }

        // Case 3: Pitch <-> Bench (Substitution)
        // Validate Formation Constraints
        // We need to simulate the swap and check counts
        
        // Calculate current counts
        const currentCounts = { 'Goalkeeper': 0, 'Defender': 0, 'Midfielder': 0, 'Forward': 0 };
        document.querySelectorAll('.pitch .fantasy-player-slot').forEach(s => currentCounts[s.dataset.position]++);

        // Adjust counts based on the proposed swap
        // One is coming OFF (starter), one is coming ON (sub)
        const playerOff = sourceIsStarter ? source : target;
        const playerOn = sourceIsStarter ? target : source;

        // GK Check: Must swap GK for GK
        if (playerOff.dataset.position === 'Goalkeeper' && playerOn.dataset.position !== 'Goalkeeper') {
            showToast("Goalkeeper must be swapped with another Goalkeeper.", "error");
            return;
        }
        if (playerOff.dataset.position !== 'Goalkeeper' && playerOn.dataset.position === 'Goalkeeper') {
            showToast("Outfield player cannot be swapped with a Goalkeeper.", "error");
            return;
        }

        // Update counts
        currentCounts[playerOff.dataset.position]--;
        currentCounts[playerOn.dataset.position]++;

        // Validate Constraints
        if (currentCounts['Goalkeeper'] !== 1) { showToast("Invalid formation: Must have 1 Goalkeeper.", "error"); return; }
        if (currentCounts['Defender'] < 3) { showToast("Invalid formation: Must have at least 3 Defenders.", "error"); return; }
        if (currentCounts['Midfielder'] < 2) { showToast("Invalid formation: Must have at least 2 Midfielders.", "error"); return; }
        if (currentCounts['Forward'] < 1) { showToast("Invalid formation: Must have at least 1 Forward.", "error"); return; }

        // If valid, perform the DOM move
        performDomMove(playerOff, playerOn);
    }

    function performDomMove(playerOff, playerOn) {
        // 1. Identify containers
        const pitchContainerClass = getPitchRowClass(playerOn.dataset.position);
        const pitchContainer = document.querySelector(`.pitch .${pitchContainerClass}`);
        const benchContainer = document.querySelector('.substitutes-bench');

        // 2. Update Data Attributes
        playerOff.dataset.isStarter = '0';
        playerOn.dataset.isStarter = '1';

        // 3. Move Elements
        // Move playerOff to bench
        benchContainer.appendChild(playerOff);
        // Move playerOn to pitch row
        pitchContainer.appendChild(playerOn);
    }

    function getPitchRowClass(position) {
        switch(position) {
            case 'Goalkeeper': return 'goalkeeper';
            case 'Defender': return 'defenders';
            case 'Midfielder': return 'midfielders';
            case 'Forward': return 'forwards';
            default: return '';
        }
    }

    function clearSwapVisuals() {
        document.querySelectorAll('.fantasy-player-slot').forEach(slot => {
            slot.classList.remove('sub-out', 'sub-in-target');
        });
    }

    // Deselect if clicking outside
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.fantasy-player-slot') && !e.target.closest('.modal') && swapSource) {
            swapSource.classList.remove('selected');
            swapSource = null;
            clearSwapVisuals();
        }
    });

    // --- Captaincy Logic ---
    function setCaptaincy(targetSlot, type) {
        if (targetSlot.dataset.isStarter !== '1') {
            showToast("Only players on the pitch can be captain or vice-captain.", "error");
            return;
        }

        const badgeClass = type === 'C' ? '' : 'vice';
        const badgeSelector = `.captain-badge${type === 'C' ? ':not(.vice)' : '.vice'}`;

        // Remove existing badge of this type
        const existingBadge = document.querySelector(badgeSelector);
        if (existingBadge) existingBadge.remove();

        // Add new badge
        const shirt = targetSlot.querySelector('.player-image-frame');
        const newBadge = document.createElement('span');
        newBadge.className = `captain-badge ${badgeClass}`;
        newBadge.textContent = type;
        shirt.appendChild(newBadge);
    }

    // --- Chip Toggle Logic ---
    window.toggleChip = function(chip, btn) {
        const input = document.getElementById('active_chip_input');
        
        // If clicking the already active chip, deselect it
        if (input.value === chip) {
            input.value = '';
            btn.classList.remove('active');
        } else {
            // Deselect others
            document.querySelectorAll('.chip-btn').forEach(b => b.classList.remove('active'));
            
            // Select new
            input.value = chip;
            btn.classList.add('active');
        }
    };

    // --- Form Submission ---
    const saveLineupBtn = document.getElementById('save-lineup-btn');
    
    if (deadlinePassed && saveLineupBtn) {
        saveLineupBtn.disabled = true;
        saveLineupBtn.style.opacity = '0.5';
        saveLineupBtn.style.cursor = 'not-allowed';
    }

    saveLineupBtn.addEventListener('click', function(e) {
        const hiddenInputsContainer = document.getElementById('hidden-inputs-container');
        hiddenInputsContainer.innerHTML = '';

        const starters = [];
        const bench = [];
        let captain = null;
        let vice_captain = null;

        document.querySelectorAll('.fantasy-pitch .fantasy-player-slot').forEach(slot => {
            starters.push(slot.dataset.playerId);
            const cBadge = slot.querySelector('.captain-badge:not(.vice)');
            const vBadge = slot.querySelector('.captain-badge.vice');
            if (cBadge) captain = slot.dataset.playerId;
            if (vBadge) vice_captain = slot.dataset.playerId;
        });

        document.querySelectorAll('.substitutes-bench .fantasy-player-slot').forEach(slot => {
            bench.push(slot.dataset.playerId);
        });

        // Create hidden inputs
        starters.forEach(id => hiddenInputsContainer.appendChild(createHiddenInput('starters[]', id)));
        bench.forEach(id => hiddenInputsContainer.appendChild(createHiddenInput('bench[]', id)));
        if(captain) hiddenInputsContainer.appendChild(createHiddenInput('captain', captain));
        if(vice_captain) hiddenInputsContainer.appendChild(createHiddenInput('vice_captain', vice_captain));

        showConfirmation('Save Lineup', 'Are you sure you want to save your changes?', function() {
            const form = document.getElementById('save-lineup-form');
            form.submit();
        });
    });

    function createHiddenInput(name, value) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = name;
        input.value = value;
        return input;
    }

    // --- Deadline Countdown Timer ---
    let countdownInterval;

    function updateCountdown() {
        const deadlineTime = new Date(deadlineCountdownEl.dataset.deadline).getTime();
        const now = new Date().getTime();
        const distance = deadlineTime - now;

        if (distance < 0) {
            deadlineCountdownEl.innerHTML = "<p>The deadline has passed.</p>";
            clearInterval(countdownInterval);
            return;
        }

        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        deadlineCountdownEl.innerHTML = `
            <div class="countdown-item"><span>${days}</span>Days</div>
            <div class="countdown-item"><span>${hours}</span>Hours</div>
            <div class="countdown-item"><span>${minutes}</span>Mins</div>
            <div class="countdown-item"><span>${seconds}</span>Secs</div>
        `;
    }

    if (deadlineCountdownEl) {
        countdownInterval = setInterval(updateCountdown, 1000);
        updateCountdown(); // Initial call
    }

    // --- Transfers Logic ---
    const confirmTransfersBtn = document.getElementById('confirm-transfers-btn');
    const resetTransfersBtn = document.getElementById('reset-transfers-btn');
    const transferBankDisplay = document.getElementById('transfer-bank-display');
    const pointsCostDisplay = document.getElementById('points-cost');
    const transfersCountDisplay = document.getElementById('transfers-count');

    // Handle clicks on the transfer pitch
    document.querySelector('.transfer-pitch-container').addEventListener('click', function(e) {
        const slot = e.target.closest('.transfer-player-slot');
        if (!slot) return;

        // Identify player to remove using data source, not DOM text
        const playerId = parseInt(slot.dataset.playerId);
        const playerData = allPlayersData.find(p => p.id === playerId);
        const price = playerData ? Math.round(playerData.price * 10) : 0;
        
        playerToRemove = {
            id: playerId,
            price: price, // Integer (price * 10)
            position: slot.dataset.position,
            slotElement: slot,
            name: slot.querySelector('.player-name-row').textContent
        };

        openTransferModal(playerToRemove.position);
    });

    function openTransferModal(position) {
        document.getElementById('transfer-modal-title').textContent = `Replace ${playerToRemove.name} (${position})`;
        transferSearchInput.value = '';
        
        // Set Position Filter (Locked)
        filterPosition.value = position;
        
        // Populate Club Filter
        const clubs = [...new Set(allPlayersData.map(p => p.club))].sort();
        filterClub.innerHTML = '<option value="">All Clubs</option>' + clubs.map(c => `<option value="${c}">${c}</option>`).join('');
        
        // Reset Price Filter
        filterMaxPrice.value = '';

        transferModal.classList.add('show');
        renderTransferList(position);
    }

    function renderTransferList(position) {
        const search = transferSearchInput.value.toLowerCase();
        const selectedClub = filterClub.value;
        const maxPrice = parseFloat(filterMaxPrice.value);

        // Get current squad IDs (including pending ins, excluding pending outs)
        const currentIds = Array.from(document.querySelectorAll('.transfer-player-slot')).map(s => parseInt(s.dataset.playerId));
        
        let html = '';
        allPlayersData.forEach(p => {
            if (p.position === position && !currentIds.includes(p.id)) {
                const matchesSearch = p.name.toLowerCase().includes(search) || p.club.toLowerCase().includes(search);
                const matchesClub = selectedClub === "" || p.club === selectedClub;
                const matchesPrice = isNaN(maxPrice) || p.price <= maxPrice;

                if (matchesSearch && matchesClub && matchesPrice) {
                    const playerInPrice = Math.round(p.price * 10);
                    const costDiff = playerInPrice - playerToRemove.price;
                    const canAfford = (bank - costDiff) >= 0;
                    
                    html += `
                    <div class="modal-player-item ${!canAfford ? 'disabled' : ''}" onclick="${canAfford ? `selectTransferPlayer(${p.id})` : ''}" title="${p.name}">
                        <div class="player-info">
                            <img src="${p.profile_picture || p.club_logo}" class="modal-player-img">
                            <div class="player-details">
                                <span class="player-name">${p.name}</span>
                                <span class="player-meta">${p.position} | ${p.club}</span>
                                <span class="player-form" style="font-size: 0.75rem; color: #e67e22; font-weight: bold;">Form: ${p.form}</span>
                            </div>
                        </div>
                        <div class="player-price">
                            ${currencySymbol}${p.price.toFixed(1)}m
                        </div>
                    </div>`;
                }
            }
        });
        transferPlayerList.innerHTML = html || '<p class="no-data-msg">No players found.</p>';
    }

    window.selectTransferPlayer = function(playerInId) {
        const playerIn = allPlayersData.find(p => p.id == playerInId);
        if (!playerIn) return;

        const playerInPrice = Math.round(playerIn.price * 10);
        const newBank = bank + playerToRemove.price - playerInPrice;
        if (newBank < 0) {
            showToast("Not enough funds.", "error");
            return;
        }

        // Execute Transfer Logic
        bank = newBank;
        console.log("New Bank: " + bank / 10);
        pendingTransfers.push({ out: {id: playerToRemove.id}, in: {id: playerIn.id} });

        // Update UI Slot
        const slot = playerToRemove.slotElement;
        slot.dataset.playerId = playerIn.id;
        slot.querySelector('.player-name-row').textContent = playerIn.name.split(' ').pop(); // Last name approx
        slot.querySelector('.player-price-label').textContent = `${currencySymbol}${playerIn.price.toFixed(1)}m`;
        
        // Update Image
        const img = slot.querySelector('.player-image-frame img');
        if (img && (playerIn.profile_picture || playerIn.club_logo)) {
            img.src = playerIn.profile_picture || playerIn.club_logo;
        }

        slot.classList.add('selected-for-transfer'); // Visual cue
            
        transferModal.classList.remove('show');
        updateTransferUI();
    };

    transferSearchInput.addEventListener('keyup', () => renderTransferList(playerToRemove.position));
    filterClub.addEventListener('change', () => renderTransferList(playerToRemove.position));
    filterMaxPrice.addEventListener('keyup', () => renderTransferList(playerToRemove.position));
    filterMaxPrice.addEventListener('change', () => renderTransferList(playerToRemove.position));
    
    // Close modal logic
    transferModal.querySelector('.modal-close-btn').onclick = () => transferModal.classList.remove('show');
    window.addEventListener('click', (e) => { 
        if (e.target === transferModal) transferModal.classList.remove('show'); 
    });

    resetTransfersBtn.addEventListener('click', () => window.location.reload());

    confirmTransfersBtn.addEventListener('click', function() {
            if (pendingTransfers.length === 0) return;
            
            const form = document.createElement('form');

            form.method = 'POST';
            form.action = 'fantasy_transfers_process.php';

            pendingTransfers.forEach((t, i) => {
                const outInput = document.createElement('input');
                outInput.type = 'hidden'; outInput.name = `transfers[${i}][out]`; outInput.value = t.out.id;
                form.appendChild(outInput);
                const inInput = document.createElement('input');
                inInput.type = 'hidden'; inInput.name = `transfers[${i}][in]`; inInput.value = t.in.id;
                form.appendChild(inInput);
            });
            document.body.appendChild(form);
            
            showConfirmation('Confirm Transfers', `Are you sure you want to make ${pendingTransfers.length} transfer(s)? Points may be deducted.`, function() {
                form.submit();
            });
        });

    function updateTransferUI() {
        transferBankDisplay.textContent = `${currencySymbol}${(bank / 10).toFixed(1)}m`;
        transfersCountDisplay.textContent = pendingTransfers.length;
        const cost = Math.max(0, pendingTransfers.length - freeTransfersAvailable) * 4;
        pointsCostDisplay.textContent = cost;
        confirmTransfersBtn.disabled = pendingTransfers.length === 0;
    }
});
</script>

<?php include 'includes/footer.php'; ?>