<!doctype html>
<html lang="ko"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_csrf" th:content="${_csrf.token}">
    <meta name="_csrf_header" th:content="${_csrf.headerName}">
    <title>포트폴리오 작성</title>
    <link rel="stylesheet" th:href="@{/resources/kr/iotdoor/comn/site/layout/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/resources/kr/iotdoor/comn/site/layout/css/iotdoor.css?v=202404021718}">
</head>
<body class="bg-light">
<div class="container py-5">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
        <div>
            <h1 class="h3 mb-1" th:text="${form.portfolioIdntfNo != null and !#strings.isEmpty(form.portfolioIdntfNo) ? '포트폴리오 수정' : '포트폴리오 등록'}">포트폴리오 등록</h1>
            <p class="text-secondary mb-0">대표이미지는 별도 파일로 저장되고, 본문은 HTML로 저장됩니다.</p>
        </div>
        <div class="d-flex gap-2">
            <a class="btn btn-outline-secondary" th:href="@{/mfuc/portfolio/list.do}">목록</a>
            <a class="btn btn-outline-primary" th:href="@{/mfuc/index.do}">대시보드</a>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <form method="post" enctype="multipart/form-data" th:action="@{/mfuc/portfolio/save.do}" th:object="${form}">
                <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
                <input type="hidden" th:field="*{portfolioIdntfNo}">
                <input type="hidden" th:field="*{thumbnailAtchFileIdntfNo}">

                <div class="mb-4">
                    <label class="form-label fw-semibold" for="title">제목</label>
                    <input class="form-control" id="title" th:field="*{title}" placeholder="포트폴리오 제목을 입력해주세요.">
                    <div class="text-danger small mt-1" th:if="${#fields.hasErrors('title')}" th:errors="*{title}">제목 오류</div>
                </div>

                <div class="mb-4">
                    <label class="form-label fw-semibold" for="thumbnailFile">대표이미지(썸네일)</label>
                    <input class="form-control" type="file" id="thumbnailFile" name="thumbnailFile" accept="image/*">
                    <div class="text-danger small mt-1" th:if="${#fields.hasErrors('thumbnailAtchFileIdntfNo')}" th:errors="*{thumbnailAtchFileIdntfNo}">썸네일 오류</div>
                    <div class="mt-3" th:if="${currentThumbnailUrl != null}">
                        <p class="small text-secondary mb-2">현재 대표이미지</p>
                        <img class="img-fluid rounded border" th:src="${currentThumbnailUrl}" alt="대표이미지 미리보기" style="max-width: 280px;">
                    </div>
                </div>

                <div class="mb-4 p-3 rounded border bg-white">
                    <div class="d-flex flex-column flex-lg-row justify-content-between gap-3">
                        <div>
                            <h2 class="h6 mb-1">본문 이미지 업로드</h2>
                            <p class="text-secondary small mb-0">이미지를 올리면 URL이 발급되고, 버튼으로 본문에 바로 삽입할 수 있습니다.</p>
                        </div>
                        <div class="d-flex flex-column flex-md-row gap-2">
                            <input class="form-control" type="file" id="contentImageFile" accept="image/*">
                            <button class="btn btn-outline-primary" id="uploadContentImageBtn" type="button">본문 이미지 업로드</button>
                        </div>
                    </div>
                    <div class="mt-3" id="contentImageResult" style="display:none;">
                        <div class="input-group">
                            <input class="form-control" type="text" id="contentImageUrl" readonly>
                            <button class="btn btn-outline-secondary" type="button" id="insertContentImageBtn">본문에 삽입</button>
                        </div>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="form-label fw-semibold" for="content">내용</label>
                    <textarea class="form-control" id="content" th:field="*{content}" rows="18" placeholder="HTML 포함 본문을 입력해주세요."></textarea>
                    <div class="form-text">예시: &lt;p&gt;설명&lt;/p&gt; 또는 &lt;img src=&quot;/comn/file/view/...&quot; alt=&quot;&quot;&gt;</div>
                    <div class="text-danger small mt-1" th:if="${#fields.hasErrors('content')}" th:errors="*{content}">내용 오류</div>
                </div>

                <div class="d-flex flex-wrap gap-2">
                    <button class="btn btn-primary px-4" type="submit">저장</button>
                    <a class="btn btn-outline-secondary px-4" th:href="@{/mfuc/portfolio/list.do}">취소</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    (function () {
        function csrf() {
            return {
                token: document.querySelector('meta[name="_csrf"]').getAttribute('content'),
                header: document.querySelector('meta[name="_csrf_header"]').getAttribute('content')
            };
        }

        const uploadButton = document.getElementById('uploadContentImageBtn');
        const insertButton = document.getElementById('insertContentImageBtn');
        const resultBox = document.getElementById('contentImageResult');
        const urlInput = document.getElementById('contentImageUrl');
        const fileInput = document.getElementById('contentImageFile');
        const contentField = document.getElementById('content');

        uploadButton.addEventListener('click', async function () {
            if (!fileInput.files.length) {
                alert('업로드할 이미지를 먼저 선택해주세요.');
                return;
            }

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            formData.append('directory', 'portfolio/content');
            formData.append('description', 'portfolio-content-image');

            const csrfInfo = csrf();
            const response = await fetch('/mfuc/file/upload.do', {
                method: 'POST',
                body: formData,
                headers: {
                    [csrfInfo.header]: csrfInfo.token
                }
            });

            if (!response.ok) {
                alert('본문 이미지 업로드에 실패했습니다.');
                return;
            }

            const payload = await response.json();
            urlInput.value = payload.url;
            resultBox.style.display = 'block';
        });

        insertButton.addEventListener('click', function () {
            if (!urlInput.value) {
                return;
            }
            const imageTag = '<p><img src="' + urlInput.value + '" alt=""></p>';
            const start = contentField.selectionStart || 0;
            const end = contentField.selectionEnd || 0;
            const original = contentField.value;
            contentField.value = original.substring(0, start) + imageTag + original.substring(end);
            contentField.focus();
        });
    })();
</script>
</body>
</html>
