<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Bootstrap dan session
|--------------------------------------------------------------------------
*/

$bootstrapFile = __DIR__ . '/bootstrap.php';

if (is_file($bootstrapFile)) {
    require_once $bootstrapFile;
}

if (session_status() === PHP_SESSION_NONE) {
    session_name('USERSESSID');
    session_start();
}

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string) $value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

/*
|--------------------------------------------------------------------------
| Informasi halaman
|--------------------------------------------------------------------------
*/

$siteName = isset($siteName)
    ? (string) $siteName
    : 'Platform Online';

$pageTitle = 'Event & Turnamen';
$activeMenu = 'event';

$isLoggedIn = !empty($_SESSION['user_id']);

$userId = $isLoggedIn
    ? (int) $_SESSION['user_id']
    : 0;

$username = isset($_SESSION['username'])
    ? (string) $_SESSION['username']
    : 'Pengunjung';

/*
|--------------------------------------------------------------------------
| Koneksi database PDO
|--------------------------------------------------------------------------
*/

$databaseFile = __DIR__ . '/config/database.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    if (!is_file($databaseFile)) {
        http_response_code(500);

        exit(
            'File koneksi database tidak ditemukan: ' .
            e($databaseFile)
        );
    }

    require_once $databaseFile;
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);

    exit(
        'Koneksi PDO $pdo tidak tersedia dari config/database.php.'
    );
}

$pdo->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);

$pdo->setAttribute(
    PDO::ATTR_DEFAULT_FETCH_MODE,
    PDO::FETCH_ASSOC
);

/*
|--------------------------------------------------------------------------
| Helper
|--------------------------------------------------------------------------
*/

function eventSafeSlug($value)
{
    $value = strtolower(trim((string) $value));

    if (
        $value === '' ||
        !preg_match('/^[a-z0-9][a-z0-9\-]{0,169}$/', $value)
    ) {
        return '';
    }

    return $value;
}

function eventSafeUrl($value)
{
    $value = trim((string) $value);

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

    if (
        preg_match('/^https?:\/\//i', $value) ||
        preg_match('/^(mailto:|tel:)/i', $value)
    ) {
        return $value;
    }

    if (
        strpos($value, '//') === 0 ||
        preg_match('/[\r\n]/', $value)
    ) {
        return '#';
    }

    return ltrim($value, '/');
}

function eventDateLabel($value)
{
    if (empty($value)) {
        return '-';
    }

    $timestamp = strtotime((string) $value);

    if ($timestamp === false) {
        return '-';
    }

    $months = [
        1 => 'Jan',
        2 => 'Feb',
        3 => 'Mar',
        4 => 'Apr',
        5 => 'Mei',
        6 => 'Jun',
        7 => 'Jul',
        8 => 'Agu',
        9 => 'Sep',
        10 => 'Okt',
        11 => 'Nov',
        12 => 'Des',
    ];

    return
        date('j', $timestamp) .
        ' ' .
        $months[(int) date('n', $timestamp)] .
        ' ' .
        date('Y H:i', $timestamp);
}

function eventStatus($startAt, $endAt)
{
    $now = time();

    $startTimestamp = $startAt
        ? strtotime((string) $startAt)
        : false;

    $endTimestamp = $endAt
        ? strtotime((string) $endAt)
        : false;

    if (
        $startTimestamp !== false &&
        $now < $startTimestamp
    ) {
        return 'UPCOMING';
    }

    if (
        $endTimestamp !== false &&
        $now > $endTimestamp
    ) {
        return 'ENDED';
    }

    return 'LIVE';
}

function eventStatusLabel($status)
{
    if ($status === 'UPCOMING') {
        return 'SEGERA';
    }

    if ($status === 'ENDED') {
        return 'SELESAI';
    }

    return 'LIVE';
}

/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/

if (
    empty($_SESSION['event_csrf']) ||
    !is_string($_SESSION['event_csrf'])
) {
    $_SESSION['event_csrf'] =
        bin2hex(random_bytes(32));
}

$csrfToken = (string) $_SESSION['event_csrf'];

/*
|--------------------------------------------------------------------------
| Flash message
|--------------------------------------------------------------------------
*/

$flashMessage = '';
$flashType = 'success';

if (
    isset($_SESSION['event_flash']) &&
    is_array($_SESSION['event_flash'])
) {
    $flashMessage = (string) (
        $_SESSION['event_flash']['message'] ??
        ''
    );

    $flashType = (string) (
        $_SESSION['event_flash']['type'] ??
        'success'
    );

    unset($_SESSION['event_flash']);
}

/*
|--------------------------------------------------------------------------
| Proses ikut event
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['join_event'])
) {
    $eventId = (int) (
        $_POST['event_id'] ??
        0
    );

    $postedCsrf = (string) (
        $_POST['csrf_token'] ??
        ''
    );

    if (
        $postedCsrf === '' ||
        !hash_equals($csrfToken, $postedCsrf)
    ) {
        $_SESSION['event_flash'] = [
            'type' => 'error',
            'message' =>
                'Sesi formulir berubah. Muat ulang halaman lalu coba lagi.',
        ];

        header('Location: event.php');
        exit;
    }

    if (!$isLoggedIn) {
        header(
            'Location: login.php?next=' .
            rawurlencode('event.php')
        );
        exit;
    }

    try {
        $pdo->beginTransaction();

        $eventStatement = $pdo->prepare(
            'SELECT
                id,
                title,
                slug,
                start_at,
                end_at,
                max_participants,
                is_active
             FROM events
             WHERE id = :id
             LIMIT 1
             FOR UPDATE'
        );

        $eventStatement->execute([
            ':id' => $eventId,
        ]);

        $eventRow = $eventStatement->fetch();

        if (!$eventRow || !(int) $eventRow['is_active']) {
            throw new RuntimeException(
                'Event tidak ditemukan atau tidak aktif.'
            );
        }

        $status = eventStatus(
            $eventRow['start_at'],
            $eventRow['end_at']
        );

        if ($status === 'ENDED') {
            throw new RuntimeException(
                'Event sudah berakhir.'
            );
        }

        $participantCountStatement =
            $pdo->prepare(
                'SELECT COUNT(*)
                 FROM event_participants
                 WHERE event_id = :event_id
                   AND status IN (
                        "JOINED",
                        "COMPLETED",
                        "WINNER"
                   )'
            );

        $participantCountStatement->execute([
            ':event_id' => $eventId,
        ]);

        $participantCount =
            (int) $participantCountStatement->fetchColumn();

        $maxParticipants =
            $eventRow['max_participants'] !== null
                ? (int) $eventRow['max_participants']
                : 0;

        if (
            $maxParticipants > 0 &&
            $participantCount >= $maxParticipants
        ) {
            throw new RuntimeException(
                'Kuota peserta event sudah penuh.'
            );
        }

        $joinStatement = $pdo->prepare(
            'INSERT INTO event_participants
            (
                event_id,
                user_id,
                progress_value,
                progress_target,
                status,
                joined_at,
                updated_at
            )
            VALUES
            (
                :event_id,
                :user_id,
                0,
                0,
                "JOINED",
                NOW(),
                NOW()
            )
            ON DUPLICATE KEY UPDATE
                status = CASE
                    WHEN status = "CANCELLED"
                    THEN "JOINED"
                    ELSE status
                END,
                updated_at = NOW()'
        );

        $joinStatement->execute([
            ':event_id' => $eventId,
            ':user_id' => $userId,
        ]);

        $pdo->commit();

        $_SESSION['event_flash'] = [
            'type' => 'success',
            'message' =>
                'Berhasil mengikuti event ' .
                (string) $eventRow['title'] .
                '.',
        ];

        $_SESSION['event_csrf'] =
            bin2hex(random_bytes(32));

        header(
            'Location: event.php?event=' .
            rawurlencode(
                (string) $eventRow['slug']
            )
        );
        exit;
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        error_log(
            'EVENT JOIN ERROR: ' .
            $exception->getMessage()
        );

        $_SESSION['event_flash'] = [
            'type' => 'error',
            'message' => $exception->getMessage(),
        ];

        header('Location: event.php');
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| Ambil data event
|--------------------------------------------------------------------------
*/

