/****************************************************************************
 * Quill 에디터 인스턴스
 ****************************************************************************/
let quill;

/****************************************************************************
 * Quill Image blot - data: URL (base64) 허용
 ****************************************************************************/
const QuillImage = Quill.import('formats/image');
const originalSanitize = QuillImage.sanitize;
QuillImage.sanitize = function (url) {
    if (url && url.startsWith('data:')) {
        return '';
    }
    return originalSanitize.call(this, url);
};

/****************************************************************************
 * Quill 에디터 초기화
 ****************************************************************************/
function fn_initQuillEditor() {
    quill = new Quill('#quillEditor', {
        theme: 'snow',
        placeholder: '내용을 입력해주세요.',
        modules: {
            toolbar: {
                container: [
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    [{ 'font': [] }],
                    [{ 'size': ['small', false, 'large', 'huge'] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'script': 'sub' }, { 'script': 'super' }],
                    [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'list': 'check' }],
                    [{ 'indent': '-1' }, { 'indent': '+1' }],
                    [{ 'direction': 'rtl' }],
                    [{ 'align': [] }],
                    ['blockquote', 'code-block'],
                    ['link', 'image', 'video', 'formula'],
                    ['clean']
                ],
                handlers: {
                    image: imageHandler
                }
            }
        }
    });

    quill.root.addEventListener('paste', function (e) {
        try {
            console.log("[Paste Event] Triggered");
            let clipboardData = e.clipboardData || window.clipboardData || (e.originalEvent && e.originalEvent.clipboardData);
            console.log("[Paste Event] clipboardData:", clipboardData);
            if (!clipboardData || !clipboardData.items) {
                console.warn("[Paste Event] No clipboardData or items found");
                return;
            }

            let items = clipboardData.items;
            console.log("[Paste Event] items length:", items.length);
            for (let i = 0; i < items.length; i++) {
                let item = items[i];
                console.log(`[Paste Event] item[${i}] kind: ${item.kind}, type: ${item.type}`);
                if (item.kind === 'file' && item.type.match('^image/')) {
                    console.log(`[Paste Event] Image file detected. Prevent default.`);
                    e.preventDefault();
                    e.stopPropagation();

                    let file = item.getAsFile();
                    console.log(`[Paste Event] getAsFile() result:`, file);
                    if (file) {
                        if (!file.name || !file.name.includes('.')) {
                            let ext = 'png';
                            if (file.type === 'image/jpeg') ext = 'jpg';
                            else if (file.type === 'image/gif') ext = 'gif';
                            file = new File([file], "clipboard_image." + ext, { type: file.type });
                            console.log(`[Paste Event] Renamed missing file info:`, file.name);
                        }
                        console.log(`[Paste Event] Call fn_uploadImageAndInsertToQuill() for:`, file.name);
                        fn_uploadImageAndInsertToQuill(file);
                    } else {
                        console.error("[Paste Event] getAsFile() returned null.");
                    }
                }
            }
        } catch (err) {
            console.error("[Paste Event] Error parsing paste logic:", err);
        }
    }, true);

    quill.root.addEventListener('drop', function (e) {
        try {
            console.log("[Drop Event] Triggered");
            if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) {
                let hasImage = false;
                console.log("[Drop Event] files length:", e.dataTransfer.files.length);
                for (let i = 0; i < e.dataTransfer.files.length; i++) {
                    let file = e.dataTransfer.files[i];
                    console.log(`[Drop Event] file[${i}] type: ${file.type}`);
                    if (file.type.match('^image/')) {
                        console.log(`[Drop Event] Image file detected. Prevent default.`);
                        hasImage = true;
                        e.preventDefault();
                        e.stopPropagation();
                        fn_uploadImageAndInsertToQuill(file);
                    }
                }
            } else {
                console.log("[Drop Event] No files found in drop event");
            }
        } catch (err) {
            console.error("[Drop Event] Error parsing drop logic:", err);
        }
    }, true);
}
function imageHandler() {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();

    input.onchange = async () => {
        const file = input.files[0];
        fn_uploadImageAndInsertToQuill(file);
    };
}

