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

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'team_manager') {
    header('Location: login.php');
    exit();
}
$manager_id = $_SESSION['user_id'];

$fixture_id = filter_input(INPUT_GET, 'fixture_id', FILTER_VALIDATE_INT);
if (!$fixture_id) {
    header('Location: /smart_football/app/select_fixture_lineup.php?error=no_fixture_selected');
    exit();
}

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

// --- Instantiate Models ---
$teamModel = new Team();
$playerModel = new Player();
$fixtureModel = new Fixture();
$lineupModel = new Lineup();
$fineModel = new Fine();

// --- Fetch Data ---
$team = $teamModel->getTeamByManagerId($manager_id);
if (!$team) {
    header('Location: my_team.php?error=no_team');
    exit();
}

$team_players = $playerModel->getPlayersByTeamId($team->id);
$fined_player_ids = [];
if (isset($team->club_id)) {
    // Get an array of user IDs for players with unpaid fines in the club
    $fined_player_ids = $fineModel->getFinedPlayerIdsForTeam($team->club_id);
}
$fixture = $fixtureModel->getAllByLeague($team->league_id, null, $fixture_id)[0] ?? null;

if (!$fixture || ($fixture->home_team_id != $team->id && $fixture->away_team_id != $team->id)) {
    // Security check: Ensure the fixture belongs to the manager's team
    header('Location: /smart_football/app/select_fixture_lineup.php?error=invalid_fixture');
    exit();
}

// --- Check if lineup is already submitted ---
$lineup_submitted = $lineupModel->hasLineupBeenSubmitted($fixture->id, $team->id);
$existing_lineup = null;
$edit_mode = isset($_GET['action']) && $_GET['action'] === 'edit';

if ($lineup_submitted) {
    $existing_lineup = $lineupModel->getLineupForFixture($fixture->id, $team->id);
}

$show_form = !$lineup_submitted || $edit_mode;

?>

