<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once dirname(__DIR__) . '/modules/fixtures/helpers.php';

function match_card_scorer_name(array $event): string
{
    $playerName = trim((string) (($event['first_name'] ?? '') . ' ' . ($event['last_name'] ?? '')));

    if ($playerName === '') {
        $playerName = (string) ($event['club_name'] ?? 'Unknown');
    }

    return match ((string) ($event['event_type'] ?? '')) {
        'penalty_goal' => $playerName . ' (P)',
        'own_goal' => $playerName . ' (OG)',
        default => $playerName,
    };
}

function match_card_event_minute(array $event): string
{
    $minute = (string) ($event['minute'] ?? '0');
    $extraMinute = isset($event['extra_minute']) && $event['extra_minute'] !== null
        ? '+' . (string) $event['extra_minute']
        : '';

    return trim($minute . $extraMinute) . "'";
}

function public_fixture_kit_color_value(string $value): string
{
    $value = trim($value);

    if ($value === '') {
        return '#dfe6e1';
    }

    if (preg_match('/^[#(),.%\- a-zA-Z0-9]+$/', $value) === 1) {
        return $value;
    }

    return '#dfe6e1';
}

function public_fixture_kit_chip(string $label, ?string $value): string
{
    $displayValue = trim((string) $value);

    if ($displayValue === '') {
        $displayValue = 'TBC';
    }

    $swatchColor = public_fixture_kit_color_value($displayValue);

    return sprintf(
        '<span class="badge rounded-pill text-dark border border-dark-subtle bg-light d-inline-flex align-items-center gap-2 me-2 mb-2"><span aria-hidden="true" style="display:inline-block;width:0.9rem;height:0.9rem;border-radius:999px;background:%s;border:1px solid rgba(15, 23, 42, 0.15);"></span><span>%s: %s</span></span>',
        e($swatchColor),
        e($label),
        e($displayValue)
    );
}

$fixtureId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$fixture = null;
$events = [];
$goalSummary = ['home' => [], 'away' => []];
$publishedFormations = [];
$publishedLineupsByClub = [];
$formationPublishLive = false;
$homeConfirmedKit = null;
$awayConfirmedKit = null;
$showConfirmedKits = false;
$relatedNewsPosts = [];

