<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@ page import="com.pandoli365.bibimbap.data.GameData" %>
<%@ page import="org.springframework.web.util.HtmlUtils" %>
<%@ page import="java.util.Collections" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Locale" %>
<!DOCTYPE html>
<%
    String ctx = request.getContextPath();
    String rawDisplayName = session.getAttribute("displayName") == null ? "" : String.valueOf(session.getAttribute("displayName"));
    String rawEmail = session.getAttribute("email") == null ? "" : String.valueOf(session.getAttribute("email"));
    String rawAvatarUrl = session.getAttribute("avatarUrl") == null ? "" : String.valueOf(session.getAttribute("avatarUrl"));
    String initialSource = rawDisplayName.isBlank() ? rawEmail : rawDisplayName;
    String initial = initialSource.isBlank() ? "B" : initialSource.substring(0, 1).toUpperCase(Locale.ROOT);

    String displayName = HtmlUtils.htmlEscape(rawDisplayName.isBlank() ? "bibimbap 사용자" : rawDisplayName);
    String email = HtmlUtils.htmlEscape(rawEmail.isBlank() ? "이메일 정보 없음" : rawEmail);
    String avatarUrl = HtmlUtils.htmlEscape(rawAvatarUrl);
    String avatarInitial = HtmlUtils.htmlEscape(initial);
    Object rawMyGames = request.getAttribute("myGames");
    List<GameData> myGames = rawMyGames instanceof List<?> ? (List<GameData>) rawMyGames : Collections.emptyList();
