<template>
	<view class="search-page">
		<view class="search-hd" :style="{ paddingTop: (statusBar + 12) + 'px' }">
			<view class="search-hd-row">
				<view class="search-back-btn" @tap="goBack">
					<text class="search-back-icon">←</text>
				</view>
				<view class="search-input-wrap">
					<text class="search-input-icon">🔍</text>
					<input
						class="search-input"
						type="text"
						maxlength="32"
						confirm-type="search"
						:focus="inputFocus"
						:value="inputValue"
						:placeholder="copy.placeholder"
						placeholder-class="search-input-ph"
						@input="onInput"
						@confirm="onConfirm"
					/>
					<view v-if="inputValue" class="search-clear" @tap="clearInput">
						<text class="search-clear-icon">×</text>
					</view>
				</view>
			</view>
		</view>

		<scroll-view scroll-y class="search-scroll" :style="{ height: scrollHeight + 'px' }">
			<view class="search-body" :style="{ paddingBottom: safeBottom + 'px' }">
				<!-- 联想结果 -->
				<view v-if="showSuggest" class="search-suggest">
					<view
						v-for="(item, index) in suggestKeywords"
						:key="'kw-' + index"
						class="search-suggest-item"
						@tap="goResult(item.keywords)"
					>
						<text class="search-suggest-icon">🔍</text>
						<text class="search-suggest-text">{{ item.keywords }}</text>
					</view>
					<view
						v-for="item in suggestCategories"
						:key="'cat-' + item.id"
						class="search-suggest-item"
						@tap="goResult(item.name)"
					>
						<text class="search-suggest-icon">📁</text>
						<text class="search-suggest-text">{{ item.name }}</text>
						<text class="search-suggest-tag">{{ copy.categoryTag }}</text>
					</view>
					<view v-if="!suggestKeywords.length && !suggestCategories.length" class="search-empty">
						<text class="search-empty-text">{{ copy.noSuggest }}</text>
					</view>
				</view>

				<!-- 历史 + 热门 -->
				<view v-else>
					<view v-if="historyList.length" class="search-block">
						<view class="search-block-hd">
							<text class="search-block-title">{{ copy.history }}</text>
							<view class="search-block-action" @tap="clearHistory">
								<text class="search-block-action-icon">🗑</text>
							</view>
						</view>
						<view class="search-chips">
							<view
								v-for="(item, index) in historyList"
								:key="'h-' + index"
								class="search-chip"
								@tap="goResult(item.keywords)"
							>
								<text class="search-chip-text">{{ item.keywords }}</text>
							</view>
						</view>
					</view>

					<view class="search-block">
						<view class="search-block-hd">
							<text class="search-block-title">{{ copy.hot }}</text>
							<text class="search-block-fire">🔥</text>
						</view>
						<view class="search-chips">
							<view
								v-for="(item, index) in hotList"
								:key="item.id || index"
								class="search-chip"
								:class="{ 'search-chip--hot': item.flag === 'hot' }"
								@tap="goResult(item.keywords)"
							>
								<text class="search-chip-text">{{ item.keywords }}</text>
								<text v-if="item.flag === 'hot'" class="search-chip-badge">{{ copy.hotBadge }}</text>
							</view>
						</view>
						<view v-if="!hotList.length && !hotLoading" class="search-empty">
							<text class="search-empty-text">{{ copy.noHot }}</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import {
	fetchHotSearchList,
	fetchSearchSuggestions,
	recordSearchKeyword
} from '@/features/search/search-gateway'
import {
	readSearchHistory,
	pushSearchHistory,
	clearSearchHistory
} from '@/features/search/search-history'