if ($fixtureId > 0) {
    try {
        $fixture = db_fetch_one(
            'SELECT f.id, f.matchday, f.match_date, f.match_time, f.status, f.stage_type, f.group_label, f.knockout_round,
                    hc.id AS home_club_id, ac.id AS away_club_id,
                    hc.name AS home_club, hc.short_name AS home_short_name, hc.logo AS home_logo,
                    ac.name AS away_club, ac.short_name AS away_short_name, ac.logo AS away_logo,
                    c.name AS competition_name, c.type AS competition_type, v.name AS venue_name,
                    mr.home_score, mr.away_score, mr.result_status
             FROM fixtures f
             INNER JOIN clubs hc ON hc.id = f.home_club_id
             INNER JOIN clubs ac ON ac.id = f.away_club_id
             INNER JOIN competitions c ON c.id = f.competition_id
             LEFT JOIN venues v ON v.id = f.venue_id
             LEFT JOIN match_results mr ON mr.fixture_id = f.id
             WHERE f.id = :id
             LIMIT 1',
            ['id' => $fixtureId]
        );

        if ($fixture !== null) {
            $homeConfirmedKit = fixture_kit_record_for_club((int) $fixture['id'], (int) $fixture['home_club_id']);
            $awayConfirmedKit = fixture_kit_record_for_club((int) $fixture['id'], (int) $fixture['away_club_id']);
            $showConfirmedKits = $homeConfirmedKit !== null
                && $awayConfirmedKit !== null
                && !empty($homeConfirmedKit['confirmed_at'])
                && !empty($awayConfirmedKit['confirmed_at']);

            $relatedNewsPosts = db_fetch_all(
                'SELECT title, slug, category, published_at, created_at
                 FROM news_posts
                 WHERE fixture_id = :fixture_id
                   AND status = :status
                 ORDER BY COALESCE(published_at, created_at) DESC
                 LIMIT 4',
                ['fixture_id' => $fixtureId, 'status' => 'published']
            );

            $kickoffTimestamp = strtotime(trim((string) (($fixture['match_date'] ?? '') . ' ' . ($fixture['match_time'] ?? ''))));
            $formationPublishLive = $kickoffTimestamp !== false && (time() >= ($kickoffTimestamp - 3600));
            $publishedFormations = published_fixture_formations($fixtureId);
            foreach ($publishedFormations as $formation) {
                $publishedLineupsByClub[(int) $formation['club_id']] = $formation['lineup'] ?? ['starters' => [], 'substitutes' => []];
            }

            $events = db_fetch_all(
                'SELECT me.club_id, me.event_type, me.minute, me.extra_minute, me.notes,
                        p.first_name, p.last_name, cl.name AS club_name
                 FROM match_events me
                 LEFT JOIN players p ON p.id = me.player_id
                 INNER JOIN clubs cl ON cl.id = me.club_id
                 WHERE me.fixture_id = :fixture_id
                 ORDER BY me.minute ASC, me.extra_minute ASC, me.id ASC',
                ['fixture_id' => $fixtureId]
            );

            foreach ($events as $event) {
                if (!in_array((string) ($event['event_type'] ?? ''), ['goal', 'penalty_goal', 'own_goal'], true)) {
                    continue;
                }

                $bucket = (int) ($event['club_id'] ?? 0) === (int) ($fixture['home_club_id'] ?? 0) ? 'home' : 'away';
                if ((string) ($event['event_type'] ?? '') === 'own_goal') {
                    $bucket = $bucket === 'home' ? 'away' : 'home';
                }

                $goalSummary[$bucket][] = match_card_scorer_name($event) . ' ' . match_card_event_minute($event);
            }
        }
    } catch (Throwable) {
    }
}

$renderPublicPage = 'render_public_page';

$shareUrl = absolute_url('app/public/match-details.php?id=' . $fixtureId);
$shareImageUrl = absolute_url('app/public/match-share-image.php?id=' . $fixtureId);
$shareTitle = $fixture !== null
    ? ($fixture['home_club'] . ' vs ' . $fixture['away_club'] . ' - ' . $fixture['competition_name'])
    : 'Match Details';
$shareDescription = $fixture !== null
    ? ('Matchday ' . (string) $fixture['matchday'] . ' fixture details, banner, and lineup updates for ' . $fixture['home_club'] . ' vs ' . $fixture['away_club'] . '.')
    : 'Fixture summary, scoreline, and verified event log.';
$whatsAppShareUrl = 'https://wa.me/?text=' . rawurlencode($shareTitle . ' ' . $shareUrl);
$facebookShareUrl = 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode($shareUrl);