%>
<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-shadow: rgba(0, 0, 0, 0.06);
        --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);
        --card-shadow: rgba(0, 0, 0, 0.35);
        --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);
        display: flex;
        flex-direction: column;
      }
      .profile-main {
        width: 100%;
        max-width: 72rem;
        box-sizing: border-box;
        margin: 0 auto;
        padding: 2rem max(1rem, env(safe-area-inset-left)) 3rem max(1rem, env(safe-area-inset-right));
        flex: 1;
      }
      .profile-shell {
        width: min(100%, 42rem);
        margin: 0 auto;
      }
      .profile-heading {
        margin: 0 0 1rem;
      }
      .profile-heading__eyebrow {
        margin: 0 0 0.35rem;
        font-size: 0.75rem;
        font-weight: 800;
        color: var(--accent);
        letter-spacing: 0.02em;
      }
      .profile-heading__title {
        margin: 0;
        font-size: 1.75rem;
        line-height: 1.2;
        letter-spacing: 0;
      }
      .profile-panel {
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 2px 8px var(--card-shadow);
        overflow: hidden;
      }
      .profile-summary {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 1.5rem;
        border-bottom: 1px solid var(--border);
      }
      .profile-avatar {
        flex-shrink: 0;
        width: 4.5rem;
        height: 4.5rem;
        border-radius: 14px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        background: rgba(232, 165, 75, 0.18);
        color: var(--text);
        font-size: 1.75rem;
        font-weight: 900;
        border: 1px solid var(--border);
      }
      .profile-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .profile-avatar img[hidden],
      .profile-avatar span[hidden] {
        display: none;
      }
      .profile-summary__body {
        min-width: 0;
      }
      .profile-summary__name {
        margin: 0;
        font-size: 1.35rem;
        line-height: 1.25;
        letter-spacing: 0;
        word-break: break-word;
      }
      .profile-summary__email {
        margin: 0.35rem 0 0;
        color: var(--text-muted);
        font-size: 0.9375rem;
        word-break: break-word;
      }
      .profile-avatar-form {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-top: 0.875rem;
      }
      .profile-avatar-form__input {
        position: absolute;
        width: 1px;
        height: 1px;
        padding: 0;
        margin: -1px;
        overflow: hidden;
        clip: rect(0, 0, 0, 0);
        border: 0;
      }
      .profile-details {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 0;
      }
      .profile-detail {
        padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border);
      }
      .profile-detail:nth-child(odd) {
        border-right: 1px solid var(--border);
      }
      .profile-detail__label {
        margin: 0 0 0.25rem;
        font-size: 0.75rem;
        font-weight: 800;
        color: var(--text-muted);
      }
      .profile-detail__value {
        margin: 0;
        font-size: 0.9375rem;
        font-weight: 700;
        word-break: break-word;
      }
      .profile-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.625rem;
        padding: 1.25rem 1.5rem 1.5rem;
      }
      .profile-button {
        min-height: 2.75rem;
        border: 1px solid var(--border);
        border-radius: 10px;
        padding: 0 1rem;
        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;
        cursor: pointer;
        box-sizing: border-box;
        -webkit-tap-highlight-color: transparent;
      }
      .profile-button:hover {
        border-color: rgba(232, 165, 75, 0.45);
        box-shadow: 0 4px 12px var(--card-shadow);
      }
      .profile-button:active {
        transform: scale(0.98);
      }
      .profile-button--primary {
        border-color: transparent;
        background: var(--accent);
        color: var(--button-text);
      }
      .profile-button--small {
        min-height: 2.375rem;
        border-radius: 9px;
        padding: 0 0.875rem;
        font-size: 0.8125rem;
      }
      .profile-button:disabled {
        cursor: not-allowed;
        opacity: 0.55;
        box-shadow: none;
      }
      .profile-actions form {
        margin: 0;
      }
      .profile-games {
        margin-top: 1rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 2px 8px var(--card-shadow);
        overflow: hidden;
      }
      .profile-games__head {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 0.75rem;
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--border);
      }
      .profile-games__title {
        margin: 0;
        font-size: 1.05rem;
        line-height: 1.25;
        letter-spacing: 0;
      }
      .profile-games__count {
        color: var(--text-muted);
        font-size: 0.8125rem;
        font-weight: 800;
      }
      .profile-games__empty {
        margin: 0;
        padding: 1.25rem 1.5rem;
        color: var(--text-muted);
        font-size: 0.9375rem;
      }
      .profile-game-list {
        display: grid;
      }
      .profile-game {
        display: grid;
        grid-template-columns: 3.75rem minmax(0, 1fr) auto;
        gap: 0.875rem;
        align-items: center;
        padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border);
      }
      .profile-game:last-child {
        border-bottom: 0;
      }
      .profile-game__thumb {
        width: 3.75rem;
        height: 3.75rem;
        border-radius: 10px;
        border: 1px solid var(--border);
        background: rgba(232, 165, 75, 0.16);
        overflow: hidden;
        display: inline-flex;
        align-items: center;
        justify-content: center;
      }
      .profile-game__thumb img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .profile-game__fallback {
        width: 1.85rem;
        height: 1.85rem;
        opacity: 0.75;
      }
      .profile-game__body {
        min-width: 0;
      }
      .profile-game__name {
        margin: 0;
        color: var(--text);
        font-size: 0.975rem;
        font-weight: 900;
        line-height: 1.3;
        text-decoration: none;
        word-break: break-word;
      }
      .profile-game__name:hover {
        color: var(--accent);
      }
      .profile-game__meta {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-top: 0.45rem;
        color: var(--text-muted);
        font-size: 0.8125rem;
        font-weight: 700;
      }
      .profile-game__status {
        border-radius: 999px;
        padding: 0.15rem 0.5rem;
        background: rgba(92, 92, 92, 0.12);
        color: var(--text-muted);
      }
      .profile-game__status--visible {
        background: rgba(232, 165, 75, 0.18);
        color: var(--text);
      }
      .profile-game__actions {
        display: flex;
        gap: 0.5rem;
      }
      .profile-game__action {
        min-height: 2.25rem;
        padding: 0 0.75rem;
        border: 1px solid var(--border);
        border-radius: 9px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        color: var(--text);
        font-size: 0.8125rem;
        font-weight: 900;
        text-decoration: none;
      }
      .profile-game__action:hover {
        border-color: rgba(232, 165, 75, 0.45);
        color: var(--accent);
      }
      @media (max-width: 560px) {
        .profile-main {
          padding-top: 1.5rem;
        }
        .profile-summary {
          align-items: flex-start;
          flex-direction: column;
          padding: 1.25rem;
        }
        .profile-details {
          grid-template-columns: 1fr;
        }
        .profile-detail {
          padding: 1rem 1.25rem;
        }
        .profile-detail:nth-child(odd) {
          border-right: none;
        }
        .profile-actions {
          padding: 1.25rem;
        }
        .profile-button,
        .profile-avatar-form,
        .profile-actions form {
          width: 100%;
        }
        .profile-avatar-form .profile-button {
          flex: 1;
        }
        .profile-games__head {
          padding: 1.25rem;
        }
        .profile-game {
          grid-template-columns: 3.25rem minmax(0, 1fr);
          padding: 1rem 1.25rem;
        }
        .profile-game__thumb {
          width: 3.25rem;
          height: 3.25rem;
        }
        .profile-game__actions {
          grid-column: 1 / -1;
          justify-content: flex-end;
        }
      }
    </style>
