<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.pandoli365.bibimbap.data.JamData" %>
<%@ page import="com.pandoli365.bibimbap.data.JamCriterionData" %>
<%@ page import="com.pandoli365.bibimbap.data.JamScoreData" %>
<%@ page import="org.springframework.web.util.HtmlUtils" %>
<%
    String ctx = request.getContextPath();
    JamData jam = (JamData) request.getAttribute("jam");
    Long jamId = (Long) request.getAttribute("jamId");
    Long gameId = (Long) request.getAttribute("gameId");
    List<JamCriterionData> criteria = (List<JamCriterionData>) request.getAttribute("criteria");
    List<JamScoreData> mine = (List<JamScoreData>) request.getAttribute("mine");

    Object rawCsrf = request.getAttribute("csrfToken");
    String csrfToken = rawCsrf == null ? "" : String.valueOf(rawCsrf);
    String csrfTokenHtml = HtmlUtils.htmlEscape(csrfToken);
    // JS 문자열 컨텍스트용: 따옴표/역슬래시/스크립트 종료 시퀀스 차단 (jam-detail.jsp 동형)
    String csrfTokenJs = csrfToken
            .replace("\\", "\\\\")
            .replace("'", "\\'")
            .replace("\"", "\\\"")
            .replace("<", "\\u003C")
            .replace(">", "\\u003E")
            .replace("\r", "")
            .replace("\n", "");

    // prefill: criterionKey -> score
    Map<String, Integer> mineByKey = new HashMap<String, Integer>();
    if (mine != null) {
        for (JamScoreData s : mine) {
            if (s == null || s.getCriterionKey() == null) {
                continue;
            }
            mineByKey.put(s.getCriterionKey(), s.getScore());
        }
    }
%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_csrf" content="<%= csrfTokenHtml %>">
    <jsp:include page="/WEB-INF/views/theme-init.jsp"/>
    <title><%= jam == null ? "심사 채점" : HtmlUtils.htmlEscape(jam.getTitle() == null ? "" : jam.getTitle()) %> 심사 채점 | bibimbap</title>
    <style>
      html {
        color-scheme: light;
        --surface: #faf8f5;
        --card-bg: #fff;
        --text: #1a1a1a;
        --text-muted: #5c5c5c;
        --accent: #e8a54b;
        --accent-soft: rgba(232, 165, 75, 0.16);
        --border: rgba(0, 0, 0, 0.08);
        --shadow: rgba(0, 0, 0, 0.06);
        --field-bg: #fff;
        --button-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);
        --shadow: rgba(0, 0, 0, 0.35);
        --field-bg: #181818;
        --button-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);
      }
      .scoring-page {
        max-width: 48rem;
        margin: 0 auto;
        padding: 1.5rem max(1rem, env(safe-area-inset-left)) 3rem max(1rem, env(safe-area-inset-right));
      }
      .scoring-back {
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
        min-height: 2.25rem;
        margin-bottom: 1rem;
        color: var(--text-muted);
        font-size: 0.875rem;
        font-weight: 800;
        text-decoration: none;
      }
      .scoring-back:hover {
        color: var(--accent);
      }
      .scoring-section {
        margin-bottom: 1rem;
        padding: 1.25rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 2px 8px var(--shadow);
      }
      .scoring-section h1 {
        margin: 0 0 1rem;
        font-size: 1.5rem;
        line-height: 1.2;
      }
      .scoring-row {
        display: grid;
        grid-template-columns: 1fr auto;
        align-items: center;
        gap: 0.75rem;
        padding: 0.75rem 0;
        border-bottom: 1px solid var(--border);
      }
      .scoring-row:last-of-type {
        border-bottom: none;
      }
      .scoring-row__label {
        font-weight: 800;
        color: var(--text);
      }
      .scoring-row__weight {
        margin-left: 0.4rem;
        font-size: 0.8rem;
        font-weight: 600;
        color: var(--text-muted);
      }
      .scoring-row select {
        min-height: 2.6rem;
        padding: 0 0.7rem;
        border: 1px solid var(--border);
        border-radius: 8px;
        background: var(--field-bg);
        color: var(--text);
        font-size: 0.95rem;
        box-sizing: border-box;
      }
      .scoring-actions {
        margin-top: 1.25rem;
      }
      .scoring-button {
        min-height: 2.75rem;
        padding: 0 1.25rem;
        border: 1px solid transparent;
        border-radius: 10px;
        background: var(--accent);
        color: var(--button-text);
        font-size: 0.9375rem;
        font-weight: 900;
        cursor: pointer;
      }
      .scoring-status {
        margin-top: 0.9rem;
        font-size: 0.9rem;
        color: var(--text-muted);
        min-height: 1.2em;
      }
      .empty-note {
        color: var(--text-muted);
        font-size: 0.9rem;
      }
    </style>