export default {
	data() {
		return {
			statusBar: 0,
			safeBottom: 0,
			scrollHeight: 600,
			inputFocus: true,
			inputValue: '',
			presetKeyword: '',
			historyList: [],
			hotList: [],
			hotLoading: false,
			showSuggest: false,
			suggestKeywords: [],
			suggestCategories: [],
			suggestTimer: null,
			searchType: 'find'
		}
	},
	computed: {
		copy() {
			const t = this.$t.bind(this)
			return {
				placeholder: t('search.placeholder'),
				categoryTag: t('search.categoryTag'),
				noSuggest: t('search.noSuggest'),
				history: t('search.history'),
				hot: t('search.hot'),
				hotBadge: t('search.hotBadge'),
				noHot: t('search.noHot'),
				enterKeyword: t('search.enterKeyword'),
				clearHistoryTitle: t('search.clearHistoryTitle'),
				clearHistoryContent: t('search.clearHistoryContent'),
				shopSearchDev: t('search.shopSearchDev')
			}
		}
	},
	onLoad(query) {
		if (query && query.keywords) {
			this.presetKeyword = decodeURIComponent(query.keywords)
			this.inputValue = this.presetKeyword
		}
		if (query && query.type) {
			this.searchType = query.type
		}
		this.initLayout()
		this.historyList = readSearchHistory()
		this.loadHot()
	},
	onReady() {
		this.pagesNum = getCurrentPages().length
	},
	onUnload() {
		if (this.suggestTimer) clearTimeout(this.suggestTimer)
	},
	methods: {
		initLayout() {
			try {
				const info = uni.getSystemInfoSync()
				this.statusBar = info.statusBarHeight || 0
				this.safeBottom = (info.safeAreaInsets && info.safeAreaInsets.bottom) || 0
				const navH = this.statusBar + uni.upx2px(100)
				this.scrollHeight = (info.windowHeight || 667) - navH
			} catch (_) {}
		},
		goBack() {
			uni.navigateBack({
				fail: () => uni.switchTab({ url: '/pages/index/index' })
			})
		},
		async loadHot() {
			this.hotLoading = true
			try {
				this.hotList = await fetchHotSearchList()
			} finally {
				this.hotLoading = false
			}
		},
		onInput(e) {
			const value = (e.detail && e.detail.value) || ''
			this.inputValue = value
			if (!value.trim()) {
				this.showSuggest = false
				this.suggestKeywords = []
				this.suggestCategories = []
				return
			}
			if (this.suggestTimer) clearTimeout(this.suggestTimer)
			this.suggestTimer = setTimeout(() => this.loadSuggest(value.trim()), 280)
		},
		async loadSuggest(keyword) {
			try {
				const pack = await fetchSearchSuggestions(keyword)
				this.suggestKeywords = pack.searchList || []
				this.suggestCategories = this.searchType === 'find' ? [] : (pack.categoryList || [])
				this.showSuggest =
					this.suggestKeywords.length > 0 || this.suggestCategories.length > 0
			} catch (_) {
				this.suggestKeywords = []
				this.suggestCategories = []
				this.showSuggest = false
			}
		},
		clearInput() {
			this.inputValue = ''
			this.showSuggest = false
			this.suggestKeywords = []
			this.suggestCategories = []
		},
		onConfirm(e) {
			const value = ((e.detail && e.detail.value) || this.inputValue || '').trim()
			if (!value) {
				if (this.presetKeyword) {
					this.goResult(this.presetKeyword)
					return
				}
				this.$appKit && this.$appKit.msg(this.copy.enterKeyword)
				return
			}
			uni.hideKeyboard()
			this.goResult(value)
		},
		clearHistory() {
			uni.showModal({
				title: this.copy.clearHistoryTitle,
				content: this.copy.clearHistoryContent,
				success: (res) => {
					if (res.confirm) {
						this.historyList = clearSearchHistory()
					}
				}
			})
		},
		async goResult(keywords) {
			const text = String(keywords || '').trim()
			if (!text) return
			recordSearchKeyword(text)
			this.historyList = pushSearchHistory(text)
			this.loadHot()
			if (this.searchType === 'find') {
				uni.navigateTo({
					url: `/pages/search/result?search=${encodeURIComponent(text)}`
				})
				return
			}
			this.$appKit && this.$appKit.msg(this.copy.shopSearchDev)
		}
	}
}
</script>

<style scoped>
.search-page {
	min-height: 100vh;
	background-color: #eef3fb;
}

.search-hd {
	padding-left: 32rpx;
	padding-right: 32rpx;
	padding-bottom: 20rpx;
}

.search-hd-row {
	display: flex;
	flex-direction: row;
	align-items: center;
}

.search-back-btn {
	width: 72rpx;
	height: 72rpx;
	border-radius: 20rpx;
	background-color: #ffffff;
	box-shadow: 0 6rpx 20rpx rgba(74, 140, 255, 0.12);
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
	margin-right: 20rpx;
}