</head>
<body>
    <jsp:include page="/WEB-INF/views/header.jsp"/>
    <main class="profile-main">
        <section class="profile-shell" aria-labelledby="profile-title">
            <div class="profile-heading">
                <p class="profile-heading__eyebrow">BIBIMBAP ACCOUNT</p>
                <h1 class="profile-heading__title" id="profile-title">프로필</h1>
            </div>

            <div class="profile-panel">
                <div class="profile-summary">
                    <div class="profile-avatar" aria-hidden="true">
                        <img id="profile-avatar-img" src="<%= avatarUrl %>" alt="" width="96" height="96" <%= avatarUrl.isBlank() ? "hidden" : "" %> />
                        <span id="profile-avatar-initial" <%= avatarUrl.isBlank() ? "" : "hidden" %>><%= avatarInitial %></span>
                    </div>
                    <div class="profile-summary__body">
                        <h2 class="profile-summary__name" id="profile-display-name"><%= displayName %></h2>
                        <p class="profile-summary__email"><%= email %></p>
                        <form class="profile-avatar-form" action="<%= ctx %>/profile/avatar" method="post" enctype="multipart/form-data" id="profile-avatar-form">
                            <label class="profile-button profile-button--small" for="profile-avatar-input" id="profile-avatar-label">프로필 이미지 변경</label>
                            <input class="profile-avatar-form__input" type="file" id="profile-avatar-input" name="avatar" accept="image/png,image/jpeg,image/webp,image/gif" />
                            <button class="profile-button profile-button--small" type="button" id="profile-nickname-button" data-current-name="<%= displayName %>">닉네임 변경</button>
                        </form>
                    </div>
                </div>

                <div class="profile-actions">
                    <a class="profile-button profile-button--primary" href="<%= ctx %>/">홈으로 이동</a>
                    <form action="<%= ctx %>/logout" method="post">
                        <button class="profile-button" type="submit">로그아웃</button>
                    </form>
                </div>
            </div>

            <div class="profile-games">
                <div class="profile-games__head">
                    <h2 class="profile-games__title">내 게임</h2>
                    <span class="profile-games__count"><%= myGames.size() %>개</span>
                </div>
                <% if (myGames.isEmpty()) { %>
                <p class="profile-games__empty">등록한 게임이 없습니다.</p>
                <% } else { %>
                <div class="profile-game-list">
                    <%
                        for (GameData game : myGames) {
                            if (game == null || game.getId() == null) {
                                continue;
                            }
                            String gameName = HtmlUtils.htmlEscape(game.getName() == null || game.getName().isBlank() ? "제목 없음" : game.getName());
                            String rawThumbUrl = game.getThumbnailUrl();
                            boolean hasImage = rawThumbUrl != null && !rawThumbUrl.isBlank();
                            String thumbUrl = "";
                            if (hasImage) {
                                thumbUrl = rawThumbUrl.startsWith("/") ? ctx + rawThumbUrl : rawThumbUrl;
                                thumbUrl = HtmlUtils.htmlEscape(thumbUrl);
                            }
                            boolean visible = game.getVisible() == null || game.getVisible();
                    %>
                    <div class="profile-game">
                        <a class="profile-game__thumb" href="<%= ctx %>/game/<%= game.getId() %>" aria-hidden="true" tabindex="-1">
                            <% if (hasImage) { %>
                            <img src="<%= thumbUrl %>" alt="" loading="lazy" decoding="async" />
                            <% } else { %>
                            <img class="profile-game__fallback" src="<%= ctx %>/images/logo.png" alt="" width="40" height="40" />
                            <% } %>
                        </a>
                        <div class="profile-game__body">
                            <a class="profile-game__name" href="<%= ctx %>/game/<%= game.getId() %>"><%= gameName %></a>
                            <div class="profile-game__meta">
                                <span class="profile-game__status <%= visible ? "profile-game__status--visible" : "" %>"><%= visible ? "공개" : "비공개" %></span>
                                <span>좋아요 <%= String.format("%,d", game.getLikeCount() == null ? 0 : game.getLikeCount()) %></span>
                            </div>
                        </div>
                        <div class="profile-game__actions">
                            <a class="profile-game__action" href="<%= ctx %>/game/<%= game.getId() %>/edit">수정</a>
                        </div>
                    </div>
                    <% } %>
                </div>
                <% } %>
            </div>
        </section>
    </main>
    <jsp:include page="/WEB-INF/views/footer.jsp"/>
    <script>
