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

// Instantiate models
$fixtureModel = new Fixture();
$leagueModel = new League();
$announcementModel = new Announcement();
$seasonModel = new Season();
$eventModel = new MatchEvent();
$playerModel = new Player();
$sponsorModel = new Sponsorship();

// --- Determine Context (Season & League) ---
// Get all seasons to find the current one (assuming first is latest)
$all_seasons = $seasonModel->getAll();
$current_season = $all_seasons[0]->name ?? date('Y') . '/' . (date('Y') + 1);

// Get leagues for the current season
$leagues_in_season = $leagueModel->getAllBySeason($current_season);

// Determine League ID (from URL or default to first in season)
$league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);
if (!$league_id && !empty($leagues_in_season)) {
    $league_id = $leagues_in_season[0]->id;
}

// Determine current league name for display
$current_league_name = 'League';
foreach ($leagues_in_season as $l) {
    if ($l->id == $league_id) {
        $current_league_name = $l->name;
        break;
    }
}

$pageTitle = 'Latest';
include 'includes/header.php';

// --- Fetch Data for Each Dashboard Section ---

// 1. Live Matches
$live_matches = $fixtureModel->getLiveMatches($league_id);
foreach ($live_matches as $match) {
    $match->events = $eventModel->getEventsForFixture($match->id);
    $match->player_names = $playerModel->getPlayerNamesForFixture($match->id);
}

// 2. Hero Match Logic (First live match OR next upcoming match)
$hero_match = null;
if (!empty($live_matches)) {
    $hero_match = $live_matches[0];
} else {
    $upcoming_hero = $fixtureModel->getUpcomingFixtures($league_id, 1);
    if (!empty($upcoming_hero)) {
        $hero_match = $upcoming_hero[0];
        $hero_match->status = 'scheduled'; // Ensure status is set
    } else {
        // Fallback: Show latest result if no upcoming matches
        $recent_hero = $fixtureModel->getRecentResults($league_id, 1);
        if (!empty($recent_hero)) {
            $hero_match = $recent_hero[0];
        }
    }
}

// Ensure hero match has events/players if it is live/finished (and wasn't in live_matches list)
if ($hero_match && in_array($hero_match->status, ['live', 'half_time', 'finished'])) {
    if (!isset($hero_match->events)) {
        $hero_match->events = $eventModel->getEventsForFixture($hero_match->id);
        $hero_match->player_names = $playerModel->getPlayerNamesForFixture($hero_match->id);
    }
}

// 3. "Stories" - We'll use the most recent results for this
$stories = $fixtureModel->getRecentResults($league_id, 7);

// 4. Recent Results (Previous Gameweek)
$recent_results = [];
$latest_finished_gameweek = $fixtureModel->getLatestFinishedGameweek($league_id);
if ($latest_finished_gameweek) {
    $recent_results = $fixtureModel->getFixturesByGameweek($league_id, $latest_finished_gameweek);
    foreach ($recent_results as $match) {
        $match->events = $eventModel->getEventsForFixture($match->id);
        $match->player_names = $playerModel->getPlayerNamesForFixture($match->id);
    }
}

// 5. Upcoming Matches (Next Gameweek)
$upcoming_matches = [];
$next_gameweek_to_show = $hero_match->gameweek ?? ($latest_finished_gameweek + 1);
if ($next_gameweek_to_show) {
    $upcoming_matches = $fixtureModel->getFixturesByGameweek($league_id, $next_gameweek_to_show);
    // Filter out live matches from upcoming list to avoid duplicates
    $live_ids = array_map(fn($m) => $m->id, $live_matches);
    $upcoming_matches = array_filter($upcoming_matches, fn($m) => !in_array($m->id, $live_ids));
    
    // Fetch events for finished matches in upcoming list (e.g. played earlier in the current gameweek)
    foreach ($upcoming_matches as $match) {
        if ($match->status === 'finished') {
            $match->events = $eventModel->getEventsForFixture($match->id);
            $match->player_names = $playerModel->getPlayerNamesForFixture($match->id);
        }
    }
}

// 6. League Table Snapshot
$league_table = $leagueModel->getTable($league_id);
$table_snapshot = array_slice($league_table, 0, 6); // Get top 6 teams

// 7. Announcements
$announcements = $announcementModel->getActive();

// Get colors for inline styles if needed, though CSS vars are preferred
$primary_color = $settings['primary_color'] ?? '#37003c';
$secondary_color = $settings['secondary_color'] ?? '#580a66';

// Fetch General Product Ads
$productAds = $sponsorModel->getActiveAds(5);