</head>
<body>
    <jsp:include page="/WEB-INF/views/header.jsp"/>
    <main class="scoring-page">
        <a class="scoring-back" href="<%= ctx %>/jams">← 게임잼 목록</a>
        <section class="scoring-section" aria-labelledby="scoring-title">
            <h1 id="scoring-title"><%= jam == null ? "" : HtmlUtils.htmlEscape(jam.getTitle() == null ? "" : jam.getTitle()) %> 심사 채점</h1>
<%
    if (criteria == null || criteria.isEmpty()) {
%>
            <p class="empty-note">채점 항목이 없습니다.</p>
<%
    } else {
%>
            <form id="scoring-form">
<%
        for (JamCriterionData c : criteria) {
            if (c == null || c.getCriterionKey() == null) {
                continue;
            }
            String key = c.getCriterionKey();
            String keyHtml = HtmlUtils.htmlEscape(key);
            String nameHtml = HtmlUtils.htmlEscape(c.getDisplayName() == null ? key : c.getDisplayName());
            String weightStr = c.getWeight() == null ? "" : c.getWeight().toPlainString();
            Integer prefill = mineByKey.get(key);
%>
                <div class="scoring-row">
                    <label class="scoring-row__label" for="score-<%= keyHtml %>"><%= nameHtml %><%= weightStr.isEmpty() ? "" : "<span class=\"scoring-row__weight\">가중치 " + HtmlUtils.htmlEscape(weightStr) + "</span>" %></label>
                    <select id="score-<%= keyHtml %>" data-criterion-key="<%= keyHtml %>">
                        <option value=""<%= prefill == null ? " selected" : "" %>>미선택</option>
<%
            for (int v = 1; v <= 5; v++) {
%>
                        <option value="<%= v %>"<%= prefill != null && prefill.intValue() == v ? " selected" : "" %>><%= v %></option>
<%
            }
%>
                    </select>
                </div>
<%
        }
%>
                <input type="hidden" name="_csrf" value="<%= csrfTokenHtml %>">
                <div class="scoring-actions">
                    <button type="submit" class="scoring-button">채점 저장</button>
                </div>
                <p id="scoring-status" class="scoring-status" role="status" aria-live="polite"></p>
            </form>
<%
    }
%>
        </section>
    </main>
    <jsp:include page="/WEB-INF/views/footer.jsp"/>
    <script>
(function () {
  var ctx = '<%= ctx %>';
  var CSRF_TOKEN = '<%= csrfTokenJs %>';
  var JAM_ID = '<%= jamId == null ? "" : jamId.longValue() %>';
  var GAME_ID = '<%= gameId == null ? "" : gameId.longValue() %>';

  var form = document.getElementById('scoring-form');
  var statusEl = document.getElementById('scoring-status');
  if (!form) {
    return;
  }

  function setStatus(message) {
    if (statusEl) {
      statusEl.textContent = message;
    }
  }

  form.addEventListener('submit', function (ev) {
    ev.preventDefault();

    var scores = [];
    var selects = form.querySelectorAll('select[data-criterion-key]');
    for (var i = 0; i < selects.length; i++) {
      var sel = selects[i];
      var raw = sel.value;
      if (raw === '') {
        continue; // 미입력 항목은 제외 (부분 입력 허용)
      }
      scores.push({
        criterionKey: sel.getAttribute('data-criterion-key'),
        score: parseInt(raw, 10)
      });
    }

    if (scores.length === 0) {
      setStatus('점수를 1개 이상 선택해 주세요.');
      return;
    }

    setStatus('저장 중...');
    fetch(ctx + '/jams/' + encodeURIComponent(JAM_ID) + '/games/' + encodeURIComponent(GAME_ID) + '/scores', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': CSRF_TOKEN,
        'Accept': 'application/json'
      },
      body: JSON.stringify({ scores: scores })
    })
      .then(function (res) {
        if (res.ok) {
          setStatus('채점을 저장했습니다.');
          return;
        }
        setStatus('저장하지 못했습니다. (상태 ' + res.status + ')');
      })
      .catch(function () {
        setStatus('요청 중 오류가 발생했습니다.');
      });
  });
})();
    </script>
</body>
</html>
