<template>
    <li class="card p-5 mb-2">
        <DictWrite
            v-if="writeStore.isItemActive(item.WRDDICSEQ)"
            @close="writeStore.closeAll();"
            :dataList="cateList"
            @addWord="editWord"
            :NumValue="item.WRDDICSEQ"
            :formValue="item.WRDDICCAT"
            :titleValue="item.WRDDICTTL"
            :contentValue="item.WRDDICCON"
            :isDisabled="userStore.user.role !== 'ROLE_ADMIN'"
            />
        <div v-else>
            <input
                v-if="userStore.user.role == 'ROLE_ADMIN'"
                type="checkbox"
                class="form-check-input admin-chk"
                :name="item.WRDDICSEQ"
                @change="toggleCheck($event)"
            >
            <div class="d-flex align-ite-center">
                <div class="w-100 d-flex align-items-center">
                    <span class="btn btn-primary pe-none">{{ item.category }}</span>
                    <strong class="mx-2 w-75">{{ item.WRDDICTTL }}</strong>
                </div>
            </div>
            <p class="mt-5 dict-content-wrap" v-html="$common.contentToHtml(item.WRDDICCON)"></p>
            <div class="d-flex justify-content-between flex-wrap gap-2 mb-2">
                <div class="d-flex flex-wrap align-items-center mb-50">
                    <div class="avatar avatar-sm me-2">
                        <img
                            class="rounded-circle user-avatar"
                            :src="getProfileImage(item.author.profileImage)"
                            alt="최초 작성자"
                            :style="{ borderColor: item.author.color}"
                            @error="setDefaultImage"
                        />
                    </div>
                    <div>
                        <p class="mb-0 small fw-medium">{{ $common.dateFormatter(item.author.createdAt) }}</p>
                    </div>
                </div>
            </div>
            <div
                v-if="item.author.createdAt !== item.lastEditor.updatedAt"
                class="d-flex justify-content-between flex-wrap gap-2 mb-2"
            >
                <div class="d-flex flex-wrap align-items-center mb-50">
                    <div class="avatar avatar-sm me-2">
                        <img
                            class="rounded-circle user-avatar"
                            :src="getProfileImage(item.lastEditor.profileImage)"
                            alt="최근 작성자"
                            :style="{ borderColor: item.lastEditor.color}"
                            @error="setDefaultImage"
                        />
                    </div>
                    <div>
                        <p class="mb-0 small fw-medium">{{ $common.dateFormatter(item.lastEditor.updatedAt) }}</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="edit-btn">
            <EditBtn ref="writeButton" @click="writeStore.toggleItem(item.WRDDICSEQ)" :isToggleEnabled="true"
            :isActive="writeStore.activeItemId === item.WRDDICSEQ"/>
        </div>
    </li>
</template>

<script setup>
import axios from "@api";
import { useToastStore } from '@s/toastStore';
import { getCurrentInstance, ref } from 'vue';
import EditBtn from '@/components/button/EditBtn.vue';
import $api from '@api';
import DictWrite from './DictWrite.vue';
import { useUserInfoStore } from '@s/useUserInfoStore';
import { useWriteVisibleStore } from '@s/writeVisible';

const writeStore = useWriteVisibleStore();
const writeButton = ref(null);

// 유저 구분
const userStore = useUserInfoStore();

const toastStore = useToastStore();

const { appContext } = getCurrentInstance();
const $common = appContext.config.globalProperties.$common;

// Props
const props = defineProps({
    item: {
        type: Object,
        required: true
    },
    cateList: {
        type: Array,
        required: false,
    }
});

// cateList emit
const emit = defineEmits(['update:cateList','refreshWordList', 'updateChecked']);


// 용어집 수정
const editWord = (data) => {

    if (!data.id) {
        console.error('❌ 수정할 데이터의 ID가 없습니다.');
        toastStore.onToast('수정할 용어의 ID가 필요합니다.', 'e');
        return;
    }

    axios.patch('worddict/updateWord', {
        WRDDICSEQ: data.id,
        WRDDICCAT: data.category,
        WRDDICTTL: data.title,
        WRDDICCON: $common.deltaAsJson(data.content),
    })
    .then((res) => {
        if (res.data.data === 1) {
            toastStore.onToast('용어가 수정되었습니다.', 's');
            writeStore.closeAll();
            if (writeButton.value) {
                writeButton.value.resetButton();
            }
            emit('refreshWordList');
        } else {
            console.warn('⚠️ 서버 응답이 예상과 다릅니다:', res.data);
            toastStore.onToast('용어 수정이 정상적으로 처리되지 않았습니다.', 'e');
        }
    })
    .catch((err) => {
        console.error('❌ 용어 수정 중 오류 발생:', err.response?.data || err.message);
        toastStore.onToast(`용어 수정 실패: ${err.response?.data?.message || '알 수 없는 오류'}`, 'e');
    });
};

const baseUrl = $api.defaults.baseURL.replace(/api\/$/, '');

// 프로필 이미지
const defaultProfile = "/img/icons/icon.png";

const getProfileImage = (profilePath) => {
    return profilePath && profilePath.trim() ? `${baseUrl}upload/img/profile/${profilePath}` : defaultProfile;
};

const setDefaultImage = (event) => {
    event.target.src = defaultProfile;
};


// 체크 상태 변경 시 부모로 전달
const toggleCheck = (event) => {
    emit('updateChecked', event.target.checked, props.item.WRDDICSEQ, event.target.name);
};
</script>

<style scoped>
.avatar {
    cursor: default;
}

.user-avatar {
    border: 3px solid;
    padding: 0.1px;
}

.edit-btn {
    position: absolute;
    right: 0.7rem;
    top: 1.2rem;
}

.admin-chk {
    position: absolute;
    left: -0.5rem;
    top: -0.5rem;
    --bs-form-check-bg: #fff;
}
</style>
