<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/default_layout}">

<th:block layout:fragment="head">
  <style>
    .message-list { list-style: none; padding-left: 0; }
    .message-item { border: 1px solid #ddd; border-radius: 5px; margin-bottom: 1em; }
    .message-header { padding: 10px 15px; background: #f7f7f7; cursor: pointer; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; }
    .message-item.unread .message-header { font-weight: bold; background: #fffbe5; border-left: 3px solid #FFA500; }
    .message-content { padding: 15px; display: none; border-top: 1px solid #ddd; }
    .message-content.active { display: block; }
    .reply-form { margin-top: 1em; }
    .message-title { flex-grow: 1; }
  </style>
</th:block>

<th:block layout:fragment="content">
  <section class="wrapper style1">
    <div class="container">
      <header class="major">
        <h2 th:text="${pageTitle}"></h2>
      </header>

      <div class="box">
        <ul class="message-list">
          <li th:if="${#lists.isEmpty(messages)}">받은 쪽지가 없습니다.</li>
          <li th:each="msg : ${messages}" class="message-item" th:classappend="${!msg.isRead} ? 'unread'" th:data-message-id="${msg.id}">
            <div class="message-header" onclick="toggleMessage(this)">
              <div class="message-title">
                <span th:text="${msg.title}"></span>
                <small style="margin-left: 1em; color: #777;" th:text="'보낸 사람: ' + ${msg.senderId}"></small>
              </div>
              <small th:text="${#temporals.format(T(java.time.Instant).ofEpochMilli(msg.timestamp).atZone(T(java.time.ZoneId).systemDefault()), 'yyyy-MM-dd HH:mm')}"></small>
            </div>
            <div class="message-content">
              <p style="white-space: pre-wrap;" th:text="${msg.content}"></p>
              <hr/>
              <div class="reply-form">
                <h4>답장 보내기</h4>
                <form onsubmit="sendMessage(event, this)">
                  <input type="hidden" name="receiverId" th:value="${msg.senderId}" />
                  <div class="row gtr-50">
                    <div class="col-12">
                      <input type="text" name="title" placeholder="제목" th:value="'RE: ' + ${msg.title}" required />
                    </div>
                    <div class="col-12">
                      <textarea name="content" placeholder="내용" rows="4" required></textarea>
                    </div>
                    <div class="col-12">
                      <button type="submit" class="button primary">답장 전송</button>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </section>

  <script th:inline="javascript">
    const csrfToken = document.querySelector('meta[name="_csrf"]')?.getAttribute('content');
    const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.getAttribute('content');

    async function toggleMessage(headerElement) {
      const messageItem = headerElement.closest('.message-item');
      const content = messageItem.querySelector('.message-content');
      const messageId = messageItem.dataset.messageId;

      const isOpening = !content.classList.contains('active');

      // 모든 열린 쪽지 닫기
      document.querySelectorAll('.message-content.active').forEach(c => {
        if(c !== content) c.classList.remove('active');
      });
      content.classList.toggle('active');

      if (isOpening && messageItem.classList.contains('unread')) {
        const response = await fetch(`/messages/${messageId}/read`, {
          method: 'POST',
          headers: { [csrfHeader]: csrfToken }
        });
        if (response.ok) {
          messageItem.classList.remove('unread');
          // 헤더의 아이콘도 업데이트 할 수 있지만, 페이지 새로고침 전까지는 유지됩니다.
        }
      }
    }

    async function sendMessage(event, form) {
      event.preventDefault();
      const formData = new FormData(form);
      const data = {
        receiverId: formData.get('receiverId'),
        title: formData.get('title'),
        content: formData.get('content')
      };

      const submitButton = form.querySelector('button[type="submit"]');
      submitButton.disabled = true;
      submitButton.textContent = '전송 중...';

      const response = await fetch('/messages/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', [csrfHeader]: csrfToken },
        body: JSON.stringify(data)
      });

      if(response.ok) {
        alert('답장을 성공적으로 보냈습니다.');
        form.querySelector('textarea').value = ''; // 내용만 초기화
        toggleMessage(form.closest('.message-item').querySelector('.message-header')); // 답장 후 창 닫기
      } else {
        alert('답장 보내기에 실패했습니다.');
      }
      submitButton.disabled = false;
      submitButton.textContent = '답장 전송';
    }
  </script>
</th:block>
</html>