<div class="page-content">
    <div class="matches-header">
        <h1><?php echo $lineup_submitted && !$edit_mode ? 'Lineup Submitted' : 'Submit Lineup'; ?></h1>
    </div>

    <div class="fixture-context" style="text-align: center; margin-bottom: 2rem;">
        <span class="gameweek-badge" style="background: #e9ecef; padding: 4px 12px; border-radius: 15px; font-size: 0.85rem; font-weight: 600; color: #555;">Gameweek <?php echo htmlspecialchars($fixture->gameweek); ?></span>
        <h2 style="margin: 10px 0;"><?php echo htmlspecialchars($fixture->home_team_name); ?> <span style="color: #999; font-size: 0.8em;">vs</span> <?php echo htmlspecialchars($fixture->away_team_name); ?></h2>
        <p style="color: #666; font-size: 1.1rem;"><i class="fa-regular fa-calendar"></i> <?php echo date('D, d M Y - H:i', strtotime($fixture->match_datetime)); ?></p>
        
        <div class="submission-guidelines" style="max-width: 600px; margin: 1.5rem auto; text-align: left; background: #fff3cd; border: 1px solid #ffeeba; color: #856404; padding: 15px; border-radius: 8px;">
            <strong><i class="fa-solid fa-circle-info"></i> Important Guidelines:</strong>
            <ul style="margin: 5px 0 0 0; padding-left: 1.2rem;">
                <li>Lineups must be submitted at least <strong>30 minutes</strong> before kick-off.</li>
                <li>You must select exactly 11 starters (including 1 Goalkeeper).</li>
                <li>You can select up to 7 substitutes.</li>
            </ul>
        </div>
    </div> 

    <?php if ($show_form): ?>
        <form action="/smart_football/app/submit_lineup_process.php" method="POST" id="lineup-form">
            <input type="hidden" name="fixture_id" value="<?php echo $fixture->id; ?>">
            <input type="hidden" name="formation" id="formation-input" value="4-3-3">
            <div id="hidden-inputs-container"></div>

            <div class="lineup-controls">
                <div class="form-group">
                    <label for="formation-select">Select Formation</label>
                    <select id="formation-select">
			<option value="4-2-3-1">4-2-3-1</option>
                        <option value="4-4-2">4-4-2</option>
                        <option value="4-3-3" selected>4-3-3</option>
                        <option value="4-5-1">4-5-1</option>
                        <option value="3-5-2">3-5-2</option>
                        <option value="3-4-3">3-4-3</option>
                        <option value="5-3-2">5-3-2</option>
			<option value="3-4-2-1">3-4-2-1</option>

                    </select>
                </div>
                <div class="controls-actions">
                    <button type="button" id="auto-fill-btn" class="btn btn-secondary"><i class="fa-solid fa-wand-magic-sparkles"></i> Auto-fill Previous</button>
                    <button type="submit" id="submit-lineup-btn" class="btn" disabled><?php echo $lineup_submitted ? 'Update Lineup' : 'Submit Lineup'; ?></button>
                </div>
            </div>

            <div class="lineup-builder-container">
                <div class="pitch-area">
                    <div class="pitch">
                    
                        <div class="pitch-row goalkeeper"></div>
                        <div class="pitch-row defenders"></div>
                        <div class="pitch-row midfielders"></div>
                        <div class="pitch-row forwards"></div>
                    </div>
                </div>

                <div class="substitutes-bench-area">
                    <h3>Substitutes</h3>
                    <div class="substitutes-bench">
                        <?php for ($i = 0; $i < 7; $i++): ?>
                            <div class="player-slot sub-slot" data-position="Substitute"></div>
                        <?php endfor; ?>
                    </div>
                </div>
            </div> <!-- End lineup-builder-container -->

        </form>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const allPlayers = <?php echo json_encode($team_players); ?>;
                const finedPlayerIds = <?php echo json_encode($fined_player_ids); ?>;
                const formationSelect = document.getElementById('formation-select');
                const pitch = {
                    goalkeeper: document.querySelector('.pitch .goalkeeper'),
                    defenders: document.querySelector('.pitch .defenders'),
                    midfielders: document.querySelector('.pitch .midfielders'),
                    forwards: document.querySelector('.pitch .forwards')
                };
                const subsBench = document.querySelector('.substitutes-bench');
                const submitBtn = document.getElementById('submit-lineup-btn');
                const lineupForm = document.getElementById('lineup-form');
                const hiddenInputsContainer = document.getElementById('hidden-inputs-container');
                const autoFillBtn = document.getElementById('auto-fill-btn');

                const modal = document.getElementById('playerSelectModal');
                const modalPlayerList = document.getElementById('playerList');
                const closeModalBtn = modal.querySelector('.close');
                const toastContainer = document.getElementById('toast-container');
                const confirmationModal = document.getElementById('confirmationModal');
                const confirmOkBtn = document.getElementById('confirm-modal-ok');
                const confirmCancelBtn = document.getElementById('confirm-modal-cancel');
                const confirmCloseBtn = document.getElementById('confirm-modal-close');

                let activeSlot = null;

                const formations = {
                    '4-4-2': {d: 4, m: 4, f: 2},
                    '4-3-3': {d: 4, m: 3, f: 3},
                    '4-2-3-1': {d: 4, m: 5, f: 1},
                    '4-5-1': {d: 4, m: 5, f: 1},
                    '3-5-2': {d: 3, m: 5, f: 2},
                    '3-4-3': {d: 3, m: 4, f: 3},
                    '3-4-2-1': {d: 3, m: 6, f: 1},
                    '5-3-2': {d: 5, m: 3, f: 2},
                };

                function showToast(message, type = 'error') {
                    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);
                }

                function drawPitch(formation) {
                    pitch.goalkeeper.innerHTML = '<div class="player-slot" data-position="Goalkeeper"><i class="fa-solid fa-plus"></i></div>';
                    pitch.defenders.innerHTML = Array(formation.d).fill('<div class="player-slot" data-position="Defender"><i class="fa-solid fa-plus"></i></div>').join('');
                    pitch.midfielders.innerHTML = Array(formation.m).fill('<div class="player-slot" data-position="Midfielder"><i class="fa-solid fa-plus"></i></div>').join('');
                    pitch.forwards.innerHTML = Array(formation.f).fill('<div class="player-slot" data-position="Forward"><i class="fa-solid fa-plus"></i></div>').join('');
                }

                function getPlacedPlayerIds() {
                    const placedIds = [];
                    document.querySelectorAll('.player-card').forEach(card => {
                        placedIds.push(parseInt(card.dataset.playerId));
                    });
                    return placedIds;
                }

                async function showPlayerSelectionModal(slot) {
                    activeSlot = slot;
                    const placedIds = getPlacedPlayerIds();
                    const availablePlayers = allPlayers.filter(p => !placedIds.includes(parseInt(p.id)));

                    // Fetch unavailable players
                    let unavailableData = { injured: [], suspended: [] };
                    try {
                        const response = await fetch(`api/get_unavailable_players.php?team_id=<?php echo $team->id; ?>`);
                        unavailableData = await response.json();
                    } catch (e) {
                        console.error("Error fetching unavailable players:", e);
                    }

                    const injuredIds = unavailableData.injured.map(p => parseInt(p.id));
                    const suspendedIds = unavailableData.suspended.map(p => parseInt(p.id)); 
                    const finedIds = finedPlayerIds.map(id => parseInt(id));

                    let playerListHTML = '<h4>Select a Player</h4>';
                    const availableForSelection = availablePlayers.filter(p => !injuredIds.includes(p.id) && !suspendedIds.includes(p.id) && !finedIds.includes(p.id));
                    const unavailableForSelection = allPlayers.filter(p => injuredIds.includes(p.id) || suspendedIds.includes(p.id) || finedIds.includes(p.id));

                    if (availableForSelection.length > 0) {
                        availableForSelection.forEach(player => {
                            playerListHTML += `<div class="modal-player-item" data-player-id="${player.id}">
                                <span>#${player.squad_number} - ${player.first_name} ${player.last_name}</span>
                                <span>(${player.position})</span>
                            </div>`;
                        });
                    } else if (unavailableForSelection.length === allPlayers.length - getPlacedPlayerIds().length) {
                        // This case handles when all remaining players are unavailable
                        playerListHTML += '<p>No available players.</p>';
                    }

                    if (unavailableForSelection.length > 0) {
                        playerListHTML += '<h5 class="unavailable-header">Unavailable</h5>';
                        unavailableForSelection.forEach(player => {
                            let reason = '';
                            if (injuredIds.includes(player.id)) {
                                const injuryDetails = unavailableData.injured.find(p => p.id == player.id);
                                reason = `Injured: ${injuryDetails.injury_description}`;
                            } else if (suspendedIds.includes(player.id)) {
                                const suspensionDetails = unavailableData.suspended.find(p => p.id == player.id);
                                reason = `Suspended: ${suspensionDetails.reason}`;
                            } else if (finedIds.includes(player.id)) {
                                reason = `Outstanding Fine`;
                            }
                            playerListHTML += `<div class="modal-player-item disabled">
                                <span>#${player.squad_number} - ${player.first_name} ${player.last_name}</span>
                                <small>(${reason})</small>
                            </div>`;
                        });
                    }

                    modalPlayerList.innerHTML = playerListHTML;
                    modal.classList.add('show');

                    document.querySelectorAll('.modal-player-item').forEach(item => {
                        item.addEventListener('click', () => selectPlayerForSlot(item.dataset.playerId));
                    });
                }

                function selectPlayerForSlot(playerId) {
                    const player = allPlayers.find(p => p.id == playerId);
                    if (!player || !activeSlot) return;

                    activeSlot.innerHTML = `<div class="player-card" data-player-id='${player.id}'>
                                                <div class="player-shirt"><i class="fa-solid fa-shirt"></i></div>
                                                <span class="player-name-label">${player.last_name}</span>
                                            </div>`;

                    modal.classList.remove('show');
                    validateLineup();
                }

                function handleSlotClick(e) {
                    const slot = e.target.closest('.player-slot');
                    if (!slot) return;

                    const playerCard = slot.querySelector('.player-card');

                    if (playerCard && playerCard.classList.contains('unavailable')) {
                        // If clicking an unavailable player, treat it like an empty slot to force replacement
                        showPlayerSelectionModal(slot);
                    } else if (playerCard) {
                        // If clicking a normal, available player, remove them
                        slot.innerHTML = '<i class="fa-solid fa-plus"></i>';
                        validateLineup();
                    } else {
                        // If the slot is empty, open the modal
                        showPlayerSelectionModal(slot);
                    }
                }

                // Event Delegation for Player Slots
                document.querySelector('.lineup-builder-container').addEventListener('click', function(e) {
                    const slot = e.target.closest('.player-slot');
                    if (slot) {
                        handleSlotClick(e);
                    }
                });

                formationSelect.addEventListener('change', () => {
                    const selectedFormation = formations[formationSelect.value];
                    drawPitch(selectedFormation);
                    subsBench.querySelectorAll('.player-slot').forEach(slot => {
                        slot.innerHTML = '<i class="fa-solid fa-plus"></i>';
                    });
                    validateLineup();
                });

                function validateLineup() {
                    const starters = document.querySelectorAll('.pitch .player-card');
                    const unavailablePlayers = document.querySelectorAll('.player-card.unavailable').length;
                    const isSquadFull = starters.length === 11;

                    let goalkeeperCount = 0;
                    document.querySelectorAll('.pitch .player-slot[data-position="Goalkeeper"]').forEach(slot => {
                        if (slot.querySelector('.player-card')) {
                            goalkeeperCount++;
                        }
                    });

                    // Disable if squad is not full, OR if it is full but doesn't have exactly one GK, OR if there are unavailable players.
                    submitBtn.disabled = !isSquadFull || goalkeeperCount !== 1 || unavailablePlayers > 0;
                }

                // --- Auto-fill Logic ---
                autoFillBtn.addEventListener('click', async () => {
                    if (document.querySelectorAll('.player-card').length > 0 && !confirm('This will overwrite your current selection. Continue?')) {
                        return;
                    }

                    // Fetch unavailable players first
                    let unavailableIds = [];
                    try {
                        const unavailableResponse = await fetch(`api/get_unavailable_players.php?team_id=<?php echo $team->id; ?>`);
                        const unavailableData = await unavailableResponse.json();
                        const injuredIds = unavailableData.injured.map(p => parseInt(p.id));
                        const suspendedIds = unavailableData.suspended.map(p => parseInt(p.id));
                        unavailableIds = [...injuredIds, ...suspendedIds, ...finedPlayerIds];
                    } catch (e) {
                        console.error("Error fetching unavailable players:", e);
                        showToast('Could not check player availability.', 'error');
                    }

                    try {
                        const response = await fetch('api/get_previous_lineup.php');
                        const data = await response.json();

                        if (data.error) {
                            alert(data.error);
                            return;
                        }

                        // 1. Set Formation & Redraw Pitch
                        if (data.formation && formations[data.formation]) {
                            formationSelect.value = data.formation;
                            drawPitch(formations[data.formation]);
                        } else {
                            // If formation not found or invalid, just redraw current to clear pitch
                            drawPitch(formations[formationSelect.value]);
                        }

                        // 2. Clear Bench
                        subsBench.querySelectorAll('.player-slot').forEach(slot => { slot.innerHTML = ''; });

                        // 3. Place Starters
                        if (data.starters) {
                            for (const [playerId, position] of Object.entries(data.starters)) {
                                // Find first empty slot matching position
                                const emptySlot = Array.from(document.querySelectorAll(`.pitch .player-slot[data-position="${position}"]`))
                                    .find(slot => !slot.querySelector('.player-card'));
                                
                                if (emptySlot) {
                                    if (unavailableIds.includes(parseInt(playerId))) {
                                        placeUnavailablePlayerInSlotLogic(playerId, emptySlot);
                                    } else {
                                        selectPlayerForSlotLogic(playerId, emptySlot);
                                    }
                                }
                            }
                        }

                        // 4. Place Substitutes
                        if (data.substitutes) {
                            const subSlots = document.querySelectorAll('.substitutes-bench .player-slot');
                            data.substitutes.forEach((playerId, index) => {
                                if (subSlots[index]) {
                                    if (unavailableIds.includes(parseInt(playerId))) {
                                        placeUnavailablePlayerInSlotLogic(playerId, subSlots[index]);
                                    } else {
                                        selectPlayerForSlotLogic(playerId, subSlots[index]);
                                    }
                                }
                            });
                        }

                    } catch (e) {
                        console.error(e);
                        alert('Failed to auto-fill lineup.');
                    }
                });

                function selectPlayerForSlotLogic(playerId, slot) {
                    const player = allPlayers.find(p => p.id == playerId);
                    if (player) {
                        slot.innerHTML = `<div class="player-card" data-player-id='${player.id}'><div class="player-shirt"><i class="fa-solid fa-shirt"></i></div><span class="player-name-label">${player.last_name}</span></div>`;
                        validateLineup();
                    }
                }

                function placeUnavailablePlayerInSlotLogic(playerId, slot) {
                    const player = allPlayers.find(p => p.id == playerId);
                    if (player) {
                        slot.innerHTML = `<div class="player-card unavailable" data-player-id='${player.id}'>
                                            <div class="player-shirt"><i class="fa-solid fa-triangle-exclamation"></i></div>
                                            <span class="player-name-label">${player.last_name}</span>
                                          </div>`;
                        validateLineup();
                    }
                }

                function placeUnavailablePlayerInSlotLogic(playerId, slot) {
                    const player = allPlayers.find(p => p.id == playerId);
                    if (player) {
                        slot.innerHTML = `<div class="player-card unavailable" data-player-id='${player.id}'>
                                            <div class="player-shirt"><i class="fa-solid fa-triangle-exclamation"></i></div>
                                            <span class="player-name-label">${player.last_name}</span>
                                          </div>`;
                        validateLineup();
                    }
                }

                lineupForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    // Final validation before submitting
                    const starters = document.querySelectorAll('.pitch .player-card');
                    if (starters.length !== 11) {
                        showToast('You must select a full starting lineup of 11 players.', 'error');
                        return;
                    }

                    let goalkeeperCount = 0;
                    hiddenInputsContainer.innerHTML = '';

                    starters.forEach(card => {
                        const slot = card.closest('.player-slot');
                        if (slot.dataset.position === 'Goalkeeper') {
                            goalkeeperCount++;
                        }
                        const input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = `starters[${card.dataset.playerId}]`;
                        input.value = slot.dataset.position; // The position of the slot
                        hiddenInputsContainer.appendChild(input);
                    });

                    if (goalkeeperCount !== 1) {
                        showToast('You must have exactly one Goalkeeper in your starting lineup.', 'error');
                        return;
                    }

                    confirmationModal.classList.add('show');
                });

                confirmOkBtn.addEventListener('click', function() {
                    hiddenInputsContainer.innerHTML = '';
                    const starters = document.querySelectorAll('.pitch .player-card');
                    starters.forEach(card => {
                        const slot = card.closest('.player-slot');
                        const input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = `starters[${card.dataset.playerId}]`;
                        input.value = slot.dataset.position; // The position of the slot
                        hiddenInputsContainer.appendChild(input);
                    });

                    // If validation passes, continue building inputs
                    document.getElementById('formation-input').value = formationSelect.value;
                    document.querySelectorAll('.substitutes-bench .player-card').forEach(card => {
                        const input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = 'substitutes[]';
                        input.value = card.dataset.playerId;
                        hiddenInputsContainer.appendChild(input);
                    });
                    
                    lineupForm.submit();
                });

                confirmCancelBtn.addEventListener('click', () => confirmationModal.classList.remove('show'));
                confirmCloseBtn.addEventListener('click', () => confirmationModal.classList.remove('show'));
                window.addEventListener('click', (e) => {
                    if (e.target === confirmationModal) confirmationModal.classList.remove('show');
                });

                closeModalBtn.onclick = () => modal.classList.remove('show');
                window.addEventListener('click', (event) => {
                    if (event.target == modal) {
                        modal.classList.remove('show');
                    }
                });

                // Initial setup
                drawPitch(formations[formationSelect.value]);

                const existingStarters = <?php echo json_encode($existing_lineup->starters ?? []); ?>;
                const existingSubs = <?php echo json_encode($existing_lineup->substitutes ?? []); ?>;

                if (Object.keys(existingStarters).length > 0) {
                    const pitchSlots = document.querySelectorAll('.pitch .player-slot');
                    Object.keys(existingStarters).slice(0, pitchSlots.length).forEach((playerId, index) => {
                        const player = allPlayers.find(p => p.id == playerId);
                        if(player && pitchSlots[index]) {
                            pitchSlots[index].innerHTML = `<div class="player-card" data-player-id='${player.id}'><div class="player-shirt"><i class="fa-solid fa-shirt"></i></div><span class="player-name-label">${player.last_name}</span></div>`;
                        }
                    });
                }
                if (existingSubs.length > 0) {
                    const subSlots = document.querySelectorAll('.substitutes-bench .player-slot');
                     existingSubs.slice(0, subSlots.length).forEach((playerId, index) => {
                        const player = allPlayers.find(p => p.id == playerId);
                        if(player && subSlots[index]) {
                            subSlots[index].innerHTML = `<div class="player-card" data-player-id='${player.id}'><div class="player-shirt"><i class="fa-solid fa-shirt"></i></div><span class="player-name-label">${player.last_name}</span></div>`;
                        }
                    });
                }
                validateLineup();
            });
        </script>
        </div>
    <?php else: ?>
        <div class="status-container" style="text-align: center; padding: 2rem; background-color: #f0f4f8; border-radius: 8px; max-width: 600px; margin: auto;">
            <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="currentColor" class="bi bi-check-circle-fill" viewBox="0 0 16 16" style="color: #28a745; margin-bottom: 1rem;"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg>
            <h2>Lineup Submitted</h2>
            <p>Your lineup for the upcoming match has been successfully submitted.</p>
            <a href="submit_lineup.php?fixture_id=<?php echo $fixture->id; ?>&action=edit" class="btn">Edit Lineup</a>
        </div>
    <?php endif; ?>