function fn_uploadImageAndInsertToQuill(file) {
    if (!file) {
        console.error("[Upload] file is undefined or null");
        return;
    }
    console.log("[Upload] fn_uploadImageAndInsertToQuill Start. File name:", file.name, "size:", file.size);

    const formData = new FormData();
    formData.append('file', file);
    formData.append("menuClass", menuClass);

    $.ajax({
        url: '/procedureReview/putProcedureReviewFile.do',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (res) {
            if (typeof res === 'string') {
                try { res = JSON.parse(res); } catch (e) { }
            }
            console.log("[Upload] API Success response:", res);
            if (res.msgCode == 0 || res.msgCode === '0') {
                let range = quill.getSelection(true);
                let index = range ? range.index : quill.getLength();
                console.log(`[Upload] Inserting image at index = ${index}, path = ${res.rows.filePath}`);
                quill.insertEmbed(index, 'image', res.rows.filePath);
            } else {
                console.error("[Upload] API logic error msgDesc:", res.msgDesc);
                modalEvent.danger("업로드 오류", res.msgDesc);
            }
        },
        error: function (xhr, status, error) {
            console.error("[Upload] AJAX HTTP error. status:", status, "error:", error, "responseText:", xhr.responseText);
            modalEvent.danger("업로드 오류", "이미지 업로드 중 오류가 발생했습니다.");
        }
    });
}

/****************************************************************************
 * Quill 콘텐츠를 Delta JSON 문자열로 반환 (저장용)
 ****************************************************************************/
function fn_getQuillContentForSave() {
    return JSON.stringify(quill.getContents());
}

/****************************************************************************
 * 저장된 콘텐츠를 Quill에 로드 (Delta JSON / 레거시 HTML 호환)
 ****************************************************************************/
function fn_loadQuillContent(content) {
    if (!content) return;

    if (typeof content === 'object') {
        if (Array.isArray(content.ops)) quill.setContents(content.ops);
        else if (Array.isArray(content)) quill.setContents(content);
        return;
    }

    try {
        if (typeof content === 'string') {
            // base64인지 판별해 디코딩 시도 (기존 데이터와 새 데이터 호환을 위해)
            const isBase64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/.test(content);
            if (isBase64 && content.length > 0 && !content.trim().startsWith('{') && !content.trim().startsWith('[')) {
                try {
                    content = decodeURIComponent(escape(atob(content)));
                } catch (e) {
                    // base64 디코딩 실패면 그냥 넘어감
                }
            }

            if (content.trim().startsWith('{') || content.trim().startsWith('[')) {
                let parsed = JSON.parse(content);
                if (typeof parsed === 'string') {
                    parsed = JSON.parse(parsed);
                }

                if (typeof parsed === 'object' && parsed !== null && Array.isArray(parsed.ops)) {
                    quill.setContents(parsed.ops);
                    return;
                } else if (Array.isArray(parsed)) {
                    quill.setContents(parsed);
                    return;
                }
            }
        }
    } catch (e) {
        console.warn("Quill Delta Parsing Failed - Fallback to HTML : ", e);
    }

    quill.clipboard.dangerouslyPasteHTML(content);
}

/****************************************************************************
 * 시술후기 상세 조회
 ****************************************************************************/
