(function ($) {
    'use strict';

    if (!$ || !$.fn || !$.fn.summernote) {
        return;
    }

    var editorCfg = window.FATE_RICH_EDITOR || {};

    var defaultToolbar = [
        ['style', ['bold', 'italic', 'underline', 'clear']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['table', ['table']],
        ['insert', ['link', 'picture']],
        ['view', ['fullscreen']]
    ];

    function uploadRichImage(file, $editor) {
        if (!editorCfg.uploadUrl || !editorCfg.csrf) {
            window.alert('圖片上傳未設定。');
            return;
        }
        if (!file || !file.type || file.type.indexOf('image/') !== 0) {
            window.alert('請選擇圖片檔案。');
            return;
        }

        var formData = new FormData();
        formData.append('csrf', editorCfg.csrf);
        formData.append('image', file);

        $.ajax({
            url: editorCfg.uploadUrl,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json'
        }).done(function (resp) {
            if (resp && resp.ok && resp.url) {
                $editor.summernote('insertImage', resp.url);
                return;
            }
            window.alert((resp && resp.error) ? resp.error : '圖片上傳失敗。');
        }).fail(function (xhr) {
            var msg = '圖片上傳失敗。';
            try {
                var json = xhr.responseJSON;
                if (json && json.error) {
                    msg = json.error;
                }
            } catch (e) {
                /* ignore */
            }
            window.alert(msg);
        });
    }

    function initRichEditor(el) {
        if (!el || el.getAttribute('data-fate-rich-editor-ready') === '1') {
            return;
        }
        var $el = $(el);
        if ($el.next('.note-editor').length) {
            el.setAttribute('data-fate-rich-editor-ready', '1');
            return;
        }

        var placeholder = el.getAttribute('placeholder') || '';
        var height = parseInt(el.getAttribute('data-fate-rich-editor-height') || '180', 10);

        $el.summernote({
            lang: 'zh-TW',
            height: height,
            placeholder: placeholder,
            disableDragAndDrop: false,
            toolbar: defaultToolbar,
            callbacks: {
                onInit: function () {
                    var noteEditor = $el.next('.note-editor');
                    if (noteEditor.length) {
                        noteEditor.addClass('fate-rich-summernote');
                    }
                },
                onImageUpload: function (files) {
                    var $editor = $(this);
                    for (var i = 0; i < files.length; i++) {
                        uploadRichImage(files[i], $editor);
                    }
                },
                onChange: function () {
                    syncPaidToggleForEditor(el);
                }
            }
        });

        el.setAttribute('data-fate-rich-editor-ready', '1');

        var form = el.closest('form');
        if (form && !form.getAttribute('data-fate-rich-editor-bound')) {
            form.setAttribute('data-fate-rich-editor-bound', '1');
            form.addEventListener('submit', function () {
                $(form).find('[data-fate-rich-editor]').each(function () {
                    var $ta = $(this);
                    if ($ta.next('.note-editor').length) {
                        $ta.val($ta.summernote('code'));
                    }
                });
            });
        }
    }

    function plainTextLengthFromEditor(el) {
        var $el = $(el);
        var html = '';
        if ($el.next('.note-editor').length) {
            html = $el.summernote('code') || '';
        } else {
            html = el.value || '';
        }
        var tmp = document.createElement('div');
        tmp.innerHTML = html;
        var text = (tmp.textContent || tmp.innerText || '').replace(/\s+/g, ' ').trim();
        return text.length;
    }

    function syncPaidToggleForEditor(textarea) {
        var form = textarea.closest('form');
        if (!form) {
            return;
        }
        var wrap = form.querySelector('.masseur-review-paid-fields');
        if (!wrap) {
            return;
        }
        var toggle = wrap.querySelector('.masseur-review-paid-fields__toggle');
        if (!toggle) {
            return;
        }
        var minBody = parseInt(wrap.getAttribute('data-min-body-chars') || '0', 10);
        if (minBody <= 0) {
            return;
        }
        var len = plainTextLengthFromEditor(textarea);
        var hint = wrap.querySelector('.masseur-review-paid-fields__hint');
        if (len < minBody) {
            toggle.disabled = true;
            toggle.checked = false;
            if (hint) {
                hint.textContent = '正文至少 ' + minBody.toLocaleString() + ' 字才可勾選付費（目前 ' + len.toLocaleString() + ' 字）。';
            }
        } else {
            toggle.disabled = false;
            if (hint) {
                hint.textContent = '正文至少 ' + minBody.toLocaleString() + ' 字才可勾選付費。';
            }
        }
        var opts = wrap.querySelector('.masseur-review-paid-fields__opts');
        if (opts) {
            opts.hidden = !toggle.checked;
            opts.querySelectorAll('input, select, textarea').forEach(function (el) {
                if (el !== toggle) {
                    el.disabled = !toggle.checked;
                }
            });
        }
    }

    document.querySelectorAll('[data-fate-rich-editor]').forEach(function (el) {
        var details = el.closest('details');
        if (!details || details.open) {
            initRichEditor(el);
            syncPaidToggleForEditor(el);
        }
    });

    document.querySelectorAll('details.masseur-reviews-fold').forEach(function (details) {
        details.addEventListener('toggle', function () {
            if (!details.open) {
                return;
            }
            details.querySelectorAll('[data-fate-rich-editor]').forEach(function (ta) {
                initRichEditor(ta);
                syncPaidToggleForEditor(ta);
            });
        });
    });

    document.querySelectorAll('.masseur-review-paid-fields').forEach(function (wrap) {
        var toggle = wrap.querySelector('.masseur-review-paid-fields__toggle');
        var opts = wrap.querySelector('.masseur-review-paid-fields__opts');
        if (!toggle || !opts) {
            return;
        }
        function syncPaidOpts() {
            opts.hidden = !toggle.checked;
            opts.querySelectorAll('input, select, textarea').forEach(function (el) {
                if (el !== toggle) {
                    el.disabled = !toggle.checked;
                }
            });
        }
        toggle.addEventListener('change', syncPaidOpts);
        syncPaidOpts();
    });
}(window.jQuery));
