<template>
	<scroll-view class="mine-panel-scroll" scroll-y :show-scrollbar="false">
		<view class="mine-panel-publish" hover-class="mine-panel-publish--press" @tap="onPublishTap">
			<image
				class="mine-panel-publish-icon"
				src="/static/mine/panel/panel-camera.png"
				mode="aspectFit"
			/>
			<text class="mine-panel-publish-txt">{{ $t('user.panelPublishNow') }}</text>
		</view>

		<!-- <view
			v-if="signedIn"
			class="mine-panel-live"
			hover-class="mine-panel-live--press"
			@tap="onLiveBroadcastTap"
		>
			<image
				class="mine-panel-live-icon"
				src="/static/tabbar/live.png"
				mode="aspectFit"
			/>
			<text class="mine-panel-live-txt">{{ $t('mine.actionLive') }}</text>
		</view> -->

		<view class="mine-panel-block">
			<view class="mine-panel-row" hover-class="mine-panel-row--press" @tap.stop="openAccountSecurity">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-account.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.panelAccountSecurity') }}</text>
				</view>
				<text class="mine-panel-chevron">›</text>
			</view>
			<view class="mine-panel-row" hover-class="mine-panel-row--press" @tap="openRealnameEntry">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-identity.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.realnameVerification') }}</text>
				</view>
				<view class="mine-panel-row-tail">
					<text
						v-if="signedIn && realnameBadgeText"
						class="mine-panel-badge"
						:class="{ 'mine-panel-badge--muted': realnameBadgeLoading }"
					>{{ realnameBadgeText }}</text>
					<text class="mine-panel-chevron">›</text>
				</view>
			</view>
			<view class="mine-panel-row mine-panel-row--last" hover-class="mine-panel-row--press" @tap="openRoute('/pages/account/language')">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-language.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.panelLanguage') }}</text>
				</view>
				<text class="mine-panel-chevron">›</text>
			</view>
		</view>

		<view class="mine-panel-block">
			<view class="mine-panel-row" hover-class="mine-panel-row--press" @tap="openRoute('/pages/account/notice')">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-notice.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.panelNewMessage') }}</text>
				</view>
				<text class="mine-panel-chevron">›</text>
			</view>
			<view class="mine-panel-row mine-panel-row--last" hover-class="mine-panel-row--press" @tap="openRoute('/pages/user/settings/general')">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-general.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.panelGeneral') }}</text>
				</view>
				<text class="mine-panel-chevron">›</text>
			</view>
		</view>

		<view class="mine-panel-block">
			<view class="mine-panel-row" hover-class="mine-panel-row--press" @tap="openRoute('/pages/account/complaint')">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-report.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.panelReport') }}</text>
				</view>
				<text class="mine-panel-chevron">›</text>
			</view>
			<view class="mine-panel-row" hover-class="mine-panel-row--press" @tap="openRoute('/pages/account/complaint-lists')">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-myreports.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.myReports') }}</text>
				</view>
				<text class="mine-panel-chevron">›</text>
			</view>
			<view class="mine-panel-row mine-panel-row--last" hover-class="mine-panel-row--press" @tap="openRoute('/pages/account/blocked')">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-blocked.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.blockedList') }}</text>
				</view>
				<text class="mine-panel-chevron">›</text>
			</view>
		</view>

		<view class="mine-panel-block">
			<view class="mine-panel-row" hover-class="mine-panel-row--press" @tap="wipeLocalCache">
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-clear.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.panelClearCache') }}</text>
				</view>
				<view class="mine-panel-row-tail">
					<text class="mine-panel-meta">{{ cacheSizeLabel }}</text>
					<text class="mine-panel-chevron">›</text>
				</view>
			</view>
			<view
				class="mine-panel-row mine-panel-row--last"
				hover-class="mine-panel-row--press"
				@tap="openRoute('/pages/account/about', false, 'pop-in', 200)"
			>
				<view class="mine-panel-row-main">
					<image class="mine-panel-row-icon" src="/static/mine/panel/panel-about.png" mode="aspectFit" />
					<text class="mine-panel-row-label">{{ $t('user.panelAbout') }}</text>
				</view>
				<view class="mine-panel-row-tail">
					<text class="mine-panel-meta">{{ appVersion }}</text>
					<text class="mine-panel-chevron">›</text>
				</view>
			</view>
		</view>

		<view class="mine-panel-block mine-panel-block--tail">
			<view class="mine-panel-row mine-panel-row--logout" hover-class="mine-panel-row--press" @tap="leaveAccount">
				<view class="mine-panel-row-main">
					<text class="mine-panel-logout-glyph">⎋</text>
					<text class="mine-panel-row-label">{{ $t('user.panelLogout') }}</text>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
import { mapState } from 'vuex'
import { buildRestPath } from '@/core/config/api-paths'
import { post } from '@/core/http/http-client'
import {
	normalizeRealnameFlag,
	pullRealnameFlagFromApi,
	realnameBadgeI18nKey,
	shouldOpenRealnameDetail,
	REALNAME_NONE
} from '@/features/mine-panel/realname-bridge'

