<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@ page import="com.pandoli365.bibimbap.security.CsrfTokens" %>
<%@ page import="org.springframework.web.util.HtmlUtils" %>
<!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-shadow: rgba(0, 0, 0, 0.06);
        --button-text: #1a1a1a;
        --field-bg: #fff;
      }
      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;
        --field-bg: #181818;
      }
      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;
      }
      .auth-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;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .auth-panel {
        width: min(100%, 30rem);
        padding: 2rem;
        box-sizing: border-box;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 2px 8px var(--card-shadow);
      }
      .auth-brand {
        display: flex;
        align-items: center;
        gap: 0.875rem;
        margin-bottom: 1.5rem;
      }
      .auth-brand__logo {
        width: 3rem;
        height: 3rem;
        border-radius: 10px;
        object-fit: contain;
        background: var(--surface);
        border: 1px solid var(--border);
      }
      .auth-panel__eyebrow {
        margin: 0 0 0.2rem;
        font-size: 0.75rem;
        font-weight: 800;
        color: var(--accent);
        letter-spacing: 0.02em;
      }
      .auth-panel__title {
        margin: 0;
        font-size: 1.75rem;
        line-height: 1.2;
        letter-spacing: 0;
      }
      .auth-form {
        display: grid;
        gap: 0.875rem;
      }
      .auth-field {
        display: grid;
        gap: 0.375rem;
      }
      .auth-field__label {
        font-size: 0.8125rem;
        font-weight: 700;
        color: var(--text);
      }
      .auth-field__input {
        width: 100%;
        height: 3rem;
        box-sizing: border-box;
        padding: 0 0.875rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--field-bg);
        color: var(--text);
        font-size: 1rem;
      }
      .auth-field__input::placeholder {
        color: var(--text-muted);
      }
      .auth-field__input:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(232, 165, 75, 0.25);
      }
      .auth-grid {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 0.875rem;
      }
      .auth-check {
        display: flex;
        align-items: flex-start;
        gap: 0.5rem;
        font-size: 0.8125rem;
        line-height: 1.5;
        color: var(--text-muted);
      }
      .auth-check input {
        flex-shrink: 0;
        width: 1rem;
        height: 1rem;
        margin-top: 0.15rem;
        accent-color: var(--accent);
      }
      .auth-link {
        color: var(--accent);
        font-weight: 700;
        text-decoration: none;
      }
      .auth-link:hover {
        text-decoration: underline;
      }
      .auth-button {
        width: 100%;
        min-height: 3rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        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;
      }
      .auth-button:hover {
        border-color: rgba(232, 165, 75, 0.45);
        box-shadow: 0 4px 12px var(--card-shadow);
      }
      .auth-button:active {
        transform: scale(0.98);
      }
      .auth-button--primary {
        border-color: transparent;
        background: var(--accent);
        color: var(--button-text);
      }
      .auth-panel__footer {
        margin: 1.25rem 0 0;
        text-align: center;
        color: var(--text-muted);
        font-size: 0.875rem;
      }
      @media (max-width: 560px) {
        .auth-main {
          align-items: flex-start;
          padding-top: 1.5rem;
        }
        .auth-panel {
          padding: 1.5rem 1rem;
        }
        .auth-grid {
          grid-template-columns: 1fr;
        }
      }
    </style>