// --- My Feed Logic ---
$feed_items = [];
if (isset($_SESSION['user_id'])) {
    $db = new Database();
    // Get user's clubs from memberships
    $db->query("SELECT club_id FROM memberships WHERE user_id = :uid AND expiry_date >= CURDATE()");
    $db->bind(':uid', $_SESSION['user_id']);
    $memberships = $db->resultSet();
    $club_ids = array_map(fn($m) => $m->club_id, $memberships);

    if (!empty($club_ids)) {
        $in_clubs = implode(',', array_map('intval', $club_ids));
        
        // Fetch Fixtures (Recent Results & Upcoming) for these clubs
        $query = "SELECT f.*, 
                         hc.name as home_team_name, ht.club_id as home_club_id,
                         ac.name as away_team_name, at.club_id as away_club_id,
                         hc.logo as home_team_logo, ac.logo as away_team_logo
                  FROM fixtures f
                  JOIN teams ht ON f.home_team_id = ht.id
                  LEFT JOIN clubs hc ON ht.club_id = hc.id
                  JOIN teams at ON f.away_team_id = at.id
                  LEFT JOIN clubs ac ON at.club_id = ac.id
                  WHERE (ht.club_id IN ($in_clubs) OR at.club_id IN ($in_clubs))
                  AND f.match_datetime BETWEEN DATE_SUB(NOW(), INTERVAL 60 DAY) AND DATE_ADD(NOW(), INTERVAL 2 DAY)
                  ORDER BY f.match_datetime DESC
                  LIMIT 6";
        
        $db->query($query);
        $fixtures_feed = $db->resultSet();

        // Fetch recent suspensions for these clubs
        $db->query("SELECT ps.*, u.first_name, u.last_name, u.profile_picture, t.name as team_name, c.name as club_name, c.logo as club_logo
                  FROM player_suspensions ps
                  JOIN players p ON ps.player_id = p.user_id
                  JOIN users u ON p.user_id = u.id
                  JOIN teams t ON p.team_id = t.id
                  JOIN clubs c ON t.club_id = c.id
                  WHERE t.club_id IN ($in_clubs)
                  AND ps.created_at BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
                  ORDER BY ps.created_at DESC");
        $suspensions_feed = $db->resultSet();

        foreach ($suspensions_feed as $s) {
            // Use suspension ID for the link
            $feed_items[] = ['type' => 'suspension', 'timestamp' => strtotime($s->created_at), 'data' => $s, 'id' => $s->id];
        }

        // Fetch injury recoveries for these clubs
        $db->query("SELECT i.*, u.first_name, u.last_name, u.profile_picture, t.name as team_name, c.name as club_name, c.logo as club_logo
                  FROM injuries i
                  JOIN players p ON i.player_id = p.user_id
                  JOIN users u ON p.user_id = u.id
                  JOIN teams t ON p.team_id = t.id
                  JOIN clubs c ON t.club_id = c.id
                  WHERE t.club_id IN ($in_clubs)
                  AND i.status = 'Fit'
                  AND i.expected_return_date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
                  ORDER BY i.expected_return_date DESC");
        $recoveries_feed = $db->resultSet();

        foreach ($recoveries_feed as $r) {
            $feed_items[] = ['type' => 'injury_recovery', 'timestamp' => strtotime($r->expected_return_date), 'data' => $r, 'id' => $r->id];
        }

        foreach ($fixtures_feed as $f) {
            $match_timestamp = strtotime($f->match_datetime);
            $time_diff = $match_timestamp - time();
            if ($f->status === 'finished') {
                $type = 'match_report';
            } elseif ($time_diff <= 3600 && $f->status !== 'finished') {
                // Show announcement 1 hour before kickoff
                $type = 'lineups_announced';
            } else {
                $type = 'match_preview';
            }
            $feed_items[] = ['type' => $type, 'timestamp' => strtotime($f->match_datetime), 'data' => $f, 'id' => $f->id];
        }
        // Sort by timestamp descending (newest first)
        usort($feed_items, fn($a, $b) => $b['timestamp'] <=> $a['timestamp']);
        // Take only the first 6 items for the initial page load
        $feed_items = array_slice($feed_items, 0, 6);
    }
}
?>

    <!-- Hero Section -->
    <?php if ($hero_match): ?>
    <div class="dashboard-hero">
        <div class="hero-header">
            <span class="league-badge"><?php echo htmlspecialchars($current_league_name); ?></span>
            
            <!-- League Selector -->
            <form action="index.php" method="GET" class="hero-league-selector">
                <select name="league_id" onchange="this.form.submit()">
                    <?php foreach ($leagues_in_season as $l): ?>
                        <option value="<?php echo $l->id; ?>" <?php echo ($l->id == $league_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($l->name); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>

            <span class="match-status-badge <?php echo ($hero_match->status === 'live' || $hero_match->status === 'half_time') ? 'live' : ''; ?>">
                <?php 
                if ($hero_match->status === 'live') echo 'LIVE';
                elseif ($hero_match->status === 'half_time') echo 'HALF TIME';
                else echo 'UPCOMING'; 
                ?>
            </span>
        </div>
        <a href="fixture.php?id=<?php echo $hero_match->id; ?>" class="hero-match-content">
            <?php
            $hero_home_scorers = [];
            $hero_away_scorers = [];
            if (isset($hero_match->events)) {
                foreach ($hero_match->events as $event) {
                    if (in_array($event->event_type, ['goal', 'penalty_scored', 'own_goal'])) {
                        $pName = $hero_match->player_names[$event->player_id] ?? 'Unknown';
                        $time = $event->minute . "'";
                        $str = $pName . " " . $time;
                        if ($event->event_type === 'own_goal') $str .= " (OG)";
                        if ($event->event_type === 'penalty_scored') $str .= " (P)";
                        
                        if ($event->team_id == $hero_match->home_team_id) $hero_home_scorers[] = $str;
                        else $hero_away_scorers[] = $str;
                    }
                }
            }
            ?>
            <div class="hero-team home">
                <img src="<?php echo htmlspecialchars($hero_match->home_team_logo ?? URL_ROOT . '/public/assets/images/default_crest.png'); ?>" alt="" class="hero-logo">
                <span class="hero-name"><?php echo htmlspecialchars($hero_match->home_team_name); ?></span>
                <?php if (!empty($hero_home_scorers)): ?>
                    <div class="hero-scorers-list home">
                        <?php foreach($hero_home_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                    </div>
                <?php endif; ?>
            </div>
            <div class="hero-center">
                <?php if ($hero_match->status === 'live' || $hero_match->status === 'half_time' || $hero_match->status === 'finished'): ?>
                    <div class="hero-score"><?php echo (int)($hero_match->home_team_score ?? 0); ?> - <?php echo (int)($hero_match->away_team_score ?? 0); ?></div>
                    <?php if ($hero_match->status === 'finished'): ?>
                        <div class="match-status">FT</div>
                    <?php else: ?>
                        <?php 
                        // Use DB Elapsed Time
                        $h_elapsed_1st = max(0, (int)($hero_match->elapsed_1st ?? 0));
                        $h_elapsed_2nd = max(0, (int)($hero_match->elapsed_2nd ?? 0));
                        ?>
                        <div class="live-timer" 
                             data-status="<?php echo $hero_match->status; ?>" 
                             data-first-half-start="<?php echo $hero_match->first_half_start_time; ?>" 
                             data-second-half-start="<?php echo $hero_match->second_half_start_time; ?>"
                             data-elapsed-first="<?php echo $h_elapsed_1st; ?>"
                             data-elapsed-second="<?php echo $h_elapsed_2nd; ?>"
                             data-full-time-duration="<?php echo (int)($settings['full_time_duration'] ?? 90); ?>">Live</div>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="hero-time"><?php echo date('H:i', strtotime($hero_match->match_datetime)); ?></div>
                    <div id="hero-countdown" data-match-time="<?php echo htmlspecialchars($hero_match->match_datetime); ?>">
                        <!-- Countdown injected by JS -->
                    </div>
                <?php endif; ?>
            </div>
            <div class="hero-team away">
                <img src="<?php echo htmlspecialchars($hero_match->away_team_logo ?? URL_ROOT . '/public/assets/images/default_crest.png'); ?>" alt="" class="hero-logo">
                <span class="hero-name"><?php echo htmlspecialchars($hero_match->away_team_name); ?></span>
                <?php if (!empty($hero_away_scorers)): ?>
                    <div class="hero-scorers-list away">
                        <?php foreach($hero_away_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                    </div>
                <?php endif; ?>
            </div>
        </a>
    </div>
    <?php else: ?>
    <div class="dashboard-hero" style="min-height: 200px; display: flex; flex-direction: column; justify-content: center;">
        <div class="hero-header">
            <span class="league-badge"><?php echo htmlspecialchars($current_league_name); ?></span>
            <!-- League Selector -->
            <form action="index.php" method="GET" class="hero-league-selector">
                <select name="league_id" onchange="this.form.submit()">
                    <?php foreach ($leagues_in_season as $l): ?>
                        <option value="<?php echo $l->id; ?>" <?php echo ($l->id == $league_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($l->name); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>
        <div style="text-align: center; opacity: 0.8;">No featured matches available for this league.</div>
    </div>
    <?php endif; ?>

<div class="dashboard-view pl-style" style="padding-top: 0;">
    <!-- Announcements Section -->
    <?php if (!empty($announcements)): ?>
    <div class="dashboard-section">
        <h2 class="dashboard-title">Announcements</h2>
        <div class="announcement-list">
            <?php foreach ($announcements as $announcement): ?>
                <div class="announcement-card type-<?php echo htmlspecialchars($announcement->type); ?>">
                    <div class="announcement-header">
                        <span class="announcement-tag"><?php echo htmlspecialchars(ucfirst($announcement->type)); ?></span>
                        <span class="announcement-date"><?php echo date('d M Y', strtotime($announcement->created_at)); ?></span>
                    </div>
                    <h3><?php echo htmlspecialchars($announcement->title); ?></h3>
                    <div class="announcement-content"><?php echo nl2br(htmlspecialchars($announcement->content)); ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Live Matches Section -->
    <?php if (!empty($live_matches) && count($live_matches) > 1): ?>
    <div class="dashboard-section">
        <h2 class="dashboard-title">Live Matches</h2>
        <div class="fixture-list">
            <?php foreach ($live_matches as $match): ?>
                <?php if ($hero_match && $match->id === $hero_match->id) continue; // Skip if shown in hero ?>
                <a href="fixture.php?id=<?php echo $match->id; ?>" class="fixture-item live-match">
                    <div class="match-main-row">
                        <div class="team home-team">
                            <span class="team-name"><?php echo htmlspecialchars($match->home_team_name); ?></span>
                            <img src="<?php echo htmlspecialchars($match->home_team_logo); ?>" alt="" class="team-logo">
                        </div>
                        <div class="score-box live">
                            <span class="score"><?php echo $match->home_team_score ?? 0; ?> - <?php echo $match->away_team_score ?? 0; ?></span>
                            <?php 
                            // Use DB Elapsed Time
                            $m_elapsed_1st = max(0, (int)($match->elapsed_1st ?? 0));
                            $m_elapsed_2nd = max(0, (int)($match->elapsed_2nd ?? 0));
                            ?>
                            <div class="live-timer" 
                                 data-status="<?php echo $match->status; ?>" 
                                 data-first-half-start="<?php echo $match->first_half_start_time ?? ''; ?>" 
                                 data-second-half-start="<?php echo $match->second_half_start_time ?? ''; ?>"
                                 data-elapsed-first="<?php echo $m_elapsed_1st; ?>"
                                 data-elapsed-second="<?php echo $m_elapsed_2nd; ?>"
                                 data-full-time-duration="<?php echo (int)($settings['full_time_duration'] ?? 90); ?>"
                            >Live</div>
                        </div>
                        <div class="team away-team">
                            <img src="<?php echo htmlspecialchars($match->away_team_logo); ?>" alt="" class="team-logo">
                            <span class="team-name"><?php echo htmlspecialchars($match->away_team_name); ?></span>
                        </div>
                    </div>
                    
                    <?php
                    $home_scorers = [];
                    $away_scorers = [];
                    foreach ($match->events as $event) {
                        if (in_array($event->event_type, ['goal', 'penalty_scored', 'own_goal'])) {
                            $pName = $match->player_names[$event->player_id] ?? 'Unknown';
                            $time = $event->minute . "'";
                            $str = "$pName $time";
                            if ($event->event_type === 'own_goal') $str .= " (OG)";
                            if ($event->event_type === 'penalty_scored') $str .= " (P)";
                            if ($event->team_id == $match->home_team_id) $home_scorers[] = $str;
                            else $away_scorers[] = $str;
                        }
                    }
                    ?>
                    <?php if (!empty($home_scorers) || !empty($away_scorers)): ?>
                        <div class="match-scorers">
                            <div class="home-scorers">
                                <?php foreach($home_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                            </div>
                            <div class="away-scorers">
                                <?php foreach($away_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Stories Section -->
    <?php if (!empty($stories)): ?>
    <div class="dashboard-section stories-section">
        <h2 class="dashboard-title">Highlights</h2>
        <div class="stories-container">
            <?php foreach ($stories as $story): 
                // Check if the match was finished within the last 24 hours
                $match_timestamp = strtotime($story->match_datetime);
                $is_new = (time() - $match_timestamp) < (24 * 60 * 60);
            ?>
                <a href="match_report.php?id=<?php echo $story->id; ?>" class="story-item">
                    <div class="story-ring">
                        <?php if ($is_new): ?>
                            <span class="story-new-badge">New</span>
                        <?php endif; ?>
                        <div class="story-circle">
                            <img src="<?php echo htmlspecialchars($story->home_team_logo ?? URL_ROOT . '/public/assets/images/default_crest.png'); ?>" alt="" class="s-logo home">
                            <img src="<?php echo htmlspecialchars($story->away_team_logo ?? URL_ROOT . '/public/assets/images/default_crest.png'); ?>" alt="" class="s-logo away">
                        </div>
                    </div>
                    <span class="story-label"><?php echo (int)$story->home_team_score . '-' . (int)$story->away_team_score; ?></span>
                </a>
            <?php endforeach; ?>
            <a href="matches.php?view=matches" class="story-item view-all-story">
                <div class="story-ring">
                    <div class="story-circle">
                        <i class="fa-solid fa-arrow-right" style="font-size: 1.2rem; color: var(--primary-color);"></i>
                    </div>
                </div>
                <span class="story-label">View All</span>
            </a>
        </div>
    </div>
    <?php endif; ?>

    <!-- Recent Results Section -->
    <?php if (!empty($recent_results)): ?>
    <div class="dashboard-section">
        <h2 class="dashboard-title">Results (GW <?php echo $latest_finished_gameweek; ?>)</h2>
        <div class="fixture-list">
            <?php foreach ($recent_results as $match): ?>
                <a href="fixture.php?id=<?php echo $match->id; ?>" class="fixture-item">
                    <div class="match-main-row">
                        <div class="team home-team">
                            <span class="team-name"><?php echo htmlspecialchars($match->home_team_name); ?></span>
                            <img src="<?php echo htmlspecialchars($match->home_team_logo); ?>" alt="" class="team-logo">
                        </div>
                        <?php if ($match->status === 'finished'): ?>
                            <div class="score-box finished">
                                <span class="score"><?php echo $match->home_team_score ?? 0; ?> - <?php echo $match->away_team_score ?? 0; ?></span>
                                <span class="status-label">FT</span>
                            </div>
                        <?php else: ?>
                            <div class="score-box time-box">
                                <span class="status-label" style="font-size: 0.8rem;"><?php echo ucfirst($match->status); ?></span>
                                <span class="date"><?php echo date('d M', strtotime($match->match_datetime)); ?></span>
                            </div>
                        <?php endif; ?>
                        <div class="team away-team">
                            <img src="<?php echo htmlspecialchars($match->away_team_logo); ?>" alt="" class="team-logo">
                            <span class="team-name"><?php echo htmlspecialchars($match->away_team_name); ?></span>
                        </div>
                    </div>
                    <?php
                    $home_scorers = [];
                    $away_scorers = [];
                    foreach ($match->events as $event) {
                        if (in_array($event->event_type, ['goal', 'penalty_scored', 'own_goal'])) {
                            $pName = $match->player_names[$event->player_id] ?? 'Unknown';
                            $time = $event->minute . "'";
                            $str = "$pName $time";
                            if ($event->event_type === 'own_goal') $str .= " (OG)";
                            if ($event->event_type === 'penalty_scored') $str .= " (P)";
                            if ($event->team_id == $match->home_team_id) $home_scorers[] = $str;
                            else $away_scorers[] = $str;
                        }
                    }
                    if (!empty($home_scorers) || !empty($away_scorers)): ?>
                        <div class="match-scorers">
                            <div class="home-scorers">
                                <?php foreach($home_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                            </div>
                            <div class="away-scorers">
                                <?php foreach($away_scorers as $s) echo "<div class='scorer-row'>{$s}</div>"; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Upcoming Matches Section -->
    <?php if (!empty($upcoming_matches)): ?>
    <div class="dashboard-section">
        <h2 class="dashboard-title">Gameweek <?php echo $next_gameweek_to_show; ?></h2>
        <div class="fixture-list">
            <?php foreach ($upcoming_matches as $match): ?>
                <?php if ($hero_match && $match->id === $hero_match->id) continue; // Skip if shown in hero ?>
                <a href="fixture.php?id=<?php echo $match->id; ?>" class="fixture-item">
                    <div class="match-main-row">
                        <div class="team home-team">
                            <span class="team-name"><?php echo htmlspecialchars($match->home_team_name); ?></span>
                            <img src="<?php echo htmlspecialchars($match->home_team_logo); ?>" alt="" class="team-logo">
                        </div>
                        <?php if ($match->status === 'finished'): ?>
                            <div class="score-box finished">
                                <span class="score"><?php echo $match->home_team_score ?? 0; ?> - <?php echo $match->away_team_score ?? 0; ?></span>
                                <span class="status-label">FT</span>
                            </div>
                        <?php elseif (in_array($match->status, ['postponed', 'cancelled'])): ?>
                            <div class="score-box time-box">
                                <span class="status-label" style="color: #e74c3c;"><?php echo ucfirst($match->status); ?></span>
                                <span class="date"><?php echo date('d M', strtotime($match->match_datetime)); ?></span>
                            </div>
                        <?php else: ?>
                            <div class="score-box time-box">
                                <span class="time"><?php echo date('H:i', strtotime($match->match_datetime)); ?></span>
                                <span class="date"><?php echo date('d M', strtotime($match->match_datetime)); ?></span>
                            </div>
                        <?php endif; ?>
                        <div class="team away-team">
                            <img src="<?php echo htmlspecialchars($match->away_team_logo); ?>" alt="" class="team-logo">
                            <span class="team-name"><?php echo htmlspecialchars($match->away_team_name); ?></span>
                        </div>
                    </div>
                    <?php
                    // Display scorers for finished matches in the upcoming list
                    if ($match->status === 'finished' && isset($match->events)) {
                        $home_scorers = [];
                        $away_scorers = [];
                        foreach ($match->events as $event) {
                            if (in_array($event->event_type, ['goal', 'penalty_scored', 'own_goal'])) {
                                $pName = $match->player_names[$event->player_id] ?? 'Unknown';
                                $time = $event->minute . "'";
                                $str = "$pName $time";
                                if ($event->event_type === 'own_goal') $str .= " (OG)";
                                if ($event->event_type === 'penalty_scored') $str .= " (P)";
                                if ($event->team_id == $match->home_team_id) $home_scorers[] = $str;
                                else $away_scorers[] = $str;
                            }
                        }
                        if (!empty($home_scorers) || !empty($away_scorers)): ?>
                            <div class="match-scorers">
                                <div class="home-scorers"><?php echo implode(', ', $home_scorers); ?></div>
                                <div class="away-scorers"><?php echo implode(', ', $away_scorers); ?></div>
                            </div>
                        <?php endif;
                    }
                    ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- League Table Snapshot Section -->
    <?php if (!empty($table_snapshot)): ?>
    <div class="dashboard-section">
        <h2 class="dashboard-title">League Table</h2>
        <div class="table-wrapper-snapshot">
            <table class="styled-table mini">
                <thead><tr><th>#</th><th>Club</th><th>Pl</th><th>GD</th><th>Pts</th></tr></thead>
                <tbody>
                    <?php foreach ($table_snapshot as $index => $team): ?>
                    <tr>
                        <td><?php echo $index + 1; ?></td>
                        <td class="team-name-cell"><img src="<?php echo htmlspecialchars($team->logo ?? URL_ROOT . '/public/assets/images/default_crest.png'); ?>" alt="" class="table-logo"> <?php echo htmlspecialchars($team->team_name); ?></td>
                        <td><?php echo $team->played; ?></td>
                        <td><?php echo $team->goal_difference; ?></td>
                        <td><strong><?php echo $team->points; ?></strong></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <a href="matches.php?view=table&league_id=<?php echo $league_id; ?>" class="view-full-link">View Full Table</a>
    </div>
    <?php endif; ?>

    <!-- My Feed Section -->
    <div class="dashboard-section my-feed-section" id="my-feed">
        <h2 class="dashboard-title">My Feed</h2>
        <?php if (empty($feed_items)): ?>
            <div class="empty-feed-state">
                <i class="fa-solid fa-newspaper"></i>
                <p>Join a club to see personalized news, match reports, and team updates here.</p>
                <a href="memberships.php" class="btn btn-primary">Find a Club</a>
            </div>
        <?php else: ?>
            <div class="feed-grid" id="feed-grid-container">
                <?php 
                $adIndex = 0;
                foreach ($feed_items as $index => $item): 
                    $data = $item['data'];
                    $type_label = ucwords(str_replace('_', ' ', $item['type']));
                    
                    if ($item['type'] === 'match_report') {
                        $title = "Report: {$data->home_team_name} {$data->home_team_score}-{$data->away_team_score} {$data->away_team_name}";
                        $desc = "Full match analysis, player ratings, and key moments from the game.";
                        $img = $data->home_team_logo;
                    } elseif ($item['type'] === 'lineups_announced') {
                        $title = "Lineups: {$data->home_team_name} vs {$data->away_team_name}";
                        $desc = "Confirmed starting XIs and substitutes. See who made the cut.";
                        $img = $data->home_team_logo;
                    } elseif ($item['type'] === 'suspension') {
                        $title = "Suspension: {$data->first_name} {$data->last_name}";
                        $desc = "{$data->first_name} {$data->last_name} has received a suspension following a disciplinary incident.";
                        $img = $data->profile_picture ?? $data->club_logo;
                    } elseif ($item['type'] === 'injury_recovery') {
                        $title = "Injury Update: {$data->first_name} {$data->last_name}";
                        $desc = "Good news for {$data->club_name} as {$data->first_name} {$data->last_name} returns to full fitness.";
                        $img = $data->profile_picture ?? $data->club_logo;
                    } else {
                        $title = "Preview: {$data->home_team_name} vs {$data->away_team_name}";
                        $desc = "Team news, tactical analysis, and lineup predictions for the upcoming clash.";
                        $img = $data->away_team_logo;
                    }
                ?>
                <a href="feed_post.php?type=<?php echo $item['type']; ?>&id=<?php echo $item['id']; ?>" class="feed-card">
                    <div class="feed-img-container">
                        <img src="<?php echo htmlspecialchars($img); ?>" alt="Club Logo" class="feed-bg-logo">
                        <span class="feed-tag"><?php echo $type_label; ?></span>
                    </div>
                    <div class="feed-content">
                        <h3><?php echo htmlspecialchars($title); ?></h3>
                        <p><?php echo $desc; ?></p>
                        <span class="feed-time"><?php echo date('d M, H:i', $item['timestamp']); ?></span>
                    </div>
                </a>
                <?php 
                // Insert Ad after every 3rd item
                if (($index + 1) % 3 === 0 && isset($productAds[$adIndex])): 
                    $ad = $productAds[$adIndex];
                    $adIndex++;
                ?>
                <div class="feed-card sponsor-ad" data-campaign-id="<?php echo $ad->id; ?>" style="cursor: pointer; min-height: 250px;">
                    <div class="feed-img-container" style="height: 100%; min-height: 250px;">
                        <?php if ($ad->ad_type === 'video'): ?>
                            <video src="<?php echo htmlspecialchars($ad->ad_content); ?>" autoplay muted loop playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
                        <?php else: ?>
                            <img src="<?php echo htmlspecialchars($ad->ad_content); ?>" alt="Sponsored" style="width: 100%; height: 100%; object-fit: cover;">
                        <?php endif; ?>
                        <span class="feed-tag" style="background: #999;">Sponsored</span>
                    </div>
                </div>
                <?php endif; ?>
                <?php endforeach; ?>
            </div>
            <div id="feed-loader" style="text-align: center; padding: 20px; display: none;"><i class="fa-solid fa-spinner fa-spin" style="font-size: 2rem; color: var(--secondary-color);"></i></div>
            <div class="load-more-wrapper" style="text-align: center; margin-top: 20px;">
                <button id="load-more-btn" class="btn btn-secondary">Load More</button>
            </div>
        <?php endif; ?>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // --- Countdown Timer Logic ---
        const countdownTimer = document.getElementById('hero-countdown');
        if (countdownTimer) {
            const matchTime = new Date(countdownTimer.dataset.matchTime).getTime();

            const interval = setInterval(function() {
                const now = new Date().getTime();
                const distance = matchTime - now;

                if (distance < 0) {
                    clearInterval(interval);
                    countdownTimer.innerHTML = "<span class='starts-soon'>Starting Soon</span>";
                    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);

                countdownTimer.innerHTML = `
                    <span class="cd-part">${String(days).padStart(2, '0')}d</span> : 
                    <span class="cd-part">${String(hours).padStart(2, '0')}h</span> : 
                    <span class="cd-part">${String(minutes).padStart(2, '0')}m</span> : 
                    <span class="cd-part">${String(seconds).padStart(2, '0')}s</span>
                `;

            }, 1000);
        }


        // --- Live Timer Logic for Dashboard ---
        function formatTime(seconds) {
            const mins = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
        }

        function startTimer(element, initialElapsed, offsetMinutes) {
            const localStartTimestamp = Date.now();
            const fullTimeDuration = parseInt(element.dataset.fullTimeDuration || 90);
            const halfTimeMark = fullTimeDuration / 2;

            const interval = setInterval(() => {
                const now = Date.now();
                const delta = Math.floor((now - localStartTimestamp) / 1000);
                const totalElapsedSeconds = initialElapsed + delta;
                let displayMinutes = offsetMinutes + Math.floor(totalElapsedSeconds / 60);

                if (displayMinutes >= halfTimeMark && offsetMinutes < halfTimeMark) {
                    const stoppageMinutes = displayMinutes - halfTimeMark;
                    element.innerHTML = `${halfTimeMark}+${stoppageMinutes + 1}'`;
                } else if (displayMinutes >= fullTimeDuration) {
                    const stoppageMinutes = displayMinutes - fullTimeDuration;
                    element.innerHTML = `${fullTimeDuration}+${stoppageMinutes + 1}'`;
                } else {
                    element.innerHTML = `${displayMinutes + 1}'`;
                }
            }, 1000);
        }

        document.querySelectorAll('.live-timer').forEach(timerElement => {
            const firstHalfStart = timerElement.dataset.firstHalfStart;
            const secondHalfStart = timerElement.dataset.secondHalfStart;
            const status = timerElement.dataset.status;

            if (status === 'half_time') {
                timerElement.innerHTML = 'HT';
            } else if (status === 'live' && secondHalfStart && secondHalfStart !== '0000-00-00 00:00:00') {
                startTimer(timerElement, parseInt(timerElement.dataset.elapsedSecond), (parseInt(timerElement.dataset.fullTimeDuration || 90) / 2));
            } else if (status === 'live' && firstHalfStart && firstHalfStart !== '0000-00-00 00:00:00') {
                startTimer(timerElement, parseInt(timerElement.dataset.elapsedFirst), 0);
            } else {
                timerElement.innerHTML = 'Live'; // Fallback
            }
        });

        // --- Load More Button Logic ---
        let page = 1;
        let loading = false;
        const feedContainer = document.getElementById('feed-grid-container');
        const loader = document.getElementById('feed-loader');
        const loadMoreBtn = document.getElementById('load-more-btn');

        if (feedContainer && loadMoreBtn) {
            loadMoreBtn.addEventListener('click', () => {
                loadMoreFeed();
            });
        }

        function loadMoreFeed() {
            if (loading) return;
            loading = true;
            loader.style.display = 'block';
            loadMoreBtn.style.display = 'none';
            page++;

            fetch(`api/get_feed.php?page=${page}`)
                .then(response => response.text())
                .then(html => {
                    if (html.trim()) {
                        feedContainer.insertAdjacentHTML('beforeend', html);
                        loading = false;
                        loadMoreBtn.style.display = 'inline-block';
                    } else {
                        loadMoreBtn.style.display = 'none'; // No more content
                    }
                    loader.style.display = 'none';
                })
                .catch(err => {
                    console.error(err);
                    loading = false;
                    loader.style.display = 'none';
                    loadMoreBtn.style.display = 'inline-block';
                });
        }
    });
    </script>

</div>

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

<style>
/* === Modern Dashboard Styles === */
:root {
    --pl-purple: #37003c;
    --pl-green: #00ff85;
    --pl-pink: #e90052;
}
/* Transparent Header Override */
header {
    background: transparent !important;
    box-shadow: none !important;
    position: absolute !important;
    width: 100%;
    top: 0;
    z-index: 1000;
}

.dashboard-view {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 2.5rem;
}

/* --- Hero Section --- */
.dashboard-hero {
    background: linear-gradient(135deg, <?php echo $primary_color; ?> 0%, <?php echo $secondary_color; ?> 100%);
    border-radius: 0 0 30px 30px;
    padding: 6rem 20px 3rem 20px;
    color: white;
    position: relative;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-bottom: 2rem;
    transition: transform 0.3s ease;
}

.dashboard-hero:hover {
    transform: translateY(-3px);
    box-shadow: 0 15px 35px rgba(0,0,0,0.15);
}

.hero-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
    font-size: 0.9rem;
    opacity: 0.9;
    font-weight: 600;
    letter-spacing: 1px;
    text-transform: uppercase;
}

.league-badge {
    background: var(--pl-green);
    color: var(--pl-purple);
    padding: 5px 12px;
    border-radius: 20px;
}

.hero-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;
}

.match-status-badge {
    background: rgba(255,255,255,0.2);
    padding: 5px 15px;
    border-radius: 20px;
    backdrop-filter: blur(4px);
}

.match-status-badge.live {
    background: var(--live-color);
    box-shadow: 0 0 15px rgba(231, 76, 60, 0.4);
    animation: pulse-live 2s infinite;
}

.hero-match-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    text-decoration: none;
    color: white;
}

.hero-team {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1.2rem;
    text-align: center;
}

.hero-logo {
    width: 90px;
    height: 90px;
    object-fit: contain;
    filter: drop-shadow(0 5px 15px rgba(0,0,0,0.3));
    transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.hero-team:hover .hero-logo {
    transform: scale(1.1);
}

.hero-name {
    font-size: 1.2rem;
    font-weight: 700;
    max-width: 180px;
    line-height: 1.3;
}

.hero-center {
    flex: 0 0 140px;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.hero-score {
    font-size: 3.5rem;
    font-weight: 800;
    line-height: 1;
    margin-bottom: 0.5rem;
    text-shadow: 0 4px 20px rgba(0,0,0,0.3);
}

.hero-time {
    font-size: 3rem;
    font-weight: 700;
    letter-spacing: -1px;
}

#hero-countdown {
    font-size: 0.9rem;
    opacity: 0.9;
    margin-top: 10px;
    display: flex;
    gap: 8px;
    justify-content: center;
    background: rgba(0,0,0,0.2);
    padding: 5px 15px;
    border-radius: 20px;
}

.hero-scorers-list {
    margin-top: 10px;
    font-size: 0.85rem;
    line-height: 1.3;
    opacity: 0.9;
}

/* --- Section Titles --- */
.dashboard-title {
    font-size: 1.4rem;
    font-weight: 800;
    color: var(--text-color);
    margin-bottom: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    padding-left: 15px;
}

.dashboard-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 24px;
    width: 6px;
    background: var(--secondary-color);
    border-radius: 2px;
}

/* --- Stories / Highlights --- */
.stories-section {
    background: transparent !important;
    box-shadow: none !important;
    border: none !important;
    padding: 0 !important;
    margin-bottom: 1.5rem;
}

.stories-container {
    display: flex;
    gap: 18px;
    overflow-x: auto;
    padding: 5px 10px 15px 10px;
    scrollbar-width: none;
    -webkit-overflow-scrolling: touch;
}
.stories-container::-webkit-scrollbar { display: none; }

.story-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-decoration: none;
    cursor: pointer;
    flex-shrink: 0;
    width: 72px;
}

.story-ring {
    position: relative;
    width: 68px;
    height: 68px;
    border-radius: 50%;
    padding: 2px;
    background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 6px;
    transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.story-item:hover .story-ring {
    transform: scale(1.1);
    animation: spin 1.5s linear infinite;
}

.story-circle {
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 50%;
    border: 2px solid var(--bg-color, #f8f9fa);
    position: relative;
    overflow: hidden;
    background-color: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
}

.s-logo {
    width: 34px;
    height: 34px;
    object-fit: contain;
    position: absolute;
    padding: 2px;
}

.s-logo.home {
    top: 2px;
    left: 2px;
    z-index: 1;
}

.s-logo.away {
    bottom: 2px;
    right: 2px;
    background: rgba(255,255,255,0.8);
    border-radius: 50%;
    z-index: 2;
    box-shadow: -1px -1px 2px rgba(0,0,0,0.05);
}

.story-new-badge {
    position: absolute;
    bottom: -2px;
    right: -2px;
    background-color: var(--accent-color, #e90052);
    color: white;
    font-size: 0.6rem;
    font-weight: bold;
    padding: 2px 6px;
    border-radius: 8px;
    z-index: 3;
    border: 2px solid white;
}

.story-label {
    font-size: 0.75rem;
    color: var(--text-color);
    font-weight: 600;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
}

@keyframes spin {
    from { transform: rotate(0deg) scale(1.1); }
    to { transform: rotate(360deg) scale(1.1); }
}

/* --- Fixture List --- */
.fixture-list {
    display: flex;
    gap: 1.2rem;
    overflow-x: auto;
    padding-bottom: 10px;
}

.fixture-list.horizontal-scroll {
    flex-wrap: nowrap;
    scrollbar-width: none;
}

.live-matches-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.2rem;
    overflow-x: visible;
}

.fixture-item {
    background: var(--card-bg, #fff);
    border-radius: 14px;
    padding: 1.5rem;
    display: block; /* Changed from flex to block */
    text-decoration: none;
    color: var(--text-color);
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    border: 1px solid #e0e0e0;
    transition: all 0.25s cubic-bezier(0.25, 0.8, 0.25, 1);
    min-width: 300px;
}

.fixture-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.05);
    border-color: rgba(52, 152, 219, 0.3);
}

.fixture-item.live-match {
    border-left: 4px solid var(--live-color);
    background: linear-gradient(to right, #fff5f5, #fff);
}
.match-main-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}
.match-scorers {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    padding-top: 8px;
    border-top: 1px solid #f1f5f9;
    font-size: 0.75rem;
    color: #64748b;
    line-height: 1.4;
    align-items: flex-start;
}
.home-scorers { text-align: right; flex: 1; padding-right: 10px; }
.away-scorers { text-align: left; flex: 1; padding-left: 10px; }

.fixture-item .team {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 12px;
    font-weight: 700;
    font-size: 1rem;
}

.fixture-item .home-team { justify-content: flex-end; text-align: right; }
.fixture-item .away-team { justify-content: flex-start; text-align: left; }

.fixture-item .team-logo {
    width: 36px;
    height: 36px;
    object-fit: contain;
}
.team-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 150px;
}

.score-box {
    background: #f1f3f5;
    padding: 10px 16px;
    border-radius: 10px;
    min-width: 90px;
    text-align: center;
    margin: 0 15px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border-left: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
    flex-shrink: 0;
    white-space: nowrap;
}

.score-box.live {
    color: #e74c3c;
    background: rgba(231, 76, 60, 0.1);
}

.score-box .score {
    font-size: 1.4rem;
    font-weight: 800;
    line-height: 1.1;
}

.score-box .time {
    font-size: 1.2rem;
    font-weight: 700;
    color: var(--text-color);
}

.score-box .date, .score-box .status-label {
    font-size: 0.7rem;
    color: #95a5a6;
    font-weight: 600;
    text-transform: uppercase;
    margin-top: 4px;
}

.live-timer {
    font-size: 0.75rem;
    color: #e74c3c;
    font-weight: 700;
    text-transform: uppercase;
    margin-top: 4px;
    animation: pulse-text 1.5s infinite;
}

/* --- Table Snapshot --- */
.table-wrapper-snapshot {
    background: var(--card-bg, #fff);
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 2px 5px rgba(0,0,0,0.02);
    border: 1px solid rgba(0,0,0,0.05);
}

.styled-table.mini {
    width: 100%;
    border-collapse: collapse;
}

.styled-table.mini th {
    background: #f8f9fa;
    color: #95a5a6;
    font-weight: 700;
    text-transform: uppercase;
    font-size: 0.75rem;
    padding: 15px;
    text-align: center;
    letter-spacing: 0.5px;
}

.styled-table.mini td {
    padding: 15px;
    border-bottom: 1px solid #f1f3f5;
    text-align: center;
    font-size: 0.9rem;
    color: var(--text-color);
}

.styled-table.mini td.team-name-cell {
    text-align: left;
    display: flex;
    align-items: center;
    gap: 12px;
    font-weight: 600;
}

.styled-table.mini .table-logo {
    width: 28px;
    height: 28px;
    object-fit: contain;
}

.styled-table.mini tr:last-child td {
    border-bottom: none;
}

.styled-table.mini tr:hover td {
    background-color: #fcfcfc;
}

.view-full-link {
    display: inline-block;
    margin-top: 15px;
    color: var(--secondary-color);
    text-decoration: none;
    font-weight: 700;
    font-size: 0.95rem;
    transition: color 0.2s;
}

.view-full-link:hover {
    color: #2980b9;
    text-decoration: underline;
}

/* --- Animations --- */
@keyframes pulse-live {
    0% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.4); }
    70% { box-shadow: 0 0 0 10px rgba(231, 76, 60, 0); }
    100% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0); }
}

