/**
 * 後台預設技師頭像：AJAX 儲存／清除、更新預覽、編輯既有圖。
 */
(function (global) {
    'use strict';

    function showBlockMsg(block, text, ok) {
        var el = block.querySelector('.admin-avatar-msg');
        if (!el) {
            el = document.createElement('p');
            el.className = 'admin-avatar-msg sub';
            el.style.margin = '.35rem 0 .5rem';
            block.insertBefore(el, block.querySelector('form'));
        }
        el.textContent = text || '';
        el.style.color = ok ? 'var(--ok, #0a7)' : 'var(--bad, #c33)';
    }

    function updateCurrentPreview(block, previewUrl) {
        var img = block.querySelector('.admin-avatar-current-img');
        var empty = block.querySelector('.admin-avatar-empty');
        var clearBtn = block.querySelector('.admin-avatar-clear-btn');
        var editBtn = block.querySelector('.admin-avatar-edit-btn');
        var label = block.querySelector('.admin-avatar-current-label');
        if (previewUrl) {
            if (empty) {
                empty.hidden = true;
            }
            if (label) {
                label.style.display = '';
            }
            if (img) {
                img.src = previewUrl;
                img.hidden = false;
                img.style.display = '';
            }
            if (editBtn) {
                editBtn.setAttribute('data-src', previewUrl);
                editBtn.hidden = false;
            }
            if (clearBtn) {
                clearBtn.hidden = false;
            }
        } else {
            if (img) {
                img.hidden = true;
                img.style.display = 'none';
                img.removeAttribute('src');
            }
            if (label) {
                label.style.display = 'none';
            }
            if (empty) {
                empty.hidden = false;
            }
            if (editBtn) {
                editBtn.removeAttribute('data-src');
                editBtn.hidden = true;
            }
            if (clearBtn) {
                clearBtn.hidden = true;
            }
        }
    }

    function initDefaultAvatarAdmin(opts) {
        var genders = opts.genders || ['female', 'male'];
        var apiUrl = opts.apiUrl || 'masseur_avatar_api.php';
        var csrf = opts.csrf || '';
        var editors = {};

        genders.forEach(function (g) {
            var p = 'admin-avatar-' + g;
            var block = document.getElementById(p + '-block');
            var form = document.getElementById(p + '-form');
            var hidden = document.getElementById(p + '-data');
            var clearBtn = document.getElementById(p + '-clear');
            if (!block || !form || !hidden) {
                return;
            }

            if (typeof global.fateInitMasseurPhotoEditor === 'function') {
                editors[g] = global.fateInitMasseurPhotoEditor({
                    fileId: p + '-file',
                    panelId: p + '-panel',
                    cropStageId: p + '-crop-stage',
                    editStageId: p + '-edit-stage',
                    cropCanvasId: p + '-crop-canvas',
                    cropZoomId: p + '-crop-zoom',
                    cropApplyId: p + '-crop-apply',
                    canvasId: p + '-canvas',
                    hiddenId: p + '-data',
                    brushId: p + '-brush',
                    recropId: p + '-recrop',
                    applyId: p + '-apply',
                    resetId: p + '-reset',
                    cancelId: p + '-cancel',
                    cancelEditId: p + '-cancel-edit',
                    previewId: p + '-preview',
                    hintId: p + '-hint',
                    editExistingId: p + '-edit',
                    cropAspect: 'square',
                    existingUrl: (function () {
                        var btn = document.getElementById(p + '-edit');
                        return btn ? (btn.getAttribute('data-src') || '') : '';
                    })(),
                    applyMessage: '已套用，請按「儲存預設頭像」。',
                });
            }

            form.addEventListener('submit', function (e) {
                e.preventDefault();
                if (!hidden.value) {
                    window.alert('請先選擇圖片，完成剪裁並套用相片後再儲存。');
                    return;
                }
                var fd = new FormData();
                fd.append('csrf', csrf);
                fd.append('action', 'save_default_avatar');
                fd.append('gender', g);
                fd.append('photo_data', hidden.value);
                var saveBtn = form.querySelector('button[type="submit"]');
                if (saveBtn) {
                    saveBtn.disabled = true;
                }
                fetch(apiUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
                    .then(function (res) {
                        return res.json().then(function (j) {
                            return { status: res.status, body: j };
                        });
                    })
                    .then(function (r) {
                        if (!r.body || !r.body.ok) {
                            throw new Error((r.body && r.body.error) || '儲存失敗');
                        }
                        showBlockMsg(block, r.body.message || '已儲存。', true);
                        if (r.body.preview_url) {
                            updateCurrentPreview(block, r.body.preview_url);
                            if (editors[g] && typeof editors[g].setExistingUrl === 'function') {
                                editors[g].setExistingUrl(r.body.preview_url);
                            }
                        }
                        hidden.value = '';
                        var preview = document.getElementById(p + '-preview');
                        if (preview) {
                            preview.hidden = true;
                            preview.removeAttribute('src');
                        }
                        var hint = document.getElementById(p + '-hint');
                        if (hint) {
                            hint.textContent = '';
                        }
                    })
                    .catch(function (err) {
                        showBlockMsg(block, err.message || '儲存失敗', false);
                    })
                    .finally(function () {
                        if (saveBtn) {
                            saveBtn.disabled = false;
                        }
                    });
            });

            if (clearBtn) {
                clearBtn.addEventListener('click', function () {
                    var label = clearBtn.getAttribute('data-label') || '此';
                    if (!window.confirm('確定清除' + label + '預設頭像？')) {
                        return;
                    }
                    clearBtn.disabled = true;
                    var fd = new FormData();
                    fd.append('csrf', csrf);
                    fd.append('action', 'clear_default_avatar');
                    fd.append('gender', g);
                    fetch(apiUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
                        .then(function (res) {
                            return res.json().then(function (j) {
                                return { status: res.status, body: j };
                            });
                        })
                        .then(function (r) {
                            if (!r.body || !r.body.ok) {
                                throw new Error((r.body && r.body.error) || '清除失敗');
                            }
                            showBlockMsg(block, r.body.message || '已清除。', true);
                            updateCurrentPreview(block, null);
                            if (editors[g] && typeof editors[g].setExistingUrl === 'function') {
                                editors[g].setExistingUrl('');
                            }
                            if (editors[g] && typeof editors[g].reset === 'function') {
                                editors[g].reset();
                            }
                        })
                        .catch(function (err) {
                            showBlockMsg(block, err.message || '清除失敗', false);
                        })
                        .finally(function () {
                            clearBtn.disabled = false;
                        });
                });
            }
        });
    }

    global.fateInitDefaultAvatarAdmin = initDefaultAvatarAdmin;
})(typeof window !== 'undefined' ? window : this);