</div>

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

<!-- Modal for Player Selection -->
<div id="playerSelectModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <div id="playerList"></div>
    </div>
</div>

<!-- Confirmation Modal -->
<div id="confirmationModal" class="modal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h3>Confirm Lineup</h3>
            <button class="modal-close-btn" id="confirm-modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <p>Are you sure you want to submit this lineup?</p>
            <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button class="btn btn-secondary" id="confirm-modal-cancel">Cancel</button>
                <button class="btn btn-primary" id="confirm-modal-ok">Submit</button>
            </div>
        </div>
    </div>
</div>

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

<style>
/* Pitch & Lineup Styles */
.lineup-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    background: #fff;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.05);
    flex-wrap: wrap;
    gap: 15px;
}

.lineup-controls .form-group {
    display: flex;
    align-items: center;
    gap: 15px;
    margin: 0;
}

.lineup-controls label {
    font-weight: 700;
    color: #2c3e50;
    margin: 0;
    font-size: 1rem;
}

#formation-select {
    padding: 10px 20px;
    border-radius: 8px;
    border: 1px solid #ddd;
    background-color: #f8f9fa;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.2s;
    font-weight: 600;
    color: #333;
}

#formation-select:hover, #formation-select:focus {
    border-color: #3498db;
    background-color: #fff;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
    outline: none;
}