@keyframes pulse-text {
    0% { opacity: 1; }
    50% { opacity: 0.6; }
    100% { opacity: 1; }
}

/* --- Fixture List (Matches.php Style) --- */
.fixture-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.fixture-item {
    display: block;
    background: #fff;
    padding: 15px 20px;
    border-radius: 12px;
    text-decoration: none;
    color: inherit;
    box-shadow: 0 2px 5px rgba(0,0,0,0.03);
    transition: transform 0.2s, box-shadow 0.2s;
    border: 1px solid #f1f5f9;
}
.fixture-item:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.08); border-color: #e90052; }

.team { flex: 1; display: flex; align-items: center; gap: 12px; font-weight: 600; font-size: 1rem; color: #1e293b; }
.home-team { justify-content: flex-end; text-align: right; }
.away-team { justify-content: flex-start; text-align: left; }
.team-logo { width: 32px; height: 32px; object-fit: contain; }

.score-box {
    background: #f8fafc;
    padding: 5px 15px;
    border-radius: 8px;
    text-align: center;
    min-width: 80px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.score-box.live { background: #fff0f3; border: 1px solid #ffccd5; }
.score { font-size: 1.4rem; font-weight: 800; color: #37003c; line-height: 1; }
.time { font-size: 1.1rem; font-weight: 700; color: #333; }
.date, .status-label { font-size: 0.75rem; color: #888; text-transform: uppercase; margin-top: 2px; }
.live-timer { font-size: 0.75rem; color: #e90052; font-weight: bold; margin-top: 2px; animation: pulse 2s infinite; }

@media (max-width: 768px) {
    .team-name { display: none; } /* Hide names on small screens like matches.php usually does or adjust */
    .fixture-item { padding: 10px; }
}

/* --- My Feed Section --- */
.my-feed-section {
    margin-top: 2rem;
}

.feed-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
}

.feed-card {
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    text-decoration: none;
    color: inherit;
    transition: transform 0.2s;
    border: 1px solid #eee;
    display: flex;
    flex-direction: column;
}

.feed-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.feed-img-container {
    height: 160px;
    background: linear-gradient(45deg, #f3f4f6, #fff);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
}

.feed-bg-logo {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.feed-tag {
    position: absolute;
    top: 10px;
    left: 10px;
    background: var(--pl-purple);
    color: #fff;
    padding: 4px 10px;
    border-radius: 4px;
    font-size: 0.7rem;
    font-weight: 700;
    text-transform: uppercase;
}

.feed-content { padding: 20px; flex: 1; display: flex; flex-direction: column; }
.feed-content h3 { margin: 0 0 10px 0; font-size: 1.1rem; line-height: 1.4; color: var(--pl-purple); }
.feed-content p { font-size: 0.9rem; color: #666; margin-bottom: 15px; flex: 1; }
.feed-time { font-size: 0.8rem; color: #999; }
.empty-feed-state { text-align: center; padding: 40px; background: #fff; border-radius: 12px; }
.empty-feed-state i { font-size: 3rem; color: #ddd; margin-bottom: 15px; }

@media (max-width: 768px) {
    .hero-logo { width: 60px; height: 60px; }
    .hero-score { font-size: 2.5rem; }
    .hero-time { font-size: 2rem; }
    .fixture-list { grid-template-columns: 1fr; }
    .dashboard-view { padding: 15px; gap: 2rem; }
    .hero-header { margin-bottom: 1rem; }
    .hero-team { gap: 0.5rem; }
}

/* Announcements */
.announcement-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
}
.announcement-card {
    background: var(--card-bg, #fff);
    padding: 20px;
    border-radius: 12px;
    border-left: 5px solid var(--secondary-color);
    box-shadow: 0 2px 5px rgba(0,0,0,0.02);
    transition: transform 0.2s;
}
.announcement-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.05);
}
.announcement-card.type-alert { border-left-color: #e74c3c; background: rgba(231, 76, 60, 0.05); }
.announcement-card.type-info { border-left-color: #3498db; }
.announcement-card.type-news { border-left-color: #2ecc71; }

.announcement-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 0.85rem;
    color: #7f8c8d;
}
.announcement-tag {
    font-weight: 700;
    text-transform: uppercase;
    font-size: 0.7rem;
    padding: 3px 8px;
    border-radius: 4px;
    background: rgba(0,0,0,0.05);
    letter-spacing: 0.5px;
}
.announcement-card h3 {
    margin: 0 0 10px 0;
    font-size: 1.2rem;
    color: var(--text-color);
}
.announcement-content {
    color: var(--text-color);
    opacity: 0.9;
    line-height: 1.6;
    font-size: 0.95rem;
}
</style>