$renderPublicPage('Match Details', 'Fixture summary, scoreline, and verified event log.', static function () use ($fixture, $events, $goalSummary, $publishedFormations, $publishedLineupsByClub, $formationPublishLive, $whatsAppShareUrl, $facebookShareUrl, $homeConfirmedKit, $awayConfirmedKit, $showConfirmedKits, $relatedNewsPosts): void {
?>
    <section class="panel-card">
        <?php if ($fixture === null): ?>
            <p class="text-muted mb-0">Select a match from the results page to view details.</p>
        <?php else: ?>
            <?php $stageLabel = competition_stage_label($fixture); ?>
            <?php $homePublishedLineup = $publishedLineupsByClub[(int) $fixture['home_club_id']] ?? ['starters' => [], 'substitutes' => []]; ?>
            <?php $awayPublishedLineup = $publishedLineupsByClub[(int) $fixture['away_club_id']] ?? ['starters' => [], 'substitutes' => []]; ?>
            <?php $hasPublishedLineups = $homePublishedLineup['starters'] !== [] || $homePublishedLineup['substitutes'] !== [] || $awayPublishedLineup['starters'] !== [] || $awayPublishedLineup['substitutes'] !== []; ?>
            <p class="eyebrow mb-1"><?php echo e($fixture['competition_name']); ?></p>
            <h2 class="h3 mb-2"><?php echo e($fixture['home_club']); ?> <?php echo e((string) ($fixture['home_score'] ?? 0)); ?> - <?php echo e((string) ($fixture['away_score'] ?? 0)); ?> <?php echo e($fixture['away_club']); ?></h2>
            <p class="text-muted mb-4">Matchday <?php echo e((string) $fixture['matchday']); ?> &middot; <?php echo e(format_match_date_time($fixture['match_date'] ?? null, $fixture['match_time'] ?? null, '-', 'Time TBC')); ?> &middot; <?php echo e(ucfirst((string) ($fixture['result_status'] ?? $fixture['status']))); ?></p>

            <div class="match-share-wrap mb-4">
                <div class="match-share-preview-shell" data-match-card-shell>
                    <div class="match-share-download-card" id="matchShareCard" data-match-card-preview>
                        <div class="match-share-poster-top">
                            <div class="match-share-poster-kicker"><?php echo e(league_short_name()); ?> Official</div>
                            <h3 class="match-share-poster-title"><?php echo e($fixture['competition_name']); ?></h3>
                            <div class="match-share-poster-subtitle">Matchday <?php echo e((string) $fixture['matchday']); ?> &middot; <?php echo e($stageLabel); ?></div>
                        </div>
                        <div class="match-share-card">
                            <div class="match-share-ribbon-row">
                                <div class="match-share-ribbon-side">
                                    <span class="match-share-ribbon-label">Home team</span>
                                    <div class="match-share-ribbon-logo">
                                        <?php if (!empty($fixture['home_logo'])): ?>
                                            <img src="<?php echo e(base_url((string) $fixture['home_logo'])); ?>" alt="<?php echo e($fixture['home_club']); ?> logo">
                                        <?php else: ?>
                                            <span><?php echo e($fixture['home_short_name'] ?: mb_substr((string) $fixture['home_club'], 0, 3)); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="match-share-ribbon-team-name"><?php echo e($fixture['home_club']); ?></div>
                                </div>
                                <div class="match-share-ribbon-center">
                                    <span class="match-share-ribbon-center-label"><?php echo e($fixture['competition_name']); ?></span>
                                    <strong class="match-share-ribbon-center-score">
                                        <?php if ($fixture['home_score'] !== null && $fixture['away_score'] !== null): ?>
                                            <?php echo e((string) $fixture['home_score']); ?> - <?php echo e((string) $fixture['away_score']); ?>
                                        <?php else: ?>
                                            VS
                                        <?php endif; ?>
                                    </strong>
                                    <span class="match-share-ribbon-center-stage"><?php echo e($stageLabel); ?></span>
                                </div>
                                <div class="match-share-ribbon-side match-share-ribbon-side-away">
                                    <span class="match-share-ribbon-label">Away team</span>
                                    <div class="match-share-ribbon-logo">
                                        <?php if (!empty($fixture['away_logo'])): ?>
                                            <img src="<?php echo e(base_url((string) $fixture['away_logo'])); ?>" alt="<?php echo e($fixture['away_club']); ?> logo">
                                        <?php else: ?>
                                            <span><?php echo e($fixture['away_short_name'] ?: mb_substr((string) $fixture['away_club'], 0, 3)); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="match-share-ribbon-team-name"><?php echo e($fixture['away_club']); ?></div>
                                </div>
                            </div>
                            <div class="match-share-venue-block">
                                <div class="match-share-venue-title"><?php echo e($fixture['venue_name'] ?? 'Venue TBC'); ?></div>
                                <div class="match-share-venue-divider"></div>
                                <div class="match-share-venue-time"><?php echo e(format_time_12h($fixture['match_time'] ?? null, 'Time TBC')); ?></div>
                                <div class="match-share-venue-meta"><?php echo e($fixture['match_date'] ?? 'Date TBC'); ?> &middot; <?php echo e(ucfirst((string) ($fixture['result_status'] ?? $fixture['status']))); ?></div>
                            </div>
                            <?php if ($goalSummary['home'] !== [] || $goalSummary['away'] !== []): ?>
                                <div class="match-share-scorers">
                                    <div class="match-share-scorers-title">Goalscorers</div>
                                    <div class="match-share-scorers-grid">
                                        <div class="match-share-scorers-team">
                                            <div class="match-share-scorers-team-name"><?php echo e($fixture['home_club']); ?></div>
                                            <div class="match-share-scorers-list"><?php echo e($goalSummary['home'] !== [] ? implode(' , ', $goalSummary['home']) : 'No scorers recorded'); ?></div>
                                        </div>
                                        <div class="match-share-scorers-team match-share-scorers-team-away">
                                            <div class="match-share-scorers-team-name"><?php echo e($fixture['away_club']); ?></div>
                                            <div class="match-share-scorers-list"><?php echo e($goalSummary['away'] !== [] ? implode(' , ', $goalSummary['away']) : 'No scorers recorded'); ?></div>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <?php if ($formationPublishLive && $hasPublishedLineups): ?>
                                <div class="match-share-lineups">
                                    <div class="match-share-lineups-title">Starting XI and substitutes</div>
                                    <div class="match-share-lineups-grid">
                                        <article class="match-share-lineup-card">
                                            <div class="match-share-lineup-head">
                                                <strong><?php echo e($fixture['home_club']); ?></strong>
                                                <span>11 starters + 5 substitutes</span>
                                            </div>
                                            <div class="match-share-lineup-section-label">Starting XI</div>
                                            <ul class="match-share-lineup-list">
                                                <?php if ($homePublishedLineup['starters'] === []): ?>
                                                    <li>Lineup pending</li>
                                                <?php else: ?>
                                                    <?php foreach ($homePublishedLineup['starters'] as $player): ?>
                                                        <li><?php echo e(fixture_lineup_player_label($player)); ?></li>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </ul>
                                            <div class="match-share-lineup-section-label">Substitutes</div>
                                            <ul class="match-share-lineup-list match-share-lineup-list-substitutes">
                                                <?php if ($homePublishedLineup['substitutes'] === []): ?>
                                                    <li>Bench pending</li>
                                                <?php else: ?>
                                                    <?php foreach ($homePublishedLineup['substitutes'] as $player): ?>
                                                        <li><?php echo e(fixture_lineup_player_label($player)); ?></li>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </ul>
                                        </article>
                                        <article class="match-share-lineup-card">
                                            <div class="match-share-lineup-head">
                                                <strong><?php echo e($fixture['away_club']); ?></strong>
                                                <span>11 starters + 5 substitutes</span>
                                            </div>
                                            <div class="match-share-lineup-section-label">Starting XI</div>
                                            <ul class="match-share-lineup-list">
                                                <?php if ($awayPublishedLineup['starters'] === []): ?>
                                                    <li>Lineup pending</li>
                                                <?php else: ?>
                                                    <?php foreach ($awayPublishedLineup['starters'] as $player): ?>
                                                        <li><?php echo e(fixture_lineup_player_label($player)); ?></li>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </ul>
                                            <div class="match-share-lineup-section-label">Substitutes</div>
                                            <ul class="match-share-lineup-list match-share-lineup-list-substitutes">
                                                <?php if ($awayPublishedLineup['substitutes'] === []): ?>
                                                    <li>Bench pending</li>
                                                <?php else: ?>
                                                    <?php foreach ($awayPublishedLineup['substitutes'] as $player): ?>
                                                        <li><?php echo e(fixture_lineup_player_label($player)); ?></li>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </ul>
                                        </article>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <?php if ($formationPublishLive && $publishedFormations !== []): ?>
                                <div class="match-share-formations">
                                    <div class="match-share-formations-title">Coach lineups</div>
                                    <div class="match-share-formations-grid">
                                        <?php foreach ($publishedFormations as $formation): ?>
                                            <div class="match-share-formation-item">
                                                <div class="match-share-formation-head">
                                                    <div class="match-share-formation-club-wrap">
                                                        <div class="match-share-formation-logo">
                                                            <?php if (!empty($formation['club_logo'])): ?>
                                                                <img src="<?php echo e(base_url((string) $formation['club_logo'])); ?>" alt="<?php echo e($formation['club_name']); ?> logo">
                                                            <?php else: ?>
                                                                <span><?php echo e($formation['club_short_name'] ?: mb_substr((string) $formation['club_name'], 0, 3)); ?></span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div>
                                                            <span class="match-share-formation-club"><?php echo e($formation['club_name']); ?></span>
                                                            <span class="match-share-formation-source">Coach submission</span>
                                                        </div>
                                                    </div>
                                                    <strong class="match-share-formation-shape"><?php echo e($formation['formation']); ?></strong>
                                                </div>
                                                <?php if (!empty($formation['tactical_notes'])): ?>
                                                    <p class="match-share-formation-note"><?php echo e($formation['tactical_notes']); ?></p>
                                                <?php else: ?>
                                                    <p class="match-share-formation-note">Formation published from the club lineup update.</p>
                                                <?php endif; ?>
                                                <?php $formationLineup = $formation['lineup'] ?? ['starters' => [], 'substitutes' => []]; ?>
                                                <?php if ($formationLineup['starters'] !== [] || $formationLineup['substitutes'] !== []): ?>
                                                    <div class="match-share-formation-lineup-meta">
                                                        <strong>Starting XI:</strong>
                                                        <span><?php echo e(implode(', ', array_map('fixture_lineup_player_label', $formationLineup['starters']))); ?></span>
                                                    </div>
                                                    <div class="match-share-formation-lineup-meta">
                                                        <strong>Substitutes:</strong>
                                                        <span><?php echo e(implode(', ', array_map('fixture_lineup_player_label', $formationLineup['substitutes']))); ?></span>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <div class="match-share-pitch-markings"></div>
                        </div>
                    </div>
                </div>
                <div class="d-flex gap-2 flex-wrap mt-3">
                    <button class="btn btn-jlfc btn-sm" type="button" data-download-match-card data-card-target="#matchShareCard" data-file-name="match-<?php echo e((string) $fixture['id']); ?>-status.png">
                        <i class="bi bi-download"></i> Download status card
                    </button>
                    <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e($whatsAppShareUrl); ?>" target="_blank" rel="noopener noreferrer">
                        <i class="bi bi-whatsapp"></i> Share to WhatsApp
                    </a>
                    <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e($facebookShareUrl); ?>" target="_blank" rel="noopener noreferrer">
                        <i class="bi bi-facebook"></i> Share to Facebook
                    </a>
                </div>
            </div>

            <?php if ($showConfirmedKits): ?>
                <div class="panel-card mb-4 border-0 shadow-sm bg-light">
                    <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap mb-3">
                        <div>
                            <p class="eyebrow mb-1">Matchday kits</p>
                            <h3 class="h5 mb-0">Officially confirmed colors</h3>
                        </div>
                        <span class="badge bg-dark-subtle text-dark-emphasis">Verified pre-match</span>
                    </div>
                    <div class="row g-3">
                        <div class="col-12 col-lg-6">
                            <article class="border rounded-4 p-3 h-100 bg-white">
                                <p class="fw-semibold mb-2"><?php echo e($fixture['home_club']); ?></p>
                                <div class="small text-muted mb-2">Confirmed kit for this fixture.</div>
                                <div class="mb-1"><?php echo public_fixture_kit_chip('Shirt', (string) ($homeConfirmedKit['shirt_color'] ?? '')); ?></div>
                                <div class="mb-1"><?php echo public_fixture_kit_chip('Shorts', (string) ($homeConfirmedKit['shorts_color'] ?? '')); ?></div>
                                <div class="mb-1"><?php echo public_fixture_kit_chip('Socks', (string) ($homeConfirmedKit['socks_color'] ?? '')); ?></div>
                                <div><?php echo public_fixture_kit_chip('Goalkeeper', trim((string) (($homeConfirmedKit['goalkeeper_shirt_color'] ?? '') . ' / ' . ($homeConfirmedKit['goalkeeper_shorts_color'] ?? '')))); ?></div>
                            </article>
                        </div>
                        <div class="col-12 col-lg-6">
                            <article class="border rounded-4 p-3 h-100 bg-white">
                                <p class="fw-semibold mb-2"><?php echo e($fixture['away_club']); ?></p>
                                <div class="small text-muted mb-2">Confirmed kit for this fixture.</div>
                                <div class="mb-1"><?php echo public_fixture_kit_chip('Shirt', (string) ($awayConfirmedKit['shirt_color'] ?? '')); ?></div>
                                <div class="mb-1"><?php echo public_fixture_kit_chip('Shorts', (string) ($awayConfirmedKit['shorts_color'] ?? '')); ?></div>
                                <div class="mb-1"><?php echo public_fixture_kit_chip('Socks', (string) ($awayConfirmedKit['socks_color'] ?? '')); ?></div>
                                <div><?php echo public_fixture_kit_chip('Goalkeeper', trim((string) (($awayConfirmedKit['goalkeeper_shirt_color'] ?? '') . ' / ' . ($awayConfirmedKit['goalkeeper_shorts_color'] ?? '')))); ?></div>
                            </article>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($relatedNewsPosts !== []): ?>
                <div class="panel-card mb-4 border-0 shadow-sm bg-light">
                    <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap mb-3">
                        <div>
                            <p class="eyebrow mb-1">Fixture newsroom</p>
                            <h3 class="h5 mb-0">Related published stories</h3>
                        </div>
                        <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/news.php')); ?>">All news</a>
                    </div>
                    <div class="row g-3">
                        <?php foreach ($relatedNewsPosts as $relatedPost): ?>
                            <div class="col-12 col-lg-6">
                                <article class="border rounded-4 p-3 h-100 bg-white">
                                    <p class="eyebrow mb-1"><?php echo e((string) ($relatedPost['published_at'] ?? $relatedPost['created_at'])); ?></p>
                                    <h4 class="h6 mb-2"><?php echo e($relatedPost['title']); ?></h4>
                                    <p class="small text-muted mb-3"><?php echo e(ucwords(str_replace('_', ' ', (string) $relatedPost['category']))); ?></p>
                                    <div class="d-flex gap-2 flex-wrap">
                                        <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/news-details.php?slug=' . urlencode((string) $relatedPost['slug']))); ?>">Read story</a>
                                        <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/news.php')); ?>">More news</a>
                                    </div>
                                </article>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <div class="match-formations-section mb-4">
                <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap mb-3">
                    <div>
                        <p class="eyebrow mb-1">Match lineups</p>
                        <h3 class="h5 mb-0">Published formations</h3>
                    </div>
                    <span class="text-muted small">
                        <?php echo $formationPublishLive ? 'Formations are visible from one hour before kickoff.' : 'Formations will appear automatically one hour before kickoff.'; ?>
                    </span>
                </div>
                <?php if (!$formationPublishLive): ?>
                    <p class="text-muted mb-0">Check back closer to kickoff to see the submitted match shapes.</p>
                <?php elseif ($publishedFormations === []): ?>
                    <p class="text-muted mb-0">No formations have been published for this fixture yet.</p>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($publishedFormations as $formation): ?>
                            <div class="col-12 col-lg-6">
                                <article class="match-formation-card h-100">
                                    <div class="d-flex align-items-center gap-3 mb-3">
                                        <div class="match-formation-logo">
                                            <?php if (!empty($formation['club_logo'])): ?>
                                                <img src="<?php echo e(base_url((string) $formation['club_logo'])); ?>" alt="<?php echo e($formation['club_name']); ?> logo">
                                            <?php else: ?>
                                                <span><?php echo e($formation['club_short_name'] ?: mb_substr((string) $formation['club_name'], 0, 3)); ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <div>
                                            <p class="mb-1 fw-semibold"><?php echo e($formation['club_name']); ?></p>
                                            <div class="match-formation-shape"><?php echo e($formation['formation']); ?></div>
                                        </div>
                                    </div>
                                    <p class="small text-muted mb-2">Updated <?php echo e((string) $formation['submitted_at']); ?></p>
                                    <?php if (!empty($formation['tactical_notes'])): ?>
                                        <p class="mb-0 text-muted"><?php echo e($formation['tactical_notes']); ?></p>
                                    <?php else: ?>
                                        <p class="mb-0 text-muted">Tactical notes were not published for this lineup.</p>
                                    <?php endif; ?>
                                    <?php $formationLineup = $formation['lineup'] ?? ['starters' => [], 'substitutes' => []]; ?>
                                    <?php if ($formationLineup['starters'] !== [] || $formationLineup['substitutes'] !== []): ?>
                                        <div class="small text-muted mt-3"><strong class="text-dark">Starting XI:</strong> <?php echo e(implode(', ', array_map('fixture_lineup_player_label', $formationLineup['starters']))); ?></div>
                                        <div class="small text-muted mt-2"><strong class="text-dark">Substitutes:</strong> <?php echo e(implode(', ', array_map('fixture_lineup_player_label', $formationLineup['substitutes']))); ?></div>
                                    <?php endif; ?>
                                </article>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <h3 class="h5 mb-3">Event log</h3>
            <?php if ($events === []): ?>
                <p class="text-muted mb-0">No match events are available for this fixture yet.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table align-middle">
                        <thead>
                            <tr>
                                <th>Minute</th>
                                <th>Event</th>
                                <th>Player</th>
                                <th>Club</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($events as $event): ?>
                                <tr>
                                    <td><?php echo e((string) $event['minute']); ?><?php echo $event['extra_minute'] ? '+' . e((string) $event['extra_minute']) : ''; ?></td>
                                    <td><?php echo e(str_replace('_', ' ', ucfirst($event['event_type']))); ?></td>
                                    <td><?php echo e(trim(($event['first_name'] ?? '') . ' ' . ($event['last_name'] ?? '')) ?: 'N/A'); ?></td>
                                    <td><?php echo e($event['club_name']); ?></td>
                                    <td><?php echo e($event['notes'] ?? '-'); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    const downloadButton = document.querySelector('[data-download-match-card]');
                    const previewCard = document.querySelector('[data-match-card-preview]');
                    const previewShell = document.querySelector('[data-match-card-shell]');
                    const desktopCardWidth = 480;

                    const syncMatchCardPreviewScale = function() {
                        if (!previewCard || !previewShell) {
                            return;
                        }

                        const shellWidth = previewShell.clientWidth;
                        const scale = shellWidth > 0 && shellWidth < desktopCardWidth ?
                            shellWidth / desktopCardWidth :
                            1;

                        previewCard.style.transformOrigin = 'top center';
                        previewCard.style.transform = scale < 1 ? 'scale(' + scale + ')' : '';
                        previewShell.style.height = Math.ceil(previewCard.offsetHeight * scale) + 'px';
                    };

                    syncMatchCardPreviewScale();
                    window.addEventListener('resize', syncMatchCardPreviewScale);

                    if (!downloadButton || typeof html2canvas === 'undefined') {
                        return;
                    }

                    downloadButton.addEventListener('click', async function() {
                        const target = document.querySelector(downloadButton.getAttribute('data-card-target'));
                        if (!target) {
                            return;
                        }

                        const previousTransform = target.style.transform;
                        const previousTransformOrigin = target.style.transformOrigin;
                        if (previewShell) {
                            previewShell.style.height = target.offsetHeight + 'px';
                        }

                        target.style.transform = '';
                        target.style.transformOrigin = 'top center';

                        const canvas = await html2canvas(target, {
                            backgroundColor: '#f7fbf7',
                            scale: 2,
                            useCORS: true
                        });

                        target.style.transform = previousTransform;
                        target.style.transformOrigin = previousTransformOrigin;
                        syncMatchCardPreviewScale();

                        const link = document.createElement('a');
                        link.download = downloadButton.getAttribute('data-file-name') || 'match-status-card.png';
                        link.href = canvas.toDataURL('image/png');
                        link.click();
                    });
                });
            </script>
        <?php endif; ?>
    </section>
<?php
}, [
    'description' => $shareDescription,
    'url' => $shareUrl,
    'image' => $shareImageUrl,
    'type' => 'article',
]);