export default {
	name: 'MineSidePanel',
	props: {
		active: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			cacheSizeLabel: '0 B',
			realnameFlag: null,
			realnameBadgeLoading: false
		}
	},
	computed: {
		...mapState({
			storeUser: (state) => state.user,
			shell: (state) => state.shell
		}),
		signedIn() {
			return !!(this.storeUser && this.storeUser.isLogin)
		},
		appVersion() {
			return (this.shell && this.shell.version) || ''
		},
		realnameBadgeText() {
			if (!this.signedIn) return ''
			if (this.realnameBadgeLoading) return this.$t('user.realnameSyncing')
			if (this.realnameFlag === null || this.realnameFlag === undefined) return ''
			return this.$t(realnameBadgeI18nKey(this.realnameFlag))
		}
	},
	watch: {
		active(val) {
			if (val) this.onPanelOpen()
		},
		'storeUser.isLogin': {
			immediate: true,
			handler(isLogin) {
				if (isLogin) {
					this.syncRealnameBadge()
				} else {
					this.realnameFlag = null
					this.realnameBadgeLoading = false
				}
			}
		}
	},
	created() {
		this._onRealnameSync = () => this.syncRealnameBadge()
		uni.$on('mine-panel-sync-realname', this._onRealnameSync)
	},
	beforeDestroy() {
		if (this._onRealnameSync) {
			uni.$off('mine-panel-sync-realname', this._onRealnameSync)
		}
	},
	methods: {
		onPanelOpen() {
			this.syncRealnameBadge()
			// #ifdef APP-PLUS
			this.refreshCacheLabel()
			// #endif
		},
		closePanel() {
			this.$emit('close')
		},
		onPublishTap() {
			this.closePanel()
			this.$emit('publish')
		},
		onLiveBroadcastTap() {
			this.closePanel()
			if (this.$appKit && !this.$appKit.requireLogin()) return
			uni.navigateTo({
				url: '/pages/live/broadcast',
				fail: () => this.$appKit && this.$appKit.to('/pages/live/broadcast')
			})
		},
		openAccountSecurity() {
			this.closePanel()
			this.$emit('open-security')
		},
		openRoute(url, needAuth = false, anim, delay) {
			this.closePanel()
			if (needAuth) {
				this.$appKit.auth(url)
				return
			}
			const payload = { url }
			if (anim) {
				payload.animationType = anim
				payload.animationDuration = delay != null ? delay : 300
			}
			this.$emit('navigate', payload)
		},
		async syncRealnameBadge() {
			if (!this.signedIn) {
				this.realnameFlag = null
				this.realnameBadgeLoading = false
				return
			}
			this.realnameBadgeLoading = true
			const r = await pullRealnameFlagFromApi()
			this.realnameBadgeLoading = false
			if (r.ok) {
				this.realnameFlag = r.is_real
			} else {
				this.realnameFlag = null
			}
		},
		async openRealnameEntry() {
			if (!this.signedIn) {
				this.closePanel()
				this.$emit('navigate', { url: '/pages/passport/signin?mode=secret' })
				return
			}
			const r = await pullRealnameFlagFromApi()
			if (!r.ok) {
				if (r.reason === 'network') {
					this.$appKit.msg(this.$t('user.realnameNetworkError'))
				} else {
					this.$appKit.msg(this.$t('user.realnameStatusFetchError'))
				}
				return
			}
			const flag = normalizeRealnameFlag(r.is_real)
			this.realnameFlag = flag
			this.closePanel()
			if (flag === REALNAME_NONE) {
				this.$emit('navigate', { url: '/pages/account/realname-add' })
				return
			}
			if (shouldOpenRealnameDetail(flag)) {
				this.$emit('navigate', { url: '/pages/account/realname-info' })
				return
			}
			this.$emit('navigate', { url: '/pages/account/realname-add' })
		},
		refreshCacheLabel() {
			// #ifdef APP-PLUS
			plus.cache.calculate((size) => {
				let sizeCache = parseInt(size, 10)
				if (sizeCache === 0) {
					this.cacheSizeLabel = '0 B'
				} else if (sizeCache < 1024) {
					this.cacheSizeLabel = `${sizeCache} B`
				} else if (sizeCache < 1048576) {
					this.cacheSizeLabel = `${(sizeCache / 1024).toFixed(2)} KB`
				} else if (sizeCache < 1073741824) {
					this.cacheSizeLabel = `${(sizeCache / 1048576).toFixed(2)} MB`
				} else {
					this.cacheSizeLabel = `${(sizeCache / 1073741824).toFixed(2)} GB`
				}
			})
			// #endif
		},
		wipeLocalCache() {
			// #ifndef APP-PLUS
			this.$appKit.msg(this.$t('user.panelNoCache'))
			// #endif
			// #ifdef APP-PLUS
			uni.showModal({
				title: this.$t('user.panelPrompt'),
				content: this.$t('user.panelConfirmClearCache'),
				success: (res) => {
					if (!res.confirm) return
					if (plus.os.name === 'Android') {
						const main = plus.android.runtimeMainActivity()
						const sdRoot = main.getCacheDir()
						const files = plus.android.invoke(sdRoot, 'listFiles')
						const len = files.length
						for (let i = 0; i < len; i++) {
							const filePath = `${files[i]}`
							plus.io.resolveLocalFileSystemURL(
								filePath,
								(entry) => {
									if (entry.isDirectory) {
										entry.removeRecursively(() => {
											this.$appKit.msg(this.$t('user.panelCacheCleared'))
											this.refreshCacheLabel()
										})
									} else {
										entry.remove()
									}
								},
								() => {}
							)
						}
					} else {
						plus.cache.clear(() => {
							this.$appKit.msg(this.$t('user.panelCacheCleared'))
							this.refreshCacheLabel()
						})
					}
				}
			})
			// #endif
		},
		async leaveAccount() {
			if (!this.signedIn) {
				this.closePanel()
				this.$appKit.to('/pages/passport/signin')
				return
			}
			uni.showModal({
				title: this.$t('user.panelPrompt'),
				content: this.$t('user.panelLogoutConfirm'),
				success: async (res) => {
					if (!res.confirm) return
					try {
						await post(buildRestPath('user/logout'))
					} catch (_) {}
					try {
						await this.$store.dispatch('im/pause', true)
					} catch (_) {}
					await this.$store.dispatch('clearSession')
					this.$appKit.msg(this.$t('user.panelLogoutOk'))
					this.closePanel()
					uni.switchTab({
						url: '/pages/mine/index',
						fail: () => {
							uni.reLaunch({ url: '/pages/mine/index' })
						}
					})
				}
			})
		}
	}
}
</script>