(function () {
  var ctx = '<%= ctx %>';
  var form = document.getElementById('profile-avatar-form');
  var input = document.getElementById('profile-avatar-input');
  var avatarLabel = document.getElementById('profile-avatar-label');
  var avatarImg = document.getElementById('profile-avatar-img');
  var avatarInitial = document.getElementById('profile-avatar-initial');
  var nicknameButton = document.getElementById('profile-nickname-button');
  var displayNameEl = document.getElementById('profile-display-name');
  var previewUrl = null;
  var savedAvatarSrc = avatarImg && !avatarImg.hidden ? avatarImg.getAttribute('src') : '';
  var defaultLabelText = avatarLabel ? avatarLabel.textContent : '';
  var defaultNicknameText = nicknameButton ? nicknameButton.textContent : '';

  function openModal(title, message, confirmText, onConfirm) {
    if (window.BibimbapModal && typeof window.BibimbapModal.alert === 'function') {
      window.BibimbapModal.alert({
        title: title,
        message: message,
        confirmText: confirmText || '확인',
        onConfirm: onConfirm
      });
      return;
    }
    alert(message);
    if (typeof onConfirm === 'function') {
      onConfirm();
    }
  }

  function setAvatar(src) {
    if (!avatarImg) return;
    avatarImg.src = src;
    avatarImg.hidden = false;
    if (avatarInitial) {
      avatarInitial.hidden = true;
    }
  }

  function showInitialAvatar() {
    if (avatarImg) {
      avatarImg.removeAttribute('src');
      avatarImg.hidden = true;
    }
    if (avatarInitial) {
      avatarInitial.hidden = false;
    }
  }

  function clearPreviewUrl() {
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
      previewUrl = null;
    }
  }

  function restoreSavedAvatar() {
    clearPreviewUrl();
    if (savedAvatarSrc) {
      setAvatar(savedAvatarSrc);
    } else {
      showInitialAvatar();
    }
  }

  function setUploading(uploading) {
    if (!avatarLabel) return;
    avatarLabel.textContent = uploading ? '변경 중...' : defaultLabelText;
    avatarLabel.setAttribute('aria-disabled', uploading ? 'true' : 'false');
    avatarLabel.style.pointerEvents = uploading ? 'none' : '';
  }

  function setNicknameSaving(saving) {
    if (!nicknameButton) return;
    nicknameButton.disabled = saving;
    nicknameButton.textContent = saving ? '변경 중...' : defaultNicknameText;
  }

  function currentDisplayName() {
    if (!nicknameButton) return '';
    return nicknameButton.getAttribute('data-current-name') || '';
  }

  function updateDisplayName(displayName) {
    if (displayNameEl) {
      displayNameEl.textContent = displayName;
    }
    if (nicknameButton) {
      nicknameButton.setAttribute('data-current-name', displayName);
    }
    if (avatarInitial) {
      avatarInitial.textContent = displayName ? displayName.charAt(0).toUpperCase() : 'B';
    }
  }

  function submitNickname(nextName) {
    var value = (nextName || '').trim();
    if (!value) {
      openModal('닉네임 변경 실패', '변경할 닉네임을 입력해 주세요.');
      return;
    }
    if (value.length > 32) {
      openModal('닉네임 변경 실패', '닉네임은 32자 이하로 입력해 주세요.');
      return;
    }

    var body = new URLSearchParams();
    body.set('displayName', value);
    setNicknameSaving(true);

    fetch(ctx + '/profile/nickname', {
      method: 'POST',
      headers: window.BibimbapCsrf ? window.BibimbapCsrf.headers({
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      }) : {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: body
    }).then(function (res) {
      return res.json().catch(function () {
        return { message: '닉네임을 변경하지 못했습니다.' };
      }).then(function (data) {
        if (!res.ok) {
          var error = new Error(data && data.message ? data.message : '닉네임을 변경하지 못했습니다.');
          error.status = res.status;
          throw error;
        }
        return data;
      });
    }).then(function (data) {
      updateDisplayName(data && data.displayName ? data.displayName : value);
      openModal('닉네임 변경 완료', '닉네임이 변경되었습니다.');
    }).catch(function (err) {
      openModal('닉네임 변경 실패', err.message || '닉네임을 변경하지 못했습니다.', '확인', function () {
        if (err.status === 401) {
          window.location.href = ctx + '/login';
        }
      });
    }).finally(function () {
      setNicknameSaving(false);
    });
  }

  function openNicknamePrompt() {
    var currentName = currentDisplayName();
    if (window.BibimbapModal && typeof window.BibimbapModal.prompt === 'function') {
      window.BibimbapModal.prompt({
        title: '닉네임 변경',
        message: '새로운 닉네임을 입력해 주세요.',
        label: '닉네임',
        value: currentName,
        maxLength: 32,
        confirmText: '변경',
        cancelText: '취소',
        onConfirm: submitNickname
      });
      return;
    }
    var nextName = prompt('새로운 닉네임을 입력해 주세요.', currentName);
    if (nextName !== null) {
      submitNickname(nextName);
    }
  }

  function uploadAvatar(file) {
    if (!form || !file) return;

    var body = new FormData();
    body.append('avatar', file);
    setUploading(true);

    fetch(form.action, {
      method: 'POST',
      headers: window.BibimbapCsrf ? window.BibimbapCsrf.headers({
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      }) : {
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: body
    }).then(function (res) {
      return res.json().catch(function () {
        return { message: '프로필 이미지를 저장하지 못했습니다.' };
      }).then(function (data) {
        if (!res.ok) {
          var error = new Error(data && data.message ? data.message : '프로필 이미지를 저장하지 못했습니다.');
          error.status = res.status;
          throw error;
        }
        return data;
      });
    }).then(function (data) {
      if (data && data.avatarUrl) {
        clearPreviewUrl();
        savedAvatarSrc = data.avatarUrl + '?v=' + Date.now();
        setAvatar(savedAvatarSrc);
      }
    }).catch(function (err) {
      restoreSavedAvatar();
      openModal('이미지 변경 실패', err.message || '프로필 이미지를 저장하지 못했습니다.', '확인', function () {
        if (err.status === 401) {
          window.location.href = ctx + '/login';
        }
      });
    }).finally(function () {
      if (input) {
        input.value = '';
      }
      setUploading(false);
    });
  }

  if (input) {
    input.addEventListener('change', function () {
      clearPreviewUrl();
      var file = input.files && input.files[0];
      if (!file) {
        return;
      }
      if (!file.type || file.type.indexOf('image/') !== 0) {
        input.value = '';
        restoreSavedAvatar();
        openModal('이미지 변경 실패', '이미지 파일만 선택해 주세요.');
        return;
      }

      previewUrl = URL.createObjectURL(file);
      setAvatar(previewUrl);
      uploadAvatar(file);
    });
  }

  if (nicknameButton) {
    nicknameButton.addEventListener('click', openNicknamePrompt);
  }

  if (form) {
    form.addEventListener('submit', function (ev) {
      ev.preventDefault();
    });
  }
})();
    </script>
</body>
</html>