$eventRows = [];
$eventError = '';

try {
    $eventsStatement = $pdo->query(
        'SELECT
            e.id,
            e.title,
            e.slug,
            e.category,
            e.event_type,
            e.badge_text,
            e.short_description,
            e.description,
            e.rules_text,
            e.reward_summary,
            e.image_url,
            e.mobile_image_url,
            e.button_label,
            e.button_url,
            e.requires_login,
            e.is_featured,
            e.max_participants,
            e.start_at,
            e.end_at,
            e.sort_order,
            e.created_at,
            (
                SELECT COUNT(*)
                FROM event_participants ep_count
                WHERE ep_count.event_id = e.id
                  AND ep_count.status IN (
                    "JOINED",
                    "COMPLETED",
                    "WINNER"
                  )
            ) AS participant_count
         FROM events e
         WHERE e.is_active = 1
         ORDER BY
            e.is_featured DESC,
            e.sort_order ASC,
            e.start_at ASC,
            e.id DESC'
    );

    $eventRows = $eventsStatement->fetchAll();
} catch (Throwable $exception) {
    $eventRows = [];

    $eventError =
        'Data event belum dapat dimuat. Pastikan tabel event sudah dibuat.';

    error_log(
        'EVENT LIST ERROR: ' .
        $exception->getMessage()
    );
}

/*
|--------------------------------------------------------------------------
| Ambil status partisipasi pengguna
|--------------------------------------------------------------------------
*/

$userParticipation = [];

if (
    $isLoggedIn &&
    !empty($eventRows)
) {
    try {
        $participationStatement =
            $pdo->prepare(
                'SELECT
                    event_id,
                    progress_value,
                    progress_target,
                    status,
                    joined_at
                 FROM event_participants
                 WHERE user_id = :user_id'
            );

        $participationStatement->execute([
            ':user_id' => $userId,
        ]);

        foreach (
            $participationStatement->fetchAll()
            as $participationRow
        ) {
            $userParticipation[
                (int) $participationRow['event_id']
            ] = $participationRow;
        }
    } catch (Throwable $exception) {
        error_log(
            'EVENT PARTICIPATION ERROR: ' .
            $exception->getMessage()
        );
    }
}

/*
|--------------------------------------------------------------------------
| Ambil hadiah
|--------------------------------------------------------------------------
*/

$rewardMap = [];