<style scoped>
.mine-panel-scroll {
	width: 100%;
	height: 100%;
	min-height: 100%;
	box-sizing: border-box;
	padding: 16rpx 20rpx calc(24rpx + env(safe-area-inset-bottom));
}

.mine-panel-publish {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 96rpx;
	margin: 0 8rpx 28rpx;
	border-radius: 48rpx;
	background: linear-gradient(90deg, #5ce1e6 0%, #4a8cff 100%);
	box-shadow: 0 8rpx 24rpx rgba(74, 140, 255, 0.28);
	transition: transform 0.15s ease, opacity 0.15s ease;
}

.mine-panel-publish--press {
	transform: scale(0.98);
	opacity: 0.92;
}

.mine-panel-publish-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 12rpx;
}

.mine-panel-publish-txt {
	font-size: 32rpx;
	font-weight: 600;
	color: #ffffff;
}

.mine-panel-live {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 88rpx;
	margin: 0 8rpx 28rpx;
	border-radius: 44rpx;
	background-color: #ffffff;
	border: 2rpx solid rgba(74, 140, 255, 0.35);
	box-shadow: 0 6rpx 20rpx rgba(74, 140, 255, 0.1);
	transition: transform 0.15s ease, opacity 0.15s ease;
}

.mine-panel-live--press {
	transform: scale(0.98);
	opacity: 0.92;
}

.mine-panel-live-icon {
	width: 36rpx;
	height: 36rpx;
	margin-right: 12rpx;
}

.mine-panel-live-txt {
	font-size: 30rpx;
	font-weight: 600;
	color: #4a8cff;
}

.mine-panel-block {
	margin-bottom: 20rpx;
	background: #ffffff;
	border-radius: 24rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 16rpx rgba(15, 23, 42, 0.04);
}

.mine-panel-block--tail {
	margin-bottom: 0;
}

.mine-panel-row {
	min-height: 108rpx;
	padding: 0 24rpx 0 28rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-bottom: 1rpx solid #eef0f3;
	transition: background-color 0.15s ease;
}

.mine-panel-row--press {
	background-color: #f3f5f9;
}

.mine-panel-row--last {
	border-bottom: none;
}

.mine-panel-row--logout {
	border-bottom: none;
}

.mine-panel-row--logout .mine-panel-row-label {
	color: #dc2626;
}

.mine-panel-row-main {
	display: flex;
	align-items: center;
	flex: 1;
	min-width: 0;
}

.mine-panel-row-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 20rpx;
	flex-shrink: 0;
}

.mine-panel-row-label {
	font-size: 30rpx;
	color: #111827;
	font-weight: 500;
}

.mine-panel-row-tail {
	display: flex;
	align-items: center;
	flex-shrink: 0;
	margin-left: 12rpx;
}

.mine-panel-chevron {
	font-size: 36rpx;
	color: #c4c9d4;
	line-height: 1;
	margin-left: 8rpx;
}

.mine-panel-badge {
	font-size: 22rpx;
	line-height: 1.2;
	padding: 8rpx 18rpx;
	border-radius: 999rpx;
	background: rgba(62, 214, 86, 0.12);
	color: #2fb04a;
	max-width: 200rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.mine-panel-badge--muted {
	background: #eef0f3;
	color: #6b7280;
}

.mine-panel-meta {
	font-size: 24rpx;
	color: #9ca3af;
}

.mine-panel-logout-glyph {
	width: 40rpx;
	margin-right: 20rpx;
	flex-shrink: 0;
	font-size: 34rpx;
	color: #6b7280;
	text-align: center;
	line-height: 1;
}
</style>