.search-back-icon {
	font-size: 36rpx;
	color: #4a8cff;
	line-height: 1;
}

.search-input-wrap {
	flex: 1;
	min-width: 0;
	height: 72rpx;
	border-radius: 20rpx;
	background-color: #ffffff;
	box-shadow: 0 6rpx 20rpx rgba(74, 140, 255, 0.1);
	display: flex;
	flex-direction: row;
	align-items: center;
	padding: 0 20rpx;
	box-sizing: border-box;
}

.search-input-icon {
	font-size: 28rpx;
	margin-right: 12rpx;
	opacity: 0.7;
	flex-shrink: 0;
}

.search-input {
	flex: 1;
	min-width: 0;
	font-size: 28rpx;
	color: #1a1d29;
	height: 72rpx;
	line-height: 72rpx;
}

.search-input-ph {
	color: #8a8d9e;
	font-size: 26rpx;
}

.search-clear {
	width: 44rpx;
	height: 44rpx;
	border-radius: 22rpx;
	background-color: #eef3fb;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.search-clear-icon {
	font-size: 32rpx;
	color: #8a8d9e;
	line-height: 1;
}

.search-body {
	padding: 8rpx 32rpx 32rpx;
	box-sizing: border-box;
}

.search-block {
	margin-bottom: 36rpx;
}

.search-block-hd {
	display: flex;
	flex-direction: row;
	align-items: center;
	margin-bottom: 20rpx;
}

.search-block-title {
	font-size: 30rpx;
	font-weight: 700;
	color: #4a8cff;
	flex: 1;
}

.search-block-fire {
	font-size: 28rpx;
}

.search-block-action {
	width: 56rpx;
	height: 56rpx;
	border-radius: 16rpx;
	background-color: #ffffff;
	box-shadow: 0 4rpx 16rpx rgba(74, 140, 255, 0.1);
	display: flex;
	align-items: center;
	justify-content: center;
}

.search-block-action-icon {
	font-size: 26rpx;
}

.search-chips {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
}

.search-chip {
	display: flex;
	flex-direction: row;
	align-items: center;
	padding: 14rpx 24rpx;
	margin-right: 16rpx;
	margin-bottom: 16rpx;
	border-radius: 999rpx;
	background-color: #ffffff;
	box-shadow: 0 4rpx 16rpx rgba(74, 140, 255, 0.08);
	max-width: 100%;
	box-sizing: border-box;
}

.search-chip--hot {
	background: linear-gradient(135deg, rgba(74, 140, 255, 0.12) 0%, rgba(110, 200, 255, 0.12) 100%);
}

.search-chip-text {
	font-size: 26rpx;
	color: #4a4d5e;
	max-width: 420rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.search-chip-badge {
	margin-left: 10rpx;
	padding: 2rpx 10rpx;
	border-radius: 8rpx;
	background: linear-gradient(135deg, #ff6b6b 0%, #ff9a6b 100%);
	font-size: 18rpx;
	color: #ffffff;
	font-weight: 600;
}

.search-suggest {
	background-color: #ffffff;
	border-radius: 24rpx;
	box-shadow: 0 6rpx 24rpx rgba(74, 140, 255, 0.08);
	overflow: hidden;
}

.search-suggest-item {
	display: flex;
	flex-direction: row;
	align-items: center;
	padding: 28rpx 28rpx;
	border-bottom: 1rpx solid #eef3fb;
}

.search-suggest-item:last-child {
	border-bottom: none;
}

.search-suggest-icon {
	font-size: 26rpx;
	margin-right: 16rpx;
	opacity: 0.65;
}

.search-suggest-text {
	flex: 1;
	min-width: 0;
	font-size: 28rpx;
	color: #1a1d29;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.search-suggest-tag {
	flex-shrink: 0;
	margin-left: 12rpx;
	padding: 4rpx 12rpx;
	border-radius: 8rpx;
	background-color: #eef3fb;
	font-size: 22rpx;
	color: #4a8cff;
}

.search-empty {
	padding: 48rpx 0;
	text-align: center;
}

.search-empty-text {
	font-size: 26rpx;
	color: #8a8d9e;
}
</style>