if (!empty($eventRows)) {
    try {
        $eventIds = [];

        foreach ($eventRows as $eventRow) {
            $eventIds[] = (int) $eventRow['id'];
        }

        $placeholders = implode(
            ',',
            array_fill(
                0,
                count($eventIds),
                '?'
            )
        );

        $rewardStatement = $pdo->prepare(
            'SELECT
                id,
                event_id,
                reward_title,
                reward_description,
                reward_value,
                winner_rank,
                sort_order
             FROM event_rewards
             WHERE is_active = 1
               AND event_id IN (' .
                $placeholders .
             ')
             ORDER BY
                event_id ASC,
                sort_order ASC,
                id ASC'
        );

        $rewardStatement->execute(
            $eventIds
        );

        foreach (
            $rewardStatement->fetchAll()
            as $rewardRow
        ) {
            $rewardMap[
                (int) $rewardRow['event_id']
            ][] = $rewardRow;
        }
    } catch (Throwable $exception) {
        error_log(
            'EVENT REWARD ERROR: ' .
            $exception->getMessage()
        );
    }
}

/*
|--------------------------------------------------------------------------
| Normalisasi
|--------------------------------------------------------------------------
*/

$events = [];
$categories = [];

$liveCount = 0;
$upcomingCount = 0;
$endedCount = 0;

foreach ($eventRows as $eventRow) {
    $status = eventStatus(
        $eventRow['start_at'],
        $eventRow['end_at']
    );

    if ($status === 'LIVE') {
        $liveCount++;
    } elseif ($status === 'UPCOMING') {
        $upcomingCount++;
    } else {
        $endedCount++;
    }

    $category = strtoupper(
        trim(
            (string) (
                $eventRow['category'] ??
                'LAINNYA'
            )
        )
    );

    if ($category === '') {
        $category = 'LAINNYA';
    }

    $participantCount = (int) (
        $eventRow['participant_count'] ??
        0
    );

    $maxParticipants =
        $eventRow['max_participants'] !== null
            ? (int) $eventRow['max_participants']
            : 0;

    $capacityPercent = 0;

    if ($maxParticipants > 0) {
        $capacityPercent = (int) min(
            100,
            round(
                ($participantCount / $maxParticipants) *
                100
            )
        );
    }

    $eventId = (int) $eventRow['id'];

    $participation = isset(
        $userParticipation[$eventId]
    )
        ? $userParticipation[$eventId]
        : null;

    $buttonUrl = eventSafeUrl(
        $eventRow['button_url'] ??
        ''
    );

    if ($buttonUrl === '#') {
        $buttonUrl =
            'event.php?event=' .
            rawurlencode(
                (string) $eventRow['slug']
            );
    }

    $events[] = [
        'id' => $eventId,
        'title' => (string) $eventRow['title'],
        'slug' => (string) $eventRow['slug'],
        'category' => $category,
        'event_type' => (string) (
            $eventRow['event_type'] ??
            'OTHER'
        ),
        'badge_text' => (string) (
            $eventRow['badge_text'] ??
            'EVENT'
        ),
        'short_description' => (string) (
            $eventRow['short_description'] ??
            ''
        ),
        'description' => (string) (
            $eventRow['description'] ??
            ''
        ),
        'rules_text' => (string) (
            $eventRow['rules_text'] ??
            ''
        ),
        'reward_summary' => (string) (
            $eventRow['reward_summary'] ??
            ''
        ),
        'image_url' => (string) (
            $eventRow['image_url'] ??
            'assets/images/event/event-default.svg'
        ),
        'mobile_image_url' => (string) (
            $eventRow['mobile_image_url'] ??
            ''
        ),
        'button_label' => (string) (
            $eventRow['button_label'] ??
            'IKUT EVENT'
        ),
        'button_url' => $buttonUrl,
        'requires_login' => !empty(
            $eventRow['requires_login']
        ),
        'is_featured' => !empty(
            $eventRow['is_featured']
        ),
        'max_participants' => $maxParticipants,
        'participant_count' => $participantCount,
        'capacity_percent' => $capacityPercent,
        'start_at' => $eventRow['start_at'],
        'end_at' => $eventRow['end_at'],
        'start_label' => eventDateLabel(
            $eventRow['start_at']
        ),
        'end_label' => eventDateLabel(
            $eventRow['end_at']
        ),
        'status' => $status,
        'status_label' => eventStatusLabel(
            $status
        ),
        'rewards' => isset($rewardMap[$eventId])
            ? $rewardMap[$eventId]
            : [],
        'joined' => $participation !== null,
        'participation' => $participation,
    ];

    $categories[$category] = true;
}

$categories = array_keys(
    $categories
);

sort($categories);

$featuredEvent = null;

foreach ($events as $event) {
    if (
        $event['is_featured'] &&
        $event['status'] !== 'ENDED'
    ) {
        $featuredEvent = $event;
        break;
    }
}

if (
    $featuredEvent === null &&
    !empty($events)
) {
    foreach ($events as $event) {
        if ($event['status'] !== 'ENDED') {
            $featuredEvent = $event;
            break;
        }
    }
}

if (
    $featuredEvent === null &&
    !empty($events)
) {
    $featuredEvent = $events[0];
}

/*
|--------------------------------------------------------------------------
| Event terpilih dari URL
|--------------------------------------------------------------------------
*/

$selectedSlug = eventSafeSlug(
    $_GET['event'] ?? ''
);

$selectedEventId = 0;

if ($selectedSlug !== '') {
    foreach ($events as $event) {
        if ($event['slug'] === $selectedSlug) {
            $selectedEventId =
                (int) $event['id'];

            break;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Header
|--------------------------------------------------------------------------
*/

require __DIR__ . '/includes/header.php';

?>

<style>
/*
|--------------------------------------------------------------------------
| Halaman event
|--------------------------------------------------------------------------
*/

.event-page {
    position: relative;

    width: 100%;
    min-height: calc(100vh - 70px);

    padding: 12px 8px 28px;

    overflow: hidden;

    background:
        radial-gradient(
            circle at 50% -6%,
            rgba(0, 139, 255, 0.28),
            transparent 285px
        ),
        radial-gradient(
            circle at 108% 42%,
            rgba(255, 179, 0, 0.11),
            transparent 190px
        ),
        linear-gradient(
            180deg,
            #031431 0%,
            #020a1c 55%,
            #010610 100%
        );
}

.event-page::before,
.event-page::after {
    position: absolute;

    width: 190px;
    height: 190px;

    content: "";

    border-radius: 50%;

    filter: blur(38px);

    pointer-events: none;
}

.event-page::before {
    top: 145px;
    left: -160px;

    background:
        rgba(0, 126, 255, 0.20);
}

.event-page::after {
    right: -165px;
    bottom: 170px;

    background:
        rgba(255, 178, 0, 0.12);
}

.event-shell {
    position: relative;
    z-index: 2;

    width: 100%;
    max-width: 540px;

    margin: 0 auto;
}

/*
|--------------------------------------------------------------------------
| Heading
|--------------------------------------------------------------------------
*/

.event-heading {
    display: grid;

    justify-items: center;

    margin-bottom: 11px;

    text-align: center;
}

.event-heading-crown {
    margin-bottom: -4px;

    color: #ffd451;

    font-size: 29px;
    line-height: 1;

    text-shadow:
        0 1px 0 #fff5ac,
        0 3px 0 #713600,
        0 0 10px rgba(255, 194, 39, 0.65);
}

.event-heading h1 {
    margin: 0;

    color: #ffd450;

    background:
        linear-gradient(
            180deg,
            #fff9ba 0%,
            #ffd451 36%,
            #e58b00 72%,
            #fff09a 100%
        );

    background-clip: text;
    -webkit-background-clip: text;

    font-size: clamp(24px, 7vw, 34px);
    font-weight: 1000;

    letter-spacing: -0.035em;

    -webkit-text-fill-color: transparent;

    filter:
        drop-shadow(0 2px 0 #713600)
        drop-shadow(0 5px 6px rgba(0, 0, 0, 0.72));
}

.event-heading p {
    max-width: 430px;

    margin: 6px 0 0;

    color: #96aac5;

    font-size: 9px;
    line-height: 1.5;
}

.event-account-state {
    display: inline-flex;

    min-height: 24px;

    align-items: center;

    margin-top: 8px;
    padding: 0 9px;

    gap: 5px;

    border:
        1px solid rgba(70, 222, 150, 0.25);

    border-radius: 999px;

    color: #a9dec4;

    background:
        rgba(4, 48, 32, 0.56);

    font-size: 7px;
    font-weight: 850;
}

.event-account-state i {
    width: 5px;
    height: 5px;

    border-radius: 50%;

    background: #50e39a;

    box-shadow:
        0 0 6px rgba(80, 227, 154, 0.70);
}

/*
|--------------------------------------------------------------------------
| Flash
|--------------------------------------------------------------------------
*/

.event-alert {
    margin-bottom: 10px;
    padding: 9px 10px;

    border-radius: 10px;

    font-size: 8px;
    line-height: 1.5;
}

.event-alert--success {
    border:
        1px solid rgba(73, 232, 152, 0.36);

    color: #c9ffe0;

    background:
        rgba(5, 75, 45, 0.45);
}

.event-alert--error {
    border:
        1px solid rgba(255, 77, 77, 0.40);

    color: #ffd6d6;

    background:
        rgba(102, 12, 17, 0.48);
}

/*
|--------------------------------------------------------------------------
| Statistik
|--------------------------------------------------------------------------
*/

.event-stats {
    display: grid;

    margin-bottom: 10px;
    padding: 7px;

    grid-template-columns:
        repeat(3, minmax(0, 1fr));

    gap: 5px;

    border:
        1px solid rgba(0, 159, 255, 0.25);

    border-radius: 12px;

    background:
        linear-gradient(
            180deg,
            rgba(8, 37, 78, 0.95),
            rgba(2, 16, 38, 0.98)
        );
}

.event-stat {
    display: grid;

    min-height: 45px;

    align-content: center;
    justify-items: center;

    border:
        1px solid rgba(255, 255, 255, 0.06);

    border-radius: 9px;

    background:
        rgba(0, 0, 0, 0.14);
}

.event-stat strong {
    color: #ffffff;

    font-size: 15px;
    font-weight: 1000;
}

.event-stat small {
    margin-top: 1px;

    color: #7e94b0;

    font-size: 6px;
    font-weight: 800;
}

.event-stat.is-live strong {
    color: #55eaa0;
}

.event-stat.is-upcoming strong {
    color: #ffd34e;
}

/*
|--------------------------------------------------------------------------
| Featured
|--------------------------------------------------------------------------
*/

.event-featured {
    position: relative;

    margin-bottom: 11px;

    overflow: hidden;

    border:
        1px solid rgba(255, 198, 48, 0.44);

    border-radius: 15px;

    background: #06142c;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.09),
        0 0 10px rgba(255, 182, 20, 0.15),
        0 8px 22px rgba(0, 0, 0, 0.34);
}

.event-featured-picture {
    display: block;

    width: 100%;
    aspect-ratio: 16 / 8.7;

    overflow: hidden;

    background:
        linear-gradient(
            145deg,
            #082a5a,
            #04132d
        );
}

.event-featured-picture img {
    display: block;

    width: 100%;
    height: 100%;

    object-fit: cover;
}

.event-featured-overlay {
    position: absolute;

    inset: 0;

    display: flex;

    align-items: flex-end;

    padding: 13px;

    background:
        linear-gradient(
            180deg,
            transparent 25%,
            rgba(1, 7, 18, 0.35) 50%,
            rgba(1, 7, 18, 0.97) 100%
        );
}

.event-featured-copy {
    width: 100%;
}

.event-topline {
    display: flex;

    align-items: center;

    gap: 5px;
}

.event-status-badge,
.event-main-badge {
    display: inline-flex;

    min-height: 21px;

    align-items: center;

    padding: 0 8px;

    border-radius: 999px;

    font-size: 6px;
    font-weight: 1000;
}

.event-main-badge {
    border:
        1px solid rgba(255, 236, 157, 0.72);

    color: #341c00;

    background:
        linear-gradient(
            180deg,
            #fff29b,
            #ffc62e
        );
}

.event-status-badge {
    border:
        1px solid rgba(83, 232, 159, 0.55);

    color: #c9ffe1;

    background:
        rgba(5, 80, 48, 0.72);
}

.event-status-badge.is-upcoming {
    border-color:
        rgba(255, 204, 65, 0.55);

    color: #ffe69a;

    background:
        rgba(89, 52, 4, 0.75);
}

.event-status-badge.is-ended {
    border-color:
        rgba(156, 169, 188, 0.40);

    color: #c1cad7;

    background:
        rgba(44, 52, 65, 0.78);
}

.event-featured-copy h2 {
    margin: 7px 0 0;

    color: #ffffff;

    font-size: clamp(18px, 5.5vw, 27px);
    font-weight: 1000;

    line-height: 1.05;

    text-shadow:
        0 2px 2px rgba(0, 0, 0, 0.90);
}

.event-featured-copy p {
    max-width: 450px;

    margin: 6px 0 0;

    color: #d4deea;

    font-size: 8px;
    line-height: 1.45;
}

.event-featured-info {
    display: flex;

    flex-wrap: wrap;

    margin-top: 7px;

    gap: 5px;
}

.event-info-chip {
    display: inline-flex;

    min-height: 23px;

    align-items: center;

    padding: 0 7px;

    border:
        1px solid rgba(0, 166, 255, 0.28);

    border-radius: 7px;

    color: #a9dfff;

    background:
        rgba(3, 32, 69, 0.76);

    font-size: 6px;
    font-weight: 800;
}

.event-featured-actions {
    display: flex;

    margin-top: 8px;

    gap: 6px;
}

.event-button {
    display: inline-flex;

    min-height: 34px;

    align-items: center;
    justify-content: center;

    padding: 0 12px;

    border:
        1px solid #ffe17f;

    border-radius: 8px;

    color: #301700;

    background:
        linear-gradient(
            180deg,
            #fff08c,
            #ffc32d 50%,
            #d87700
        );

    font-size: 8px;
    font-weight: 1000;

    text-decoration: none;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.62),
        0 3px 0 #572900,
        0 0 8px rgba(255, 183, 20, 0.28);

    cursor: pointer;
}

.event-button--ghost {
    border-color:
        rgba(0, 172, 255, 0.45);

    color: #ffffff;

    background:
        linear-gradient(
            180deg,
            rgba(11, 63, 117, 0.92),
            rgba(3, 26, 59, 0.98)
        );

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.09),
        0 3px 0 rgba(0, 0, 0, 0.55);
}

/*
|--------------------------------------------------------------------------
| Filter
|--------------------------------------------------------------------------
*/

.event-filter-wrap {
    margin-bottom: 10px;
}

.event-filter-head {
    display: flex;

    align-items: center;
    justify-content: space-between;

    margin-bottom: 7px;
}

.event-filter-head strong {
    color: #ffffff;

    font-size: 11px;
}

.event-filter-head small {
    color: #758ba7;

    font-size: 7px;
}

.event-filter-scroll {
    display: flex;

    overflow-x: auto;

    padding-bottom: 3px;

    gap: 6px;

    scrollbar-width: none;
}

.event-filter-scroll::-webkit-scrollbar {
    display: none;
}

.event-filter-button {
    flex: 0 0 auto;

    min-height: 29px;

    padding: 0 11px;

    border:
        1px solid rgba(0, 157, 255, 0.28);

    border-radius: 999px;

    color: #8fa7c3;

    background:
        linear-gradient(
            180deg,
            #08284f,
            #03142d
        );

    font-size: 7px;
    font-weight: 900;

    cursor: pointer;
}

.event-filter-button.is-active {
    border-color:
        rgba(255, 211, 78, 0.72);

    color: #271400;

    background:
        linear-gradient(
            180deg,
            #ffe687,
            #ffb719
        );

    box-shadow:
        0 0 8px rgba(255, 183, 23, 0.28);
}

/*
|--------------------------------------------------------------------------
| Grid event
|--------------------------------------------------------------------------
*/

.event-grid {
    display: grid;

    grid-template-columns:
        repeat(2, minmax(0, 1fr));

    gap: 8px;
}

.event-card {
    position: relative;

    display: grid;

    min-width: 0;

    overflow: hidden;

    border:
        1px solid rgba(0, 157, 255, 0.27);

    border-radius: 12px;

    background:
        linear-gradient(
            180deg,
            rgba(7, 30, 65, 0.98),
            rgba(2, 12, 29, 0.99)
        );

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.07),
        0 4px 12px rgba(0, 0, 0, 0.25);

    transition:
        transform 160ms ease,
        border-color 160ms ease,
        box-shadow 160ms ease;
}

.event-card:hover {
    transform: translateY(-2px);

    border-color:
        rgba(255, 194, 37, 0.55);

    box-shadow:
        0 7px 15px rgba(0, 0, 0, 0.34),
        0 0 9px rgba(255, 185, 23, 0.14);
}

.event-card-picture {
    position: relative;

    display: block;

    width: 100%;
    aspect-ratio: 16 / 9;

    overflow: hidden;

    background:
        linear-gradient(
            145deg,
            #082a5a,
            #04132d
        );
}

.event-card-picture img {
    display: block;

    width: 100%;
    height: 100%;

    object-fit: cover;

    transition:
        transform 220ms ease;
}

.event-card:hover
.event-card-picture img {
    transform: scale(1.04);
}

.event-card-status {
    position: absolute;

    top: 6px;
    left: 6px;

    min-height: 20px;

    padding: 0 7px;

    border:
        1px solid rgba(83, 232, 159, 0.55);

    border-radius: 999px;

    color: #c9ffe1;
    background:
        rgba(5, 80, 48, 0.82);

    font-size: 5px;
    font-weight: 1000;

    line-height: 18px;
}

.event-card-status.is-upcoming {
    border-color:
        rgba(255, 204, 65, 0.55);

    color: #ffe69a;

    background:
        rgba(89, 52, 4, 0.85);
}

.event-card-status.is-ended {
    border-color:
        rgba(156, 169, 188, 0.40);

    color: #c1cad7;

    background:
        rgba(44, 52, 65, 0.86);
}

.event-card-body {
    display: grid;

    min-width: 0;

    padding: 8px;

    gap: 5px;
}

.event-card-meta {
    display: flex;

    align-items: center;
    justify-content: space-between;

    gap: 5px;
}

.event-card-category {
    overflow: hidden;

    color: #61cbff;

    font-size: 6px;
    font-weight: 1000;

    letter-spacing: 0.06em;

    text-overflow: ellipsis;
    white-space: nowrap;
}

.event-card-badge {
    flex: 0 0 auto;

    padding: 2px 5px;

    border-radius: 999px;

    color: #3a2100;
    background: #ffd34e;

    font-size: 5px;
    font-weight: 1000;
}

.event-card h3 {
    display: -webkit-box;

    min-height: 26px;

    margin: 0;

    overflow: hidden;

    color: #ffffff;

    font-size: 11px;
    font-weight: 1000;

    line-height: 1.15;

    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}

.event-card p {
    display: -webkit-box;

    min-height: 20px;

    margin: 0;

    overflow: hidden;

    color: #91a5bf;

    font-size: 7px;
    line-height: 1.45;

    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}

.event-countdown {
    min-height: 24px;

    padding: 5px 6px;

    border:
        1px solid rgba(255, 204, 66, 0.18);

    border-radius: 7px;

    color: #ffd85f;
    background:
        rgba(69, 42, 4, 0.24);

    font-size: 6px;
    font-weight: 900;

    text-align: center;
}

.event-reward {
    color: #72e7ac;

    font-size: 7px;
    font-weight: 850;
}

.event-capacity {
    display: grid;

    gap: 3px;
}

.event-capacity-head {
    display: flex;

    justify-content: space-between;

    color: #748ca9;

    font-size: 6px;
}

.event-capacity-track {
    height: 5px;

    overflow: hidden;

    border-radius: 999px;

    background:
        rgba(255, 255, 255, 0.07);
}

.event-capacity-fill {
    height: 100%;

    border-radius: 999px;

    background:
        linear-gradient(
            90deg,
            #009fff,
            #5fdcff
        );

    box-shadow:
        0 0 6px rgba(0, 167, 255, 0.45);
}

.event-joined {
    display: flex;

    min-height: 25px;

    align-items: center;
    justify-content: center;

    border:
        1px solid rgba(78, 231, 151, 0.30);

    border-radius: 7px;

    color: #baffd7;
    background:
        rgba(6, 67, 42, 0.45);

    font-size: 6px;
    font-weight: 1000;
}

.event-card-actions {
    display: grid;

    margin-top: 1px;

    grid-template-columns:
        minmax(0, 1fr)
        auto;

    gap: 5px;
}

.event-card-button {
    display: flex;

    min-height: 29px;

    align-items: center;
    justify-content: center;

    padding: 0 7px;

    border:
        1px solid rgba(255, 205, 70, 0.48);

    border-radius: 7px;

    color: #271400;

    background:
        linear-gradient(
            180deg,
            #ffe37e,
            #f3aa14
        );

    font-family: inherit;
    font-size: 6px;
    font-weight: 1000;

    text-decoration: none;

    cursor: pointer;
}

.event-card-button:disabled {
    border-color:
        rgba(143, 155, 173, 0.25);

    color: #7e8999;
    background:
        rgba(47, 56, 69, 0.75);

    cursor: not-allowed;
}

.event-detail-button {
    min-width: 31px;
    min-height: 29px;

    padding: 0;

    border:
        1px solid rgba(0, 170, 255, 0.40);

    border-radius: 7px;

    color: #7ed7ff;
    background: #042144;

    font-size: 13px;

    cursor: pointer;
}

/*
|--------------------------------------------------------------------------
| Empty
|--------------------------------------------------------------------------
*/

.event-empty {
    grid-column: 1 / -1;

    padding: 22px 12px;

    border:
        1px dashed rgba(255, 194, 39, 0.30);

    border-radius: 12px;

    color: #91a5bf;
    background:
        rgba(4, 18, 42, 0.74);

    font-size: 9px;
    line-height: 1.5;

    text-align: center;
}

/*
|--------------------------------------------------------------------------
| Modal
|--------------------------------------------------------------------------
*/

.event-modal {
    position: fixed;
    z-index: 2200;

    inset: 0;

    display: none;

    align-items: flex-end;
    justify-content: center;

    padding: 12px;

    background:
        rgba(0, 4, 13, 0.82);

    backdrop-filter:
        blur(8px);
}

.event-modal.is-open {
    display: flex;
}

.event-modal-dialog {
    position: relative;

    width: 100%;
    max-width: 540px;
    max-height: 90vh;

    overflow-y: auto;

    border:
        1px solid rgba(255, 197, 43, 0.42);

    border-radius: 16px;

    background:
        radial-gradient(
            circle at 50% 0,
            rgba(255, 178, 0, 0.11),
            transparent 170px
        ),
        linear-gradient(
            180deg,
            #08234b,
            #020b1d
        );

    box-shadow:
        0 0 18px rgba(0, 129, 255, 0.24),
        0 18px 36px rgba(0, 0, 0, 0.55);
}

.event-modal-close {
    position: absolute;
    z-index: 3;

    top: 8px;
    right: 8px;

    display: grid;

    width: 31px;
    height: 31px;

    place-items: center;

    border:
        1px solid rgba(255, 255, 255, 0.22);

    border-radius: 50%;

    color: #ffffff;
    background:
        rgba(0, 0, 0, 0.70);

    font-size: 16px;

    cursor: pointer;
}

.event-modal-image {
    display: block;

    width: 100%;
    aspect-ratio: 16 / 8.5;

    object-fit: cover;

    border-radius:
        15px
        15px
        0
        0;
}

.event-modal-content {
    padding: 13px;
}

.event-modal-content h2 {
    margin: 7px 0 0;

    color: #ffffff;

    font-size: 18px;
}

.event-modal-description,
.event-modal-rules {
    margin-top: 8px;

    color: #adbed1;

    font-size: 9px;
    line-height: 1.65;

    white-space: pre-line;
}

.event-modal-section-title {
    margin-top: 12px;

    color: #ffd34e;

    font-size: 9px;
    font-weight: 1000;
}

.event-reward-list {
    display: grid;

    margin-top: 7px;

    gap: 6px;
}

.event-reward-item {
    display: grid;

    padding: 8px;

    grid-template-columns:
        38px
        minmax(0, 1fr);

    align-items: center;

    gap: 8px;

    border:
        1px solid rgba(255, 203, 64, 0.18);

    border-radius: 9px;

    background:
        rgba(69, 42, 4, 0.22);
}

.event-reward-rank {
    display: grid;

    width: 38px;
    height: 38px;

    place-items: center;

    border:
        1px solid #ffd24d;

    border-radius: 50%;

    color: #ffd24d;

    font-size: 10px;
    font-weight: 1000;
}

.event-reward-item strong {
    display: block;

    color: #ffffff;

    font-size: 9px;
}

.event-reward-item small {
    display: block;

    margin-top: 2px;

    color: #93a8c1;

    font-size: 7px;
    line-height: 1.4;
}

.event-modal-actions {
    display: flex;

    margin-top: 12px;

    gap: 7px;
}

.event-modal-actions .event-button {
    flex: 1;
}

body.event-modal-open {
    overflow: hidden;
}

/*
|--------------------------------------------------------------------------
| Responsive
|--------------------------------------------------------------------------
*/

@media (max-width: 390px) {
    .event-featured-overlay {
        padding: 11px;
    }

    .event-card-body {
        padding: 7px;
    }
}

@media (max-width: 340px) {
    .event-grid {
        grid-template-columns: 1fr;
    }

    .event-card h3,
    .event-card p {
        min-height: 0;
    }
}
</style>

<section class="event-page">
    <div class="event-shell">

        <header class="event-heading">
            <span
                class="event-heading-crown"
                aria-hidden="true"
            >
                ♛
            </span>

            <h1>
                EVENT & TURNAMEN
            </h1>

            <p>
                Ikuti misi, turnamen, tantangan, dan event
                eksklusif untuk mendapatkan hadiah.
            </p>

            <span class="event-account-state">
                <i></i>

                <?php if ($isLoggedIn): ?>
                    Halo <?= e($username); ?>, akun siap mengikuti event
                <?php else: ?>
                    Event dapat dilihat tanpa login
                <?php endif; ?>
            </span>
        </header>

        <?php if ($flashMessage !== ''): ?>

            <div
                class="event-alert <?= $flashType === 'error'
                    ? 'event-alert--error'
                    : 'event-alert--success'; ?>"
            >
                <?= e($flashMessage); ?>
            </div>

        <?php endif; ?>

        <?php if ($eventError !== ''): ?>

            <div class="event-alert event-alert--error">
                <?= e($eventError); ?>
            </div>

        <?php endif; ?>

        <section class="event-stats">

            <div class="event-stat is-live">
                <strong><?= $liveCount; ?></strong>
                <small>SEDANG LIVE</small>
            </div>

            <div class="event-stat is-upcoming">
                <strong><?= $upcomingCount; ?></strong>
                <small>SEGERA DIMULAI</small>
            </div>

            <div class="event-stat">
                <strong><?= count($events); ?></strong>
                <small>TOTAL EVENT</small>
            </div>

        </section>

        <?php if ($featuredEvent): ?>

            <article class="event-featured">

                <picture class="event-featured-picture">

                    <?php if (
                        $featuredEvent['mobile_image_url'] !== ''
                    ): ?>
                        <source
                            media="(max-width: 480px)"
                            srcset="<?= e($featuredEvent['mobile_image_url']); ?>"
                        >
                    <?php endif; ?>

                    <img
                        src="<?= e($featuredEvent['image_url']); ?>"
                        alt="<?= e($featuredEvent['title']); ?>"
                        loading="eager"
                        onerror="
                            this.onerror = null;
                            this.src =
                                'assets/images/event/event-default.svg';
                        "
                    >
                </picture>

                <div class="event-featured-overlay">
                    <div class="event-featured-copy">

                        <div class="event-topline">

                            <span class="event-main-badge">
                                <?= e($featuredEvent['badge_text']); ?>
                            </span>

                            <span
                                class="event-status-badge <?= $featuredEvent['status'] === 'UPCOMING'
                                    ? 'is-upcoming'
                                    : (
                                        $featuredEvent['status'] === 'ENDED'
                                            ? 'is-ended'
                                            : ''
                                    ); ?>"
                            >
                                <?= e($featuredEvent['status_label']); ?>
                            </span>

                        </div>

                        <h2>
                            <?= e($featuredEvent['title']); ?>
                        </h2>

                        <p>
                            <?= e($featuredEvent['short_description']); ?>
                        </p>

                        <div class="event-featured-info">

                            <span class="event-info-chip">
                                Hadiah:
                                <?= e($featuredEvent['reward_summary']); ?>
                            </span>

                            <span class="event-info-chip">
                                Peserta:
                                <?= (int) $featuredEvent['participant_count']; ?>
                                <?php if (
                                    $featuredEvent['max_participants'] > 0
                                ): ?>
                                    /
                                    <?= (int) $featuredEvent['max_participants']; ?>
                                <?php endif; ?>
                            </span>

                            <span
                                class="event-info-chip"
                                data-event-countdown
                                data-status="<?= e($featuredEvent['status']); ?>"
                                data-start="<?= e((string) $featuredEvent['start_at']); ?>"
                                data-end="<?= e((string) $featuredEvent['end_at']); ?>"
                            >
                                Memuat waktu...
                            </span>

                        </div>

                        <div class="event-featured-actions">

                            <button
                                class="event-button"
                                type="button"
                                data-event-open="<?= (int) $featuredEvent['id']; ?>"
                            >
                                LIHAT DETAIL
                            </button>

                            <a
                                class="event-button event-button--ghost"
                                href="#eventList"
                            >
                                SEMUA EVENT
                            </a>

                        </div>

                    </div>
                </div>

            </article>

        <?php endif; ?>

        <section
            class="event-filter-wrap"
            id="eventList"
        >

            <div class="event-filter-head">
                <strong>
                    Daftar Event
                </strong>

                <small>
                    Pilih kategori atau status
                </small>
            </div>

            <div class="event-filter-scroll">

                <button
                    class="event-filter-button is-active"
                    type="button"
                    data-event-filter="ALL"
                >
                    SEMUA
                </button>

                <button
                    class="event-filter-button"
                    type="button"
                    data-event-filter="LIVE"
                >
                    LIVE
                </button>

                <button
                    class="event-filter-button"
                    type="button"
                    data-event-filter="UPCOMING"
                >
                    SEGERA
                </button>

                <?php foreach ($categories as $category): ?>

                    <button
                        class="event-filter-button"
                        type="button"
                        data-event-filter="<?= e($category); ?>"
                    >
                        <?= e($category); ?>
                    </button>

                <?php endforeach; ?>

            </div>

        </section>

        <section class="event-grid">

            <?php if (empty($events)): ?>

                <div class="event-empty">
                    Belum ada event aktif.
                    Tambahkan data melalui tabel
                    <strong>events</strong>.
                </div>

            <?php else: ?>

                <?php foreach ($events as $event): ?>

                    <article
                        class="event-card"
                        data-event-category="<?= e($event['category']); ?>"
                        data-event-status="<?= e($event['status']); ?>"
                    >

                        <picture class="event-card-picture">

                            <?php if (
                                $event['mobile_image_url'] !== ''
                            ): ?>
                                <source
                                    media="(max-width: 480px)"
                                    srcset="<?= e($event['mobile_image_url']); ?>"
                                >
                            <?php endif; ?>

                            <img
                                src="<?= e($event['image_url']); ?>"
                                alt="<?= e($event['title']); ?>"
                                loading="lazy"
                                onerror="
                                    this.onerror = null;
                                    this.src =
                                        'assets/images/event/event-default.svg';
                                "
                            >

                            <span
                                class="event-card-status <?= $event['status'] === 'UPCOMING'
                                    ? 'is-upcoming'
                                    : (
                                        $event['status'] === 'ENDED'
                                            ? 'is-ended'
                                            : ''
                                    ); ?>"
                            >
                                <?= e($event['status_label']); ?>
                            </span>

                        </picture>

                        <div class="event-card-body">

                            <div class="event-card-meta">
                                <span class="event-card-category">
                                    <?= e($event['category']); ?>
                                </span>

                                <span class="event-card-badge">
                                    <?= e($event['badge_text']); ?>
                                </span>
                            </div>

                            <h3>
                                <?= e($event['title']); ?>
                            </h3>

                            <p>
                                <?= e($event['short_description']); ?>
                            </p>

                            <div
                                class="event-countdown"
                                data-event-countdown
                                data-status="<?= e($event['status']); ?>"
                                data-start="<?= e((string) $event['start_at']); ?>"
                                data-end="<?= e((string) $event['end_at']); ?>"
                            >
                                Memuat waktu...
                            </div>

                            <div class="event-reward">
                                Hadiah:
                                <?= e($event['reward_summary']); ?>
                            </div>

                            <?php if (
                                $event['max_participants'] > 0
                            ): ?>

                                <div class="event-capacity">

                                    <div class="event-capacity-head">
                                        <span>
                                            Peserta
                                        </span>

                                        <span>
                                            <?= (int) $event['participant_count']; ?>
                                            /
                                            <?= (int) $event['max_participants']; ?>
                                        </span>
                                    </div>

                                    <div class="event-capacity-track">
                                        <div
                                            class="event-capacity-fill"
                                            style="width: <?= (int) $event['capacity_percent']; ?>%;"
                                        ></div>
                                    </div>

                                </div>

                            <?php endif; ?>

                            <?php if ($event['joined']): ?>

                                <div class="event-joined">
                                    ✓ SUDAH BERGABUNG
                                </div>

                            <?php endif; ?>

                            <div class="event-card-actions">

                                <?php if ($event['status'] === 'ENDED'): ?>

                                    <button
                                        class="event-card-button"
                                        type="button"
                                        disabled
                                    >
                                        EVENT SELESAI
                                    </button>

                                <?php elseif ($event['joined']): ?>

                                    <button
                                        class="event-card-button"
                                        type="button"
                                        data-event-open="<?= (int) $event['id']; ?>"
                                    >
                                        LIHAT PROGRES
                                    </button>

                                <?php elseif ($isLoggedIn): ?>

                                    <form
                                        method="post"
                                        action="event.php"
                                    >
                                        <input
                                            type="hidden"
                                            name="csrf_token"
                                            value="<?= e($csrfToken); ?>"
                                        >

                                        <input
                                            type="hidden"
                                            name="event_id"
                                            value="<?= (int) $event['id']; ?>"
                                        >

                                        <button
                                            class="event-card-button"
                                            type="submit"
                                            name="join_event"
                                            value="1"
                                        >
                                            <?= e($event['button_label']); ?>
                                        </button>
                                    </form>

                                <?php else: ?>

                                    <a
                                        class="event-card-button"
                                        href="login.php?next=<?= rawurlencode(
                                            'event.php?event=' .
                                            $event['slug']
                                        ); ?>"
                                    >
                                        LOGIN UNTUK IKUT
                                    </a>

                                <?php endif; ?>

                                <button
                                    class="event-detail-button"
                                    type="button"
                                    data-event-open="<?= (int) $event['id']; ?>"
                                    aria-label="Lihat detail <?= e($event['title']); ?>"
                                >
                                    ›
                                </button>

                            </div>

                        </div>

                    </article>

                <?php endforeach; ?>

            <?php endif; ?>

        </section>

    </div>
</section>

<!-- MODAL DETAIL EVENT -->
<div
    class="event-modal"
    id="eventModal"
    aria-hidden="true"
>
    <article
        class="event-modal-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="eventModalTitle"
    >
        <button
            class="event-modal-close"
            id="eventModalClose"
            type="button"
            aria-label="Tutup detail event"
        >
            ×
        </button>

        <img
            class="event-modal-image"
            id="eventModalImage"
            src="assets/images/event/event-default.svg"
            alt=""
        >

        <div class="event-modal-content">

            <div class="event-topline">
                <span
                    class="event-main-badge"
                    id="eventModalBadge"
                >
                    EVENT
                </span>

                <span
                    class="event-status-badge"
                    id="eventModalStatus"
                >
                    LIVE
                </span>
            </div>

            <h2 id="eventModalTitle">
                Detail Event
            </h2>

            <div
                class="event-modal-description"
                id="eventModalDescription"
            ></div>

            <div class="event-modal-section-title">
                SYARAT DAN CARA BERPARTISIPASI
            </div>

            <div
                class="event-modal-rules"
                id="eventModalRules"
            ></div>

            <div class="event-modal-section-title">
                HADIAH EVENT
            </div>

            <div
                class="event-reward-list"
                id="eventModalRewards"
            ></div>

            <div class="event-modal-actions">

                <a
                    class="event-button event-button--ghost"
                    href="terms.php"
                >
                    KETENTUAN UMUM
                </a>

                <button
                    class="event-button"
                    id="eventModalJoin"
                    type="button"
                >
                    TUTUP
                </button>

            </div>

        </div>
    </article>
</div>

<script>
(function () {
    'use strict';

    var eventData = <?= json_encode(
        $events,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_AMP |
        JSON_HEX_APOS |
        JSON_HEX_QUOT
    ); ?>;

    var selectedEventId =
        <?= (int) $selectedEventId; ?>;

    var eventMap = {};

    eventData.forEach(function (eventItem) {
        eventMap[String(eventItem.id)] =
            eventItem;
    });

    /*
    |--------------------------------------------------------------------------
    | Countdown
    |--------------------------------------------------------------------------
    */

    function parseDate(value) {
        if (!value) {
            return null;
        }

        return new Date(
            String(value).replace(' ', 'T')
        );
    }

    function formatRemaining(milliseconds) {
        if (milliseconds <= 0) {
            return '00h 00m 00s';
        }

        var totalSeconds = Math.floor(
            milliseconds / 1000
        );

        var days = Math.floor(
            totalSeconds / 86400
        );

        var hours = Math.floor(
            (totalSeconds % 86400) / 3600
        );

        var minutes = Math.floor(
            (totalSeconds % 3600) / 60
        );

        var seconds =
            totalSeconds % 60;

        var result = '';

        if (days > 0) {
            result += days + 'h ';
        }

        result +=
            String(hours).padStart(2, '0') +
            'j ' +
            String(minutes).padStart(2, '0') +
            'm ' +
            String(seconds).padStart(2, '0') +
            'd';

        return result;
    }

    function updateCountdowns() {
        var countdowns =
            document.querySelectorAll(
                '[data-event-countdown]'
            );

        var now = new Date();

        Array.prototype.forEach.call(
            countdowns,
            function (element) {
                var status =
                    element.getAttribute(
                        'data-status'
                    );

                var startDate = parseDate(
                    element.getAttribute(
                        'data-start'
                    )
                );

                var endDate = parseDate(
                    element.getAttribute(
                        'data-end'
                    )
                );

                if (status === 'ENDED') {
                    element.textContent =
                        'Event telah selesai';

                    return;
                }

                if (
                    status === 'UPCOMING' &&
                    startDate
                ) {
                    element.textContent =
                        'Mulai dalam ' +
                        formatRemaining(
                            startDate - now
                        );

                    return;
                }

                if (endDate) {
                    element.textContent =
                        'Berakhir dalam ' +
                        formatRemaining(
                            endDate - now
                        );

                    return;
                }

                element.textContent =
                    'Event sedang berlangsung';
            }
        );
    }

    updateCountdowns();

    window.setInterval(
        updateCountdowns,
        1000
    );

    /*
    |--------------------------------------------------------------------------
    | Filter
    |--------------------------------------------------------------------------
    */

    var filterButtons =
        document.querySelectorAll(
            '[data-event-filter]'
        );

    var eventCards =
        document.querySelectorAll(
            '[data-event-category]'
        );

    Array.prototype.forEach.call(
        filterButtons,
        function (button) {
            button.addEventListener(
                'click',
                function () {
                    var filter =
                        button.getAttribute(
                            'data-event-filter'
                        ) || 'ALL';

                    Array.prototype.forEach.call(
                        filterButtons,
                        function (item) {
                            item.classList.remove(
                                'is-active'
                            );
                        }
                    );

                    button.classList.add(
                        'is-active'
                    );

                    Array.prototype.forEach.call(
                        eventCards,
                        function (card) {
                            var category =
                                card.getAttribute(
                                    'data-event-category'
                                );

                            var status =
                                card.getAttribute(
                                    'data-event-status'
                                );

                            var show =
                                filter === 'ALL' ||
                                filter === category ||
                                filter === status;

                            card.style.display =
                                show
                                    ? ''
                                    : 'none';
                        }
                    );
                }
            );
        }
    );

    /*
    |--------------------------------------------------------------------------
    | Modal
    |--------------------------------------------------------------------------
    */

    var modal =
        document.getElementById('eventModal');

    var closeButton =
        document.getElementById(
            'eventModalClose'
        );

    var modalImage =
        document.getElementById(
            'eventModalImage'
        );

    var modalBadge =
        document.getElementById(
            'eventModalBadge'
        );

    var modalStatus =
        document.getElementById(
            'eventModalStatus'
        );

    var modalTitle =
        document.getElementById(
            'eventModalTitle'
        );

    var modalDescription =
        document.getElementById(
            'eventModalDescription'
        );

    var modalRules =
        document.getElementById(
            'eventModalRules'
        );

    var modalRewards =
        document.getElementById(
            'eventModalRewards'
        );

    var modalJoin =
        document.getElementById(
            'eventModalJoin'
        );

    function closeEventModal() {
        if (!modal) {
            return;
        }

        modal.classList.remove('is-open');
        modal.setAttribute(
            'aria-hidden',
            'true'
        );

        document.body.classList.remove(
            'event-modal-open'
        );
    }

    function rewardHtml(rewards) {
        if (
            !rewards ||
            rewards.length === 0
        ) {
            return (
                '<div class="event-reward-item">' +
                    '<span class="event-reward-rank">★</span>' +
                    '<div>' +
                        '<strong>Hadiah Event</strong>' +
                        '<small>Rincian hadiah mengikuti informasi event.</small>' +
                    '</div>' +
                '</div>'
            );
        }

        var html = '';

        rewards.forEach(function (reward) {
            var rank =
                reward.winner_rank ||
                '★';

            html +=
                '<div class="event-reward-item">' +
                    '<span class="event-reward-rank">' +
                        String(rank) +
                    '</span>' +
                    '<div>' +
                        '<strong>' +
                            escapeHtml(
                                reward.reward_title ||
                                'Hadiah'
                            ) +
                        '</strong>' +
                        '<small>' +
                            escapeHtml(
                                reward.reward_description ||
                                reward.reward_value ||
                                ''
                            ) +
                        '</small>' +
                    '</div>' +
                '</div>';
        });

        return html;
    }

    function escapeHtml(value) {
        var div =
            document.createElement('div');

        div.textContent =
            value === null ||
            value === undefined
                ? ''
                : String(value);

        return div.innerHTML;
    }

    function openEventModal(id) {
        var eventItem =
            eventMap[String(id)];

        if (!eventItem || !modal) {
            return;
        }

        modalImage.src =
            eventItem.image_url ||
            'assets/images/event/event-default.svg';

        modalImage.alt =
            eventItem.title ||
            'Event';

        modalBadge.textContent =
            eventItem.badge_text ||
            'EVENT';

        modalStatus.textContent =
            eventItem.status_label ||
            eventItem.status ||
            'EVENT';

        modalStatus.className =
            'event-status-badge';

        if (
            eventItem.status === 'UPCOMING'
        ) {
            modalStatus.classList.add(
                'is-upcoming'
            );
        }

        if (
            eventItem.status === 'ENDED'
        ) {
            modalStatus.classList.add(
                'is-ended'
            );
        }

        modalTitle.textContent =
            eventItem.title ||
            'Detail Event';

        modalDescription.textContent =
            eventItem.description ||
            eventItem.short_description ||
            '';

        modalRules.textContent =
            eventItem.rules_text ||
            'Ikuti ketentuan event yang berlaku.';

        modalRewards.innerHTML =
            rewardHtml(
                eventItem.rewards
            );

        if (eventItem.joined) {
            modalJoin.textContent =
                'SUDAH BERGABUNG';
        } else if (
            eventItem.status === 'ENDED'
        ) {
            modalJoin.textContent =
                'EVENT SELESAI';
        } else {
            modalJoin.textContent =
                'TUTUP';
        }

        modal.classList.add('is-open');

        modal.setAttribute(
            'aria-hidden',
            'false'
        );

        document.body.classList.add(
            'event-modal-open'
        );
    }

    var openButtons =
        document.querySelectorAll(
            '[data-event-open]'
        );

    Array.prototype.forEach.call(
        openButtons,
        function (button) {
            button.addEventListener(
                'click',
                function () {
                    openEventModal(
                        button.getAttribute(
                            'data-event-open'
                        )
                    );
                }
            );
        }
    );

    if (closeButton) {
        closeButton.addEventListener(
            'click',
            closeEventModal
        );
    }

    if (modalJoin) {
        modalJoin.addEventListener(
            'click',
            closeEventModal
        );
    }

    if (modal) {
        modal.addEventListener(
            'click',
            function (eventObject) {
                if (
                    eventObject.target === modal
                ) {
                    closeEventModal();
                }
            }
        );
    }

    document.addEventListener(
        'keydown',
        function (eventObject) {
            if (
                eventObject.key === 'Escape'
            ) {
                closeEventModal();
            }
        }
    );

    if (
        selectedEventId > 0 &&
        eventMap[String(selectedEventId)]
    ) {
        window.setTimeout(
            function () {
                openEventModal(
                    selectedEventId
                );
            },
            250
        );
    }
})();
</script>

<?php require __DIR__ . '/includes/footer.php'; ?>