</head>
<body>
    <jsp:include page="/WEB-INF/views/header.jsp"/>
    <%
        String ctx = request.getContextPath();
        String csrfToken = HtmlUtils.htmlEscape(CsrfTokens.getOrCreate(request.getSession()));
    %>
    <main class="auth-main">
        <section class="auth-panel" aria-labelledby="signup-title">
            <div class="auth-brand">
                <img class="auth-brand__logo" src="<%= ctx %>/images/logo.png" alt="" width="120" height="120" />
                <div>
                    <p class="auth-panel__eyebrow">BIBIMBAP</p>
                    <h1 class="auth-panel__title" id="signup-title">회원가입</h1>
                </div>
            </div>

            <form class="auth-form" action="<%= ctx %>/signup" method="post" id="signup-form">
                <input type="hidden" name="_csrf" value="<%= csrfToken %>" />
                <input type="hidden" name="provider" value="email" />
                <input type="hidden" name="providerUserId" id="signup-provider-user-id" />
                <div class="auth-field">
                    <label class="auth-field__label" for="signup-display-name">표시 이름</label>
                    <input class="auth-field__input" type="text" id="signup-display-name" name="displayName" autocomplete="nickname" maxlength="32" required />
                </div>
                <div class="auth-field">
                    <label class="auth-field__label" for="signup-email">이메일</label>
                    <input class="auth-field__input" type="email" id="signup-email" name="email" placeholder="name@example.com" autocomplete="email" required />
                </div>
                <div class="auth-grid">
                    <div class="auth-field">
                        <label class="auth-field__label" for="signup-password">비밀번호</label>
                        <input class="auth-field__input" type="password" id="signup-password" name="password" autocomplete="new-password" minlength="8" required />
                    </div>
                    <div class="auth-field">
                        <label class="auth-field__label" for="signup-password-confirm">비밀번호 확인</label>
                        <input class="auth-field__input" type="password" id="signup-password-confirm" name="passwordConfirm" autocomplete="new-password" minlength="8" required />
                    </div>
                </div>
                <label class="auth-check">
                    <input type="checkbox" name="termsAccepted" value="true" required />
                    <span>
                        <a class="auth-link" href="<%= ctx %>/terms" target="_blank" rel="noopener noreferrer">이용약관</a>과
                        <a class="auth-link" href="<%= ctx %>/operation-policy" target="_blank" rel="noopener noreferrer">운영정책</a>에 동의합니다.
                    </span>
                </label>
                <button class="auth-button auth-button--primary" type="submit">회원가입</button>
            </form>

            <p class="auth-panel__footer">
                이미 계정이 있나요?
                <a class="auth-link" href="<%= ctx %>/login">로그인</a>
            </p>
        </section>
    </main>
    <jsp:include page="/WEB-INF/views/footer.jsp"/>
    <script>
(function () {
  var ctx = '<%= ctx %>';
  var form = document.getElementById('signup-form');
  var emailInput = document.getElementById('signup-email');
  var providerUserId = document.getElementById('signup-provider-user-id');
  var submitBtn = form ? form.querySelector('button[type="submit"]') : null;

  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();
    }
  }

  if (form && emailInput && providerUserId) {
    form.addEventListener('submit', function (ev) {
      ev.preventDefault();

      if (!form.checkValidity()) {
        form.reportValidity();
        return;
      }

      providerUserId.value = emailInput.value.trim();
      if (submitBtn) {
        submitBtn.disabled = true;
      }

      fetch(form.action, {
        method: 'POST',
        headers: window.BibimbapCsrf ? window.BibimbapCsrf.headers({
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json'
        }) : {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json'
        },
        body: new URLSearchParams(new FormData(form))
      }).then(function (res) {
        if (res.ok) {
          openModal('계정 생성 완료', '계정 생성이 완료되었습니다.', '로그인으로 이동', function () {
            window.location.href = ctx + '/login';
          });
          return null;
        }

        return res.json().catch(function () {
          return { message: '회원가입을 처리하지 못했습니다.' };
        }).then(function (data) {
          throw new Error(data && data.message ? data.message : '회원가입을 처리하지 못했습니다.');
        });
      }).catch(function (err) {
        openModal('회원가입 실패', err.message || '회원가입을 처리하지 못했습니다.');
      }).finally(function () {
        if (submitBtn) {
          submitBtn.disabled = false;
        }
      });
    });
  }

  var params = new URLSearchParams(window.location.search);
  if (params.get('created') === '1') {
    openModal('계정 생성 완료', '계정 생성이 완료되었습니다.', '로그인으로 이동', function () {
      window.location.href = ctx + '/login';
    });
  } else if (params.get('error')) {
    var messages = {
      invalid: '입력값을 다시 확인해 주세요.',
      duplicate: '이미 가입된 이메일입니다.'
    };
    openModal('회원가입 실패', messages[params.get('error')] || '회원가입을 처리하지 못했습니다.');
  }
})();
    </script>
</body>
</html>