.controls-actions {
    display: flex;
    gap: 10px;
}

.pitch-area {
    background-image: url('/smart_football/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);
    margin-bottom: 20px;
}

.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-slot {
    width: 80px;
    height: 90px;
    border: 2px dashed rgba(255,255,255,0.5);
    border-radius: 6px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.2s;
    position: relative;
    background: rgba(0,0,0,0.1);
}

.player-slot:hover {
    background: rgba(255,255,255,0.2);
    transform: scale(1.05);
}

.player-slot .fa-plus {
    color: rgba(255,255,255,0.8);
    font-size: 1.5rem;
}

.player-card {
    text-align: center;
    width: 100%;
}

.player-shirt {
    font-size: 2.5rem;
    color: #fff;
    text-shadow: 0 2px 5px rgba(0,0,0,0.3);
    margin-bottom: 5px;
}

.player-name-label {
    background: rgba(0,0,0,0.7);
    color: white;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 0.75rem;
    white-space: nowrap;
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
}

.player-card.unavailable {
    border: 2px solid #e74c3c;
    background-color: rgba(231, 76, 60, 0.3);
    padding: 5px 0;
    border-radius: 4px;
}
.player-card.unavailable .player-shirt i {
    color: #e74c3c;
}
.player-card.unavailable .player-name-label {
    background-color: #c0392b;
}

.substitutes-bench-area {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    margin-top: 20px;
}

.substitutes-bench {
    display: flex;
    justify-content: center;
    gap: 10px;
    flex-wrap: wrap;
}

.sub-slot {
    border-color: #ccc;
    background: #e9ecef;
}

.sub-slot .fa-plus {
    color: #999;
}

/* Modal Styles */
.modal {
    display: none;
    position: fixed;
    z-index: 2000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.modal.show {
    display: block;
    opacity: 1;
}

.modal-content {
    background-color: #fff;
    margin: 10% auto;
    padding: 20px;
    border-radius: 8px;
    width: 90%;
    max-width: 500px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
    position: relative;
}

.close {
    position: absolute;
    right: 15px;
    top: 10px;
    font-size: 1.5rem;
    cursor: pointer;
    color: #aaa;
}

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

.modal-close-btn {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: #aaa;
}

.close:hover {
    color: #333;
}

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

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

.modal-player-item.disabled {
    opacity: 0.6;
    cursor: not-allowed;
    background-color: #f9f9f9;
}

.unavailable-header {
    margin-top: 15px;
    margin-bottom: 5px;
    color: #e74c3c;
    border-bottom: 1px solid #eee;
    padding-bottom: 5px;
}

/* --- 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;
}
.toast.hide {
    opacity: 0;
    transform: translateY(20px);
}
.toast-success { background-color: #28a745; }
.toast-error { background-color: #dc3545; }
.toast-info { background-color: #17a2b8; }
</style>