<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@ page import="com.pandoli365.bibimbap.data.GameData" %>
<%@ page import="com.pandoli365.bibimbap.data.TagData" %>
<%@ page import="org.springframework.web.util.HtmlUtils" %>
<%@ page import="java.util.Collections" %>
<%@ page import="java.util.Collection" %>
<%@ page import="java.util.HashSet" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Set" %>
<%
    String ctx = request.getContextPath();
    jakarta.servlet.http.HttpSession homeSession = request.getSession(false);
    boolean loggedIn = homeSession != null && homeSession.getAttribute("userId") != null;
    List<GameData> games = Collections.emptyList();
    Object gamesAttr = request.getAttribute("games");
    if (gamesAttr instanceof List<?>) {
        games = (List<GameData>) gamesAttr;
    }
    String searchQuery = "";
    Object searchQueryAttr = request.getAttribute("searchQuery");
    if (searchQueryAttr instanceof String) {
        searchQuery = ((String) searchQueryAttr).trim();
    }
    boolean searching = !searchQuery.isBlank();
    String escapedSearchQuery = HtmlUtils.htmlEscape(searchQuery);

    // 고도화 검색(GET /games/search) 폼 prefill 값. 기존 / 진입 시 전부 null → 빈값으로 안전 렌더.
    String searchKeyword = "";
    Object searchKeywordAttr = request.getAttribute("searchKeyword");
    if (searchKeywordAttr instanceof String) {
        searchKeyword = ((String) searchKeywordAttr).trim();
    }
    String escapedSearchKeyword = HtmlUtils.htmlEscape(searchKeyword);

    String searchCreator = "";
    Object searchCreatorAttr = request.getAttribute("searchCreator");
    if (searchCreatorAttr instanceof String) {
        searchCreator = ((String) searchCreatorAttr).trim();
    }
    String escapedSearchCreator = HtmlUtils.htmlEscape(searchCreator);

    String searchSort = "latest";
    Object searchSortAttr = request.getAttribute("searchSort");
    if (searchSortAttr instanceof String && !((String) searchSortAttr).isBlank()) {
        searchSort = ((String) searchSortAttr).trim();
    }

    String searchTagMode = "and";
    Object searchTagModeAttr = request.getAttribute("searchTagMode");
    if (searchTagModeAttr instanceof String && !((String) searchTagModeAttr).isBlank()) {
        searchTagMode = ((String) searchTagModeAttr).trim();
    }

    List<TagData> availableTags = Collections.emptyList();
    Object availableTagsAttr = request.getAttribute("availableTags");
    if (availableTagsAttr instanceof List<?>) {
        availableTags = (List<TagData>) availableTagsAttr;
    }

    Set<String> selectedTagSlugs = new HashSet<>();
    Object selectedTagSlugsAttr = request.getAttribute("selectedTagSlugs");
    if (selectedTagSlugsAttr instanceof Collection<?>) {
        for (Object slugObj : (Collection<?>) selectedTagSlugsAttr) {
            if (slugObj instanceof String) {
                selectedTagSlugs.add((String) slugObj);
            }
        }
    }

    String nextCursor = "";
    Object nextCursorAttr = request.getAttribute("nextCursor");
    if (nextCursorAttr instanceof String) {
        nextCursor = ((String) nextCursorAttr).trim();
    }
    boolean hasNextPage = !nextCursor.isBlank();

    com.pandoli365.bibimbap.data.JamData activeJam = null;
    Object activeJamAttr = request.getAttribute("activeJam");
    if (activeJamAttr instanceof com.pandoli365.bibimbap.data.JamData) {
        activeJam = (com.pandoli365.bibimbap.data.JamData) activeJamAttr;
    }
    int activeJamCount = 0;
    Object activeJamCountAttr = request.getAttribute("activeJamCount");
    if (activeJamCountAttr instanceof Integer) {
        activeJamCount = (Integer) activeJamCountAttr;
    }
    boolean showJamBanner = activeJamCount > 0 && activeJam != null && activeJam.getSlug() != null && !activeJam.getSlug().isBlank();