function fn_selectProcedureReview() {
    if (true != fn_emptyCheck(muProcedureReviewId)) {
        modalEvent.warning("수정", "시술후기 정보가 없습니다.");
        return;
    }
    let paramData = {
        "menuClass": menuClass,
        "muProcedureReviewId": muProcedureReviewId
    };

    $.ajax({
        url: encodeURI('/procedureReview/getProcedureReview.do'),
        data: JSON.stringify(paramData),
        dataType: "json",
        contentType: "application/json",
        type: 'POST',
        async: true,
        success: function (data) {
            if ('0' == data.msgCode) {
                if (data.rows) {
                    let photoData = data.rows;
                    $("#categoryDivCd").val(photoData.categoryDivCd);
                    $("#title").val(photoData.title);
                    fn_loadQuillContent(photoData.content);
                    $("#hashtag").val(photoData.hashtag);
                } else {
                    modalEvent.warning("수정", "조회된 시술후기 데이터가 없습니다.");
                }
            } else {
                alert("수정 오류: " + data.msgDesc);
            }
        },
        error: function (xhr, status, error) {
            alert("수정 오류: 수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        }
    });
}

/****************************************************************************
 * 시술후기 수정
 ****************************************************************************/
function fn_updateProcedureReview() {
    if ("Y" != updateUseYn) {
        modalEvent.warning("", "수정 권한이 없습니다.");
        return false;
    }
    let title = $("#title").val();
    let categoryDivCd = $("#categoryDivCd").val();
    let content = fn_getQuillContentForSave();
    let hashtag = $("#hashtag").val();

    // Quill 에디터 빈 값 체크
    let quillText = quill.getText().trim();

    if (true != fn_emptyCheck(title)) {
        modalEvent.warning("수정", "제목을 입력하세요.");
        return;
    }
    if (!quillText || quillText.length === 0) {
        modalEvent.warning("수정", "내용을 입력하세요.");
        return;
    }
    if (true != fn_emptyCheck(hashtag)) {
        modalEvent.warning("수정", "해시태그를 입력하세요.");
        return;
    }

    modalEvent.info("수정", "시술후기 정보를 수정하시겠습니까?", function () {
        let encodedContent = btoa(unescape(encodeURIComponent(content)));
        let paramData = {
            "menuClass": menuClass,
            "categoryDivCd": categoryDivCd,
            "title": title,
            "content": encodedContent,
            "isEncoded": "Y",
            "hashtag": hashtag,
            "muProcedureReviewId": muProcedureReviewId
        };

        $.ajax({
            url: encodeURI('/procedureReview/modProcedureReview.do'),
            data: JSON.stringify(paramData),
            dataType: "json",
            contentType: "application/json",
            type: 'POST',
            async: true,
            success: function (data) {
                if ('0' == data.msgCode) {
                    modalEvent.success("수정 성공", data.msgDesc, function () {
                        fn_selectListProcedureReviewIntro();
                    });
                }
                else {
                    modalEvent.danger("수정 오류", data.msgDesc);
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            }
        });
    });
}

/****************************************************************************
 * 리스트 화면으로 이동
 ****************************************************************************/
function fn_selectListProcedureReviewIntro() {
    if ("Y" == selectUseYn) {
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += "&categoryDivCd=" + categoryDivCdQuery;
        pagingParam += "&title=" + titleQuery;
        fn_leftFormAction("/procedureReview/moveProcedureReviewList.do" + pagingParam);
    } else {
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }
}

/****************************************************************************
 * 도움말 모달
 ****************************************************************************/
function fn_initHelpModal() {
    $('#btnHelp').on('click', function () {
        $('#helpModal').addClass('active');
    });
    $('#helpModalClose').on('click', function () {
        $('#helpModal').removeClass('active');
    });
    $('#helpModal').on('click', function (e) {
        if (e.target === this) {
            $(this).removeClass('active');
        }
    });
}

/****************************************************************************
 * 미리보기 모달
 ****************************************************************************/
function fn_initPreviewModal() {
    $('#previewModalClose').on('click', function () {
        $('#previewModal').removeClass('active');
    });
    $('#previewModal').on('click', function (e) {
        if (e.target === this) {
            $(this).removeClass('active');
        }
    });
}

function fn_showPreview() {
    let title = $("#title").val();
    let content = quill.root.innerHTML;
    let hashtag = $("#hashtag").val();

    // 미리보기 데이터 설정
    $('#previewTitle').text(title || '(제목 없음)');
    $('#previewContent').html(content);

    if (hashtag) {
        let tags = hashtag.split(/\s+/).map(function (tag) {
            tag = tag.trim();
            if (tag && !tag.startsWith('#')) tag = '#' + tag;
            return tag;
        }).filter(function (tag) { return tag; });
        $('#previewHashtag').html(tags.join('&nbsp;&nbsp;'));
        $('#previewHashtagArea').show();
    } else {
        $('#previewHashtagArea').hide();
    }

    $('#previewModal').addClass('active');
}

/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit() {
    fn_initQuillEditor();
    fn_initHelpModal();
    fn_initPreviewModal();
    fn_selectProcedureReview();
}

/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent() {
    $('.btnCancle').on("click", function () {
        fn_selectListProcedureReviewIntro();
    });
    $('.btnSave').on("click", function () {
        fn_updateProcedureReview();
    });
    $('.btnPreview').on("click", function () {
        fn_showPreview();
    });
}

$(function () {
    fn_pageInit();
    fn_pageEvent();
});