%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <jsp:include page="/WEB-INF/views/theme-init.jsp"/>
    <title>bibimbap</title>
    <style>
      html {
        color-scheme: light;
        --surface: #faf8f5;
        --card-bg: #fff;
        --text: #1a1a1a;
        --text-muted: #5c5c5c;
        --accent: #e8a54b;
        --border: rgba(0, 0, 0, 0.08);
        --card-media-1: #f0ebe3;
        --card-media-2: #e5ddd2;
        --card-media-3: #dccfb8;
        --card-shadow: rgba(0, 0, 0, 0.06);
        --search-btn-text: #1a1a1a;
      }
      html[data-theme="dark"] {
        color-scheme: dark;
        --surface: #121212;
        --card-bg: #1e1e1e;
        --text: #ece8e1;
        --text-muted: #a39e96;
        --border: rgba(255, 255, 255, 0.1);
        --card-media-1: #2a2620;
        --card-media-2: #1f1c18;
        --card-media-3: #3d3528;
        --card-shadow: rgba(0, 0, 0, 0.35);
        --search-btn-text: #1a1a1a;
      }
      body {
        margin: 0;
        min-height: 100vh;
        font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Noto Sans KR", sans-serif;
        background: var(--surface);
        color: var(--text);
      }
      .page-main {
        max-width: 72rem;
        margin: 0 auto;
        padding: 1rem max(1rem, env(safe-area-inset-left)) 2.5rem max(1rem, env(safe-area-inset-right));
      }
      @media (min-width: 640px) {
        .page-main {
          padding-top: 1.5rem;
        }
      }

      .home-toolbar {
        display: flex;
        align-items: stretch;
        gap: 0.625rem;
        margin-bottom: 0.75rem;
      }
      .home-action-button {
        flex-shrink: 0;
        min-height: 3rem;
        padding: 0 0.875rem 0 0.625rem;
        border: 1px solid rgba(232, 165, 75, 0.32);
        border-radius: 12px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        background: var(--card-bg);
        color: var(--text);
        font-size: 0.9375rem;
        font-weight: 800;
        text-decoration: none;
        box-sizing: border-box;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
        white-space: nowrap;
        -webkit-tap-highlight-color: transparent;
      }
      .home-action-button:hover {
        border-color: rgba(232, 165, 75, 0.62);
        box-shadow: 0 6px 16px var(--card-shadow);
      }
      .home-action-button:active {
        transform: scale(0.98);
      }
      .home-action-button__icon {
        width: 1.75rem;
        height: 1.75rem;
        border-radius: 8px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background: var(--accent);
        color: #1a1a1a;
        flex-shrink: 0;
      }
      .home-action-button__icon svg {
        width: 1.125rem;
        height: 1.125rem;
      }
      @media (max-width: 760px) {
        .home-toolbar {
          flex-direction: column;
        }
        .home-action-button {
          width: 100%;
        }
      }

      /* 검색 */
      .search-section {
        width: min(100%, 48rem);
        margin: 0 auto 1.25rem;
      }
      .search-form {
        flex: 1;
        min-width: 0;
        display: flex;
        gap: 0.5rem;
        align-items: stretch;
      }
      .search-form__field {
        flex: 1;
        min-width: 0;
      }
      .search-form__label {
        position: absolute;
        width: 1px;
        height: 1px;
        padding: 0;
        margin: -1px;
        overflow: hidden;
        clip: rect(0, 0, 0, 0);
        border: 0;
      }
      .search-form__input {
        width: 100%;
        box-sizing: border-box;
        height: 3rem;
        padding: 0 1rem 0 2.75rem;
        font-size: 1rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        color: var(--text);
        background-color: var(--card-bg);
        background-repeat: no-repeat;
        background-position: 0.875rem 50%;
        background-size: 1.125rem;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' fill='none' stroke='%23999' stroke-width='2'%3E%3Ccircle cx='8.5' cy='8.5' r='5.5'/%3E%3Cpath d='M12 12l5 5'/%3E%3C/svg%3E");
      }
      html[data-theme="dark"] .search-form__input {
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' fill='none' stroke='%23aaa' stroke-width='2'%3E%3Ccircle cx='8.5' cy='8.5' r='5.5'/%3E%3Cpath d='M12 12l5 5'/%3E%3C/svg%3E");
      }
      .search-form__input::placeholder {
        color: var(--text-muted);
      }
      .search-form__input:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(232, 165, 75, 0.25);
      }
      .search-form__submit {
        flex-shrink: 0;
        min-width: 4.5rem;
        height: 3rem;
        padding: 0 1rem;
        font-size: 0.9375rem;
        font-weight: 600;
        color: var(--search-btn-text);
        background: var(--accent);
        border: none;
        border-radius: 12px;
        cursor: pointer;
        -webkit-tap-highlight-color: transparent;
      }
      .search-form__submit:active {
        transform: scale(0.98);
      }

      .search-history {
        margin-top: 0.75rem;
      }
      .search-history[hidden] {
        display: none !important;
      }
      .search-history__head {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 0.5rem;
        margin-bottom: 0.5rem;
      }
      .search-history__label {
        font-size: 0.75rem;
        font-weight: 600;
        color: var(--text-muted);
        letter-spacing: 0.02em;
      }
      .search-history__clear {
        padding: 0.25rem 0.5rem;
        font-size: 0.6875rem;
        font-weight: 500;
        color: var(--text-muted);
        background: transparent;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        -webkit-tap-highlight-color: transparent;
      }
      .search-history__clear:hover {
        color: var(--accent);
        background: rgba(232, 165, 75, 0.12);
      }
      .search-history__chips {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
      }
      .search-history__chip {
        display: inline-flex;
        align-items: center;
        gap: 0.15rem;
        max-width: 100%;
        padding: 0.2rem 0.35rem 0.2rem 0.65rem;
        font-size: 0.8125rem;
        color: var(--text);
        background: var(--card-bg);
        border: 1px solid var(--border);
        border-radius: 999px;
        -webkit-tap-highlight-color: transparent;
      }
      .search-history__chip-text {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 12rem;
        margin: 0;
        padding: 0.15rem 0;
        font: inherit;
        color: inherit;
        text-align: left;
        background: none;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }
      .search-history__chip-text:hover {
        color: var(--accent);
      }
      .search-history__chip-remove {
        flex-shrink: 0;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 1.25rem;
        height: 1.25rem;
        padding: 0;
        font-size: 1rem;
        line-height: 1;
        color: var(--text-muted);
        background: transparent;
        border: none;
        border-radius: 50%;
        cursor: pointer;
      }
      .search-history__chip-remove:hover {
        color: var(--text);
        background: rgba(0, 0, 0, 0.06);
      }
      html[data-theme="dark"] .search-history__chip-remove:hover {
        background: rgba(255, 255, 255, 0.08);
      }

      /* 고도화 검색 */
      .advanced-search {
        margin-top: 0.75rem;
        padding: 0.875rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
      }
      .advanced-search__row {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        align-items: stretch;
        margin-bottom: 0.625rem;
      }
      .advanced-search__row:last-child {
        margin-bottom: 0;
      }
      .advanced-search__input,
      .advanced-search__select {
        flex: 1;
        min-width: 9rem;
        box-sizing: border-box;
        height: 2.75rem;
        padding: 0 0.75rem;
        font-size: 0.9375rem;
        color: var(--text);
        background-color: var(--surface);
        border: 1px solid var(--border);
        border-radius: 10px;
      }
      .advanced-search__input:focus,
      .advanced-search__select:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(232, 165, 75, 0.25);
      }
      .advanced-search__tags-label {
        display: block;
        margin-bottom: 0.375rem;
        font-size: 0.75rem;
        font-weight: 600;
        color: var(--text-muted);
        letter-spacing: 0.02em;
      }
      .advanced-search__tags {
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;
      }
      .advanced-search__tag {
        display: inline-flex;
        align-items: center;
        gap: 0.3rem;
        padding: 0.3rem 0.6rem;
        font-size: 0.8125rem;
        color: var(--text);
        background: var(--surface);
        border: 1px solid var(--border);
        border-radius: 999px;
        cursor: pointer;
        -webkit-tap-highlight-color: transparent;
      }
      .advanced-search__tag input {
        margin: 0;
      }
      .advanced-search__submit {
        flex-shrink: 0;
        min-width: 6rem;
        height: 2.75rem;
        padding: 0 1.25rem;
        font-size: 0.9375rem;
        font-weight: 600;
        color: var(--search-btn-text);
        background: var(--accent);
        border: none;
        border-radius: 10px;
        cursor: pointer;
        -webkit-tap-highlight-color: transparent;
      }
      .advanced-search__submit:active {
        transform: scale(0.98);
      }

      /* 카드 그리드: 모바일 2열 → 태블릿 3열 → 데스크톱 4~5열 */
      .card-grid {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 0.625rem;
      }
      @media (min-width: 480px) {
        .card-grid {
          gap: 0.75rem;
        }
      }
      @media (min-width: 640px) {
        .card-grid {
          grid-template-columns: repeat(3, minmax(0, 1fr));
          gap: 1rem;
        }
      }
      @media (min-width: 900px) {
        .card-grid {
          grid-template-columns: repeat(4, minmax(0, 1fr));
        }
      }
      @media (min-width: 1200px) {
        .card-grid {
          grid-template-columns: repeat(5, minmax(0, 1fr));
        }
      }

      a.card {
        display: flex;
        flex-direction: column;
        border-radius: 12px;
        overflow: hidden;
        background: var(--card-bg);
        border: 1px solid var(--border);
        box-shadow: 0 2px 8px var(--card-shadow);
        text-decoration: none;
        color: inherit;
        cursor: pointer;
        transition: box-shadow 0.18s ease, transform 0.18s ease, border-color 0.18s ease;
      }
      a.card:hover {
        box-shadow: 0 6px 16px var(--card-shadow);
        transform: translateY(-2px);
        border-color: rgba(232, 165, 75, 0.35);
      }
      a.card:focus {
        outline: none;
      }
      a.card:focus-visible {
        outline: 2px solid var(--accent);
        outline-offset: 2px;
      }
      /* 가로:세로 = 4:5 (포스터/썸네일에 흔한 비율, 3:5보다 덜 길쭉해 모바일 그리드에 균형 있음) */
      .card__media {
        position: relative;
        width: 100%;
        aspect-ratio: 4 / 5;
        background: var(--card-media-2);
      }
      .card__index {
        position: absolute;
        top: 0.45rem;
        left: 0.45rem;
        z-index: 2;
        padding: 0.25rem 0.5rem;
        font-size: 0.6875rem;
        font-weight: 800;
        letter-spacing: -0.02em;
        color: #1a1a1a;
        background: rgba(255, 255, 255, 0.93);
        border-radius: 6px;
        line-height: 1;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12);
      }
      html[data-theme="dark"] .card__index {
        background: rgba(30, 30, 30, 0.93);
        color: #ece8e1;
      }
      .card__img {
        width: 100%;
        height: 100%;
        display: block;
        object-fit: cover;
      }
      /* 이미지 없음: 로고만 중앙 */
      .card__media-empty {
        position: absolute;
        inset: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 14%;
        background: linear-gradient(160deg, var(--card-media-1) 0%, var(--card-media-2) 45%, var(--card-media-3) 100%);
      }
      .card__logo-fallback {
        width: min(52%, 7.5rem);
        height: auto;
        max-height: 42%;
        object-fit: contain;
        opacity: 0.88;
        filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.12));
      }
      html[data-theme="dark"] .card__logo-fallback {
        opacity: 0.92;
        filter: drop-shadow(0 2px 10px rgba(0, 0, 0, 0.45));
      }
      .card__body {
        padding: 0.5rem 0.625rem 0.625rem;
        flex: 1;
        min-height: 0;
        display: flex;
        flex-direction: column;
        gap: 0.2rem;
      }
      .card__game-name {
        margin: 0;
        font-size: 0.8125rem;
        font-weight: 600;
        line-height: 1.35;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        color: var(--text);
      }
      .card__creator {
        margin: 0;
        font-size: 0.6875rem;
        color: var(--text-muted);
        line-height: 1.35;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      .card__likes {
        margin: 0.15rem 0 0;
        font-size: 0.6875rem;
        font-weight: 600;
        color: var(--text);
        letter-spacing: -0.01em;
        font-variant-numeric: tabular-nums;
      }
      .home-empty {
        grid-column: 1 / -1;
        min-height: 11rem;
        padding: 2rem 1rem;
        border: 1px dashed var(--border);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-muted);
        background: var(--card-bg);
        text-align: center;
        line-height: 1.6;
      }
      .jam-banner {
        width: min(100%, 48rem);
        margin: 0 auto 1.25rem;
      }
      .jam-banner__link {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.875rem 1rem;
        border: 1px solid rgba(232, 165, 75, 0.4);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
        text-decoration: none;
        color: var(--text);
      }
      .jam-banner__link:hover {
        border-color: rgba(232, 165, 75, 0.7);
        box-shadow: 0 6px 16px var(--card-shadow);
      }
      .jam-banner__badge {
        flex-shrink: 0;
        padding: 0.25rem 0.55rem;
        font-size: 0.6875rem;
        font-weight: 800;
        color: #1a1a1a;
        background: var(--accent);
        border-radius: 6px;
      }
      .jam-banner__text {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 0.15rem;
      }
      .jam-banner__title {
        font-size: 0.9375rem;
        font-weight: 700;
        line-height: 1.3;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .jam-banner__meta {
        font-size: 0.75rem;
        color: var(--text-muted);
      }
      .jam-banner__arrow {
        flex-shrink: 0;
        font-size: 1.1rem;
        color: var(--accent);
      }
      .hub-more {
        display: flex;
        justify-content: center;
        margin-top: 1.5rem;
      }
      .hub-more__link {
        min-height: 3rem;
        padding: 0 1.5rem;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        color: var(--text);
        font-size: 0.9375rem;
        font-weight: 700;
        text-decoration: none;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
      }
      .hub-more__link:hover {
        border-color: rgba(232, 165, 75, 0.5);
        box-shadow: 0 6px 16px var(--card-shadow);
      }
    </style>
</head>
<body>
    <jsp:include page="/WEB-INF/views/header.jsp"/>
    <main class="page-main">
        <section class="search-section" aria-label="게임·제작자 검색">
            <div class="home-toolbar">
                <form class="search-form" role="search" action="<%= ctx %>/" method="get">
                    <div class="search-form__field">
                        <label class="search-form__label" for="q">게임·제작자 검색</label>
                        <input class="search-form__input" type="search" id="q" name="q" value="<%= escapedSearchQuery %>" placeholder="게임·제작자 검색" autocomplete="off" enterkeyhint="search" />
                    </div>
                    <button class="search-form__submit" type="submit">검색</button>
                </form>
                <% if (loggedIn) { %>
                <a class="home-action-button" href="<%= ctx %>/game/new">
                    <span class="home-action-button__icon" aria-hidden="true">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M12 5v14"/>
                            <path d="M5 12h14"/>
                        </svg>
                    </span>
                    <span>신규 게임 개시</span>
                </a>
                <% } %>
            </div>
            <form class="advanced-search" role="search" action="<%= ctx %>/games/search" method="get">
                <div class="advanced-search__row">
                    <label class="search-form__label" for="adv-keyword">게임 이름·소개 검색</label>
                    <input class="advanced-search__input" type="search" id="adv-keyword" name="keyword" value="<%= escapedSearchKeyword %>" placeholder="게임 이름·소개 검색" autocomplete="off" />
                    <label class="search-form__label" for="adv-creator">제작자(개발자) 검색</label>
                    <input class="advanced-search__input" type="search" id="adv-creator" name="creator" value="<%= escapedSearchCreator %>" placeholder="제작자(개발자) 검색" autocomplete="off" />
                </div>
                <div class="advanced-search__row">
                    <label class="search-form__label" for="adv-sort">정렬</label>
                    <select class="advanced-search__select" id="adv-sort" name="sort">
                        <option value="latest"<%= "latest".equals(searchSort) ? " selected" : "" %>>최신</option>
                        <option value="likes"<%= "likes".equals(searchSort) ? " selected" : "" %>>좋아요순</option>
                        <option value="views"<%= "views".equals(searchSort) ? " selected" : "" %>>방문순</option>
                        <option value="reviews"<%= "reviews".equals(searchSort) ? " selected" : "" %>>리뷰많은순</option>
                        <option value="rating"<%= "rating".equals(searchSort) ? " selected" : "" %>>평점높은순</option>
                        <option value="relevance"<%= "relevance".equals(searchSort) ? " selected" : "" %>>태그일치순</option>
                    </select>
                    <label class="search-form__label" for="adv-tagmode">태그 조건</label>
                    <select class="advanced-search__select" id="adv-tagmode" name="tagMode">
                        <option value="and"<%= "and".equals(searchTagMode) ? " selected" : "" %>>모두 포함</option>
                        <option value="or"<%= "or".equals(searchTagMode) ? " selected" : "" %>>하나라도</option>
                    </select>
                    <button class="advanced-search__submit" type="submit">상세 검색</button>
                </div>
                <% if (availableTags != null && !availableTags.isEmpty()) { %>
                <div class="advanced-search__row">
                    <div style="flex:1; min-width:0;">
                        <span class="advanced-search__tags-label">태그 필터</span>
                        <div class="advanced-search__tags">
                            <%
                                for (TagData tag : availableTags) {
                                    if (tag == null || tag.getSlug() == null || tag.getSlug().isBlank()) {
                                        continue;
                                    }
                                    String tagSlug = HtmlUtils.htmlEscape(tag.getSlug());
                                    String tagName = HtmlUtils.htmlEscape(tag.getName() == null || tag.getName().isBlank() ? tag.getSlug() : tag.getName());
                                    boolean tagChecked = selectedTagSlugs.contains(tag.getSlug());
                            %>
                            <label class="advanced-search__tag">
                                <input type="checkbox" name="tags" value="<%= tagSlug %>"<%= tagChecked ? " checked" : "" %> />
                                <span><%= tagName %></span>
                            </label>
                            <%
                                }
                            %>
                        </div>
                    </div>
                </div>
                <% } %>
            </form>
            <div class="search-history" id="search-history" hidden>
                <div class="search-history__head">
                    <span class="search-history__label">최근 검색</span>
                    <button type="button" class="search-history__clear" id="search-history-clear">전체 삭제</button>
                </div>
                <div class="search-history__chips" id="search-history-chips" role="list"></div>
            </div>
        </section>

        <% if (showJamBanner) {
            String jamTitle = HtmlUtils.htmlEscape(activeJam.getTitle() == null || activeJam.getTitle().isBlank() ? "게임잼" : activeJam.getTitle());
            String jamSlugParam = java.net.URLEncoder.encode(activeJam.getSlug(), java.nio.charset.StandardCharsets.UTF_8);
            String jamCountLabel = activeJamCount > 1 ? ("외 " + (activeJamCount - 1) + "개 진행 중") : "진행 중";
        %>
        <section class="jam-banner" aria-label="진행 중인 게임잼">
            <a class="jam-banner__link" href="<%= ctx %>/games/search?jam=<%= jamSlugParam %>">
                <span class="jam-banner__badge">게임잼</span>
                <span class="jam-banner__text">
                    <strong class="jam-banner__title"><%= jamTitle %></strong>
                    <span class="jam-banner__meta"><%= jamCountLabel %> · 출품작 보러가기</span>
                </span>
                <span class="jam-banner__arrow" aria-hidden="true">&rarr;</span>
            </a>
        </section>
        <% } %>

        <section class="card-grid" aria-label="추천 목록">
            <% if (games.isEmpty()) { %>
            <% if (searching) { %>
            <div class="home-empty">"<%= escapedSearchQuery %>"에 대한 검색 결과가 없습니다.</div>
            <% } else { %>
            <div class="home-empty">아직 공개된 게임이 없습니다.<br>로그인 후 첫 게임을 등록해 주세요.</div>
            <% } %>
            <% } %>
            <%
                for (int i = 0; i < games.size(); i++) {
                    GameData game = games.get(i);
                    if (game == null || game.getId() == null) {
                        continue;
                    }
                    String titleId = "game-title-" + game.getId();
                    String gameName = HtmlUtils.htmlEscape(game.getName() == null || game.getName().isBlank() ? "제목 없음" : game.getName());
                    String creator = HtmlUtils.htmlEscape(game.getCreator() == null || game.getCreator().isBlank() ? "bibimbap 사용자" : game.getCreator());
                    int likeCount = game.getLikeCount() == null ? 0 : game.getLikeCount();
                    String rawThumbUrl = game.getThumbnailUrl();
                    boolean hasImage = rawThumbUrl != null && !rawThumbUrl.isBlank();
                    String thumbUrl = "";
                    if (hasImage) {
                        thumbUrl = rawThumbUrl.startsWith("/") ? ctx + rawThumbUrl : rawThumbUrl;
                        thumbUrl = HtmlUtils.htmlEscape(thumbUrl);
                    }
            %>
            <a class="card" href="<%= ctx %>/game/<%= game.getId() %>" aria-labelledby="<%= titleId %>">
                <div class="card__media">
                    <span class="card__index" aria-hidden="true">#<%= game.getId() %></span>
                    <% if (hasImage) { %>
                    <img class="card__img" src="<%= thumbUrl %>" alt="" loading="lazy" decoding="async" />
                    <% } else { %>
                    <div class="card__media-empty" role="presentation">
                        <img class="card__logo-fallback" src="<%= ctx %>/images/logo.png" alt="" width="120" height="120" />
                    </div>
                    <% } %>
                </div>
                <div class="card__body">
                    <h2 class="card__game-name" id="<%= titleId %>"><%= gameName %></h2>
                    <p class="card__creator"><%= creator %></p>
                    <p class="card__likes">좋아요 <%= String.format("%,d", likeCount) %></p>
                </div>
            </a>
            <%
                }
            %>
        </section>

        <% if (hasNextPage) {
            String moreHref = ctx + "/?";
            if (searching) {
                moreHref += "q=" + java.net.URLEncoder.encode(searchQuery, java.nio.charset.StandardCharsets.UTF_8) + "&";
            }
            moreHref += "cursor=" + java.net.URLEncoder.encode(nextCursor, java.nio.charset.StandardCharsets.UTF_8);
        %>
        <nav class="hub-more" aria-label="더 많은 게임">
            <a class="hub-more__link" href="<%= moreHref %>">더 보기</a>
        </nav>
        <% } %>
    </main>
    <jsp:include page="/WEB-INF/views/footer.jsp"/>
    <script>
(function () {
  var STORAGE_KEY = 'bibimbap-search-history';
  var MAX_ITEMS = 10;

  function loadHistory() {
    try {
      var raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return [];
      var parsed = JSON.parse(raw);
      var list = Array.isArray(parsed) ? parsed.filter(function (s) { return typeof s === 'string' && s.trim(); }) : [];
      if (list.length > MAX_ITEMS) {
        list = list.slice(0, MAX_ITEMS);
        saveHistory(list);
      }
      return list;
    } catch (e) {
      return [];
    }
  }

  function saveHistory(items) {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
    } catch (e) {
      /* 용량 초과·비공개 모드 등 */
    }
  }

  /** 검색어 추가: 앞에 넣고, 동일 문구(대소문자 무시)는 제거 후 최대 개수 유지 */
  function addSearchQuery(query) {
    var q = (query || '').trim();
    if (!q) return;
    var list = loadHistory();
    var lower = q.toLowerCase();
    list = list.filter(function (item) { return item.toLowerCase() !== lower; });
    list.unshift(q);
    if (list.length > MAX_ITEMS) list = list.slice(0, MAX_ITEMS);
    saveHistory(list);
  }

  function removeSearchQuery(query) {
    var lower = (query || '').toLowerCase();
    var list = loadHistory().filter(function (item) { return item.toLowerCase() !== lower; });
    saveHistory(list);
  }

  function clearHistory() {
    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch (e) {}
  }

  var form = document.querySelector('.search-form');
  var input = document.getElementById('q');
  var historyEl = document.getElementById('search-history');
  var chipsEl = document.getElementById('search-history-chips');
  var clearBtn = document.getElementById('search-history-clear');

  function renderChips() {
    var list = loadHistory();
    chipsEl.innerHTML = '';
    if (!list.length) {
      historyEl.hidden = true;
      return;
    }
    historyEl.hidden = false;
    list.forEach(function (term) {
      var chip = document.createElement('div');
      chip.className = 'search-history__chip';
      chip.setAttribute('role', 'listitem');

      var textBtn = document.createElement('button');
      textBtn.type = 'button';
      textBtn.className = 'search-history__chip-text';
      textBtn.textContent = term;
      textBtn.title = term;
      textBtn.addEventListener('click', function () {
        input.value = term;
        form.submit();
      });

      var removeBtn = document.createElement('button');
      removeBtn.type = 'button';
      removeBtn.className = 'search-history__chip-remove';
      removeBtn.setAttribute('aria-label', '삭제: ' + term);
      removeBtn.textContent = '\u00D7';
      removeBtn.addEventListener('click', function (ev) {
        ev.stopPropagation();
        removeSearchQuery(term);
        renderChips();
      });

      chip.appendChild(textBtn);
      chip.appendChild(removeBtn);
      chipsEl.appendChild(chip);
    });
  }

  if (form && input) {
    form.addEventListener('submit', function (ev) {
      var q = input.value.trim();
      input.value = q;
      addSearchQuery(q);
      renderChips();
    });

    if (clearBtn) {
      clearBtn.addEventListener('click', function () {
        clearHistory();
        renderChips();
      });
    }

    renderChips();
  }
})();
    </script>
</body>
</html>
