<template>
    <div class="agri-file-page" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <farm-header />
        <div class="nav-cards">
            <div v-for="item in navCards" :key="item.key" class="nav-card"
                :class="{ 'is-active': activeNav === item.key }" @click="activeNav = item.key">
                <img class="nav-card__icon" :src="item.icon" alt="" />
                <span class="nav-card__label">{{ t(item.labelKey) }}</span>
            </div>
        </div>
        <div class="content-panel">
            <div v-show="activeNav === 'patrol'">
                <div v-for="item in patrolList" :key="item.id" class="tracking-item"
                    :class="`tracking-item--${item.theme}`" @click="goGrowthTrack(item)">
                    <div class="tracking-item__header">
                        <div class="tracking-item__header-row">
                            <div class="tracking-item__header-left">
                                <span class="tracking-item__level">
                                    <el-icon><BellFilled /></el-icon>
                                    {{ item.level }}
                                </span>
                                <span class="tracking-item__title van-ellipsis">
                                    {{ item.title }}<span v-if="item.zone" class="tracking-item__zone"> ({{ item.zone }})</span>
                                </span>
                            </div>
                            <div class="tracking-item__share" @click.stop>
                                <Icon size="14" color="#2199F8" name="share" />
                                <span>{{ t("agriFile.forward") }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="tracking-item__body">
                        <div class="tracking-item__action">
                            <div class="tracking-item__action-main">
                                <div class="tracking-item__icon">
                                    <img :src="item.icon" alt="" />
                                    <span class="tracking-item__reason">{{ item.subject }}</span>
                                </div>
                                <div class="tracking-item__issue">{{ item.issue }}</div>
                            </div>
                            <div class="tracking-item__btn" @click.stop="openUploadPopup">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                <span>{{ t("agriFile.uploadPhoto") }}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="crop-archive">
                    <div class="crop-archive__title">{{ t("agriFile.cropArchive") }}</div>
                    <PhenologyTrackTimelineItem :list="cropArchiveList" />
                </div>
            </div>
            <div v-show="activeNav === 'album'">
                <div class="map-card" @click="goAlbumMap">
                    <div ref="mapContainer" class="map-container"></div>
                    <div class="add-zone-btn" @click.stop="goAddZone">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>{{ t("agriFile.addZone") }}</span>
                    </div>
                    <div v-for="item in zoneList" :key="item.id" :ref="(el) => setMarkerEl(item.id, el)"
                        class="zone-marker">
                        <div class="zone-marker__label">{{ item.name }}</div>
                        <div class="zone-marker__thumb">
                            <img :src="item.cover" alt="" />
                            <span class="zone-marker__badge">{{ item.count }}</span>
                        </div>
                        <div class="zone-marker__arrow"></div>
                    </div>
                </div>
                <div class="album-grid">
                    <div class="album-add">
                        <el-icon class="album-add__icon">
                            <Plus />
                        </el-icon>
                        <span>{{ t("agriFile.addAlbum") }}</span>
                    </div>
                    <div v-for="item in albumList" :key="item.id" class="album-card">
                        <div class="album-card__cover">
                            <img :src="item.cover" alt="" />
                            <span class="album-card__count">{{ t("agriFile.photoCount", { count: item.count }) }}</span>
                            <div class="album-card__add">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </div>
                        </div>
                        <div class="album-card__name">{{ item.name }}</div>
                    </div>
                </div>
            </div>
            <div v-show="activeNav === 'report'">
                <div v-for="item in reportList" :key="item.id" class="report-card">
                    <div class="report-card__cover">
                        <img :src="item.cover" alt="" />
                        <span class="report-card__date">{{ item.date }}</span>
                        <span class="report-card__status">
                            <i class="report-card__dot"></i>
                            {{ t("agriFile.reportUpdate") }}
                        </span>
                    </div>
                    <div class="report-card__body">
                        <div class="report-card__title">{{ item.title }}</div>
                        <div class="report-card__desc">{{ item.desc }}</div>
                    </div>
                </div>
            </div>
        </div>
        <album-upload-popup v-model:show="showUploadPopup" />
    </div>
</template>

<script setup>
import { computed, nextTick, onActivated, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import Overlay from "ol/Overlay";
import { useI18n } from "@/i18n";
import { Icon } from 'vant';
import FileMap from "./fileMap";
import * as util from "@/common/ol_common.js";
import farmHeader from "@/components/farmHeader.vue";
import albumUploadPopup from "./components/albumUploadPopup.vue";
import PhenologyTrackTimelineItem from "@/components/pageComponents/PhenologyTrackTimelineItem.vue";

const { t } = useI18n();
const store = useStore();
const router = useRouter();
const tabBarHeight = computed(() => store.state.home.tabBarHeight);

const defaultCover = require("@/assets/img/home/banner.png");
const DEFAULT_CENTER = [113.6142086995688, 23.585836479509055];

const activeNav = ref("patrol");
const mapContainer = ref(null);
const fileMap = new FileMap();
const markerEls = {};
const mapOverlays = [];

const navCards = [
    {
        key: "patrol",
        labelKey: "agriFile.patrolRecord",
        icon: require("@/assets/img/agricultural/icon-1.png"),
    },
    {
        key: "album",
        labelKey: "agriFile.agriAlbum",
        icon: require("@/assets/img/agricultural/icon-2.png"),
    },
    {
        key: "report",
        labelKey: "agriFile.diagnosisReport",
        icon: require("@/assets/img/agricultural/icon-3.png"),
    },
];

const zoneList = ref([
    { id: 1, name: "", count: 2, cover: defaultCover, longitude: 113.612409, latitude: 23.587036 },
    { id: 2, name: "", count: 2, cover: defaultCover, longitude: 113.615809, latitude: 23.586636 },
    { id: 3, name: "", count: 2, cover: defaultCover, longitude: 113.613609, latitude: 23.584436 },
    { id: 4, name: "", count: 2, cover: defaultCover, longitude: 113.615609, latitude: 23.585036 },
]);

const albumList = ref([
    { id: 1, name: "", count: 125, cover: defaultCover },
    { id: 2, name: "", count: 125, cover: defaultCover },
    { id: 3, name: "", count: 125, cover: defaultCover },
]);

const reportCover = require("@/assets/img/common/sd-1.jpg");
const reportList = ref([
    { id: 1, title: "", desc: "", date: "", cover: reportCover },
    { id: 2, title: "", desc: "", date: "", cover: require("@/assets/img/common/sd-2.jpg") },
    { id: 3, title: "", desc: "", date: "", cover: require("@/assets/img/common/sd-3.jpg") },
]);

const showUploadPopup = ref(false);
const patrolList = ref([
    {
        id: 1,
        type: "growth",
        theme: "blue",
        level: "",
        title: "",
        subject: "",
        issue: "",
        icon: require("@/assets/img/report/wh-icon.png"),
    },
    {
        id: 2,
        type: "abnormal",
        theme: "blue",
        level: "",
        title: "",
        subject: "",
        issue: "",
        icon: require("@/assets/img/report/wh-icon.png"),
    },
]);

const cropArchiveList = ref([
    { id: 1, date: "2025-04-18", zone_name: "", content: "" },
    { id: 2, date: "2025-04-18", zone_name: "", content: "" },
    { id: 3, date: "2025-04-10", zone_name: "", content: "" },
]);

const setMarkerEl = (id, el) => {
    if (el) markerEls[id] = el;
    else delete markerEls[id];
};

const getFarmCenter = () => {
    try {
        const farm = JSON.parse(localStorage.getItem("selectedFarmData") || "{}");
        const wkt = farm.wkt || farm.geom_wkt || farm.farm_location;
        if (typeof wkt === "string" && /^POINT\s*\(/i.test(wkt.trim())) {
            return util.wktCastGeom(wkt).getFirstCoordinate();
        }
    } catch {
        // ignore
    }
    return DEFAULT_CENTER;
};

const clearMapOverlays = () => {
    if (!fileMap.kmap?.map) {
        mapOverlays.length = 0;
        return;
    }
    mapOverlays.forEach((overlay) => fileMap.kmap.map.removeOverlay(overlay));
    mapOverlays.length = 0;
};

const bindZoneOverlays = () => {
    if (!fileMap.kmap?.map) return;
    clearMapOverlays();
    zoneList.value.forEach((zone) => {
        const el = markerEls[zone.id];
        if (!el || zone.longitude == null || zone.latitude == null) return;
        const overlay = new Overlay({
            element: el,
            position: [zone.longitude, zone.latitude],
            positioning: "bottom-center",
            stopEvent: false,
        });
        fileMap.kmap.map.addOverlay(overlay);
        mapOverlays.push(overlay);
    });
};

const initAlbumMap = async () => {
    await nextTick();
    if (!mapContainer.value) return;
    const center = getFarmCenter();
    fileMap.initMap(`POINT(${center[0]} ${center[1]})`, mapContainer.value);
    await nextTick();
    bindZoneOverlays();
    fileMap.kmap?.map?.updateSize?.();
};

const fillMockLabels = () => {
    const zoneName = t("agriFile.zoneLabel", { n: 1 });
    const albumName = t("agriFile.zoneOne");
    zoneList.value = zoneList.value.map((item) => ({ ...item, name: zoneName }));
    albumList.value = albumList.value.map((item) => ({ ...item, name: albumName }));
    reportList.value = reportList.value.map((item) => ({
        ...item,
        title: t("agriFile.reportTitle"),
        desc: t("agriFile.reportDesc"),
        date: t("agriFile.reportDate"),
    }));
    patrolList.value = patrolList.value.map((item, index) => ({
        ...item,
        level: t("agriFile.riskLevel2"),
        title: t(index === 0 ? "agriFile.patrolGrowthTitle" : "agriFile.patrolAbnormalTitle"),
        zone: albumName,
        subject: t("agriFile.patrolSubject"),
        issue: t("agriFile.patrolIssue"),
    }));
    cropArchiveList.value = cropArchiveList.value.map((item, index) => ({
        ...item,
        zone_name: albumName,
        content: t(index % 2 === 0 ? "agriFile.cropArchiveMetric" : "agriFile.cropArchiveAbnormal"),
    }));
};

const goAddZone = () => {
    router.push("/add_zone");
};

const goAlbumMap = () => {
    router.push("/album_map");
};

const goGrowthTrack = (item) => {
    router.push({
        path: "/growth_track",
        query: { id: item?.id, type: item?.type || "growth" },
    });
};

const openUploadPopup = () => {
    showUploadPopup.value = true;
};

onMounted(() => {
    fillMockLabels();
    initAlbumMap();
});
onActivated(() => {
    fillMockLabels();
    initAlbumMap();
});
onBeforeUnmount(clearMapOverlays);

watch(activeNav, (key) => {
    if (key === "album") {
        initAlbumMap();
    }
});
</script>

<style lang="scss" scoped>
.agri-file-page {
    position: relative;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: linear-gradient(180deg, #D1EBFF 0%, #FFFFFF 100%);

    .nav-cards {
        position: relative;
        z-index: 2;
        display: flex;
        justify-content: space-around;
        padding: 10px 10px;
        margin-bottom: 10px;

        .nav-card {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            background: #fff;
            width: 90px;
            height: 64px;
            box-shadow: 0px 4px 4px 0px #0000000D;

            .nav-card__icon {
                width: 26px;
                height: 26px;
                margin-bottom: 4px;
            }

            &.is-active {
                background: linear-gradient(180deg, #5BB8FF 0%, #2199F8 100%);
                box-shadow: 0 4px 10px rgba(33, 153, 248, 0.28);

                .nav-card__icon {
                    filter: brightness(0) invert(1);
                }

                .nav-card__label {
                    color: #fff;
                }

                &::after {
                    content: "";
                    position: absolute;
                    left: 50%;
                    bottom: -6px;
                    transform: translateX(-50%);
                    border-left: 6px solid transparent;
                    border-right: 6px solid transparent;
                    border-top: 6px solid #2199F8;
                    z-index: 3;
                }
            }
        }
    }

    .content-panel {
        flex: 1;
        overflow-y: auto;
        background: linear-gradient(360deg, rgba(229, 243, 255, 0.55) 0%, rgba(255, 255, 255, 0.55) 100%);
        border-radius: 20px 20px 0 0;
        border: 1px solid #FFFFFF;
        padding: 18px 10px;

        &::-webkit-scrollbar {
            display: none;
        }

        .map-card {
            position: relative;
            height: 210px;
        }

        .map-container {
            width: 100%;
            height: 100%;
            clip-path: inset(0px round 8px);
        }

        .zone-marker {
            display: flex;
            flex-direction: column;
            align-items: center;
            pointer-events: none;

            &__label {
                padding: 3px 14px;
                border-radius: 25px;
                background: #fff;
                color: #0A0A0A;
                font-size: 12px;
            }

            &__thumb {
                position: relative;
                width: 42px;
                height: 42px;
                margin-top: 8px;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    border: 2px solid #fff;
                    border-radius: 6px;
                    box-sizing: border-box;
                }
            }

            &__badge {
                position: absolute;
                top: -6px;
                right: -6px;
                min-width: 18px;
                height: 18px;
                line-height: 16px;
                border-radius: 50%;
                background: #fff;
                color: #0A0A0A;
                font-size: 12px;
                text-align: center;
            }

            &__arrow {
                width: 0;
                height: 0;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 6px solid #fff;
            }
        }

        .add-zone-btn {
            position: absolute;
            right: 5px;
            bottom: 10px;
            z-index: 5;
            display: flex;
            align-items: center;
            gap: 2px;
            padding: 5px 10px;
            border-radius: 4px;
            background: #fff;
            color: #2199F8;
            font-weight: 500;
        }

        .album-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
            margin-top: 16px;
            box-sizing: border-box;

            .album-add {
                align-self: start;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                width: 100%;
                aspect-ratio: 1;
                border-radius: 5px;
                background: #F5F5F7;
                color: #969494;
                font-size: 16px;

                &__icon {
                    margin-bottom: 6px;
                    font-size: 20px;
                }
            }

            .album-card {
                width: 100%;

                &__cover {
                    position: relative;
                    width: 100%;
                    aspect-ratio: 1;

                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                        border-radius: 6px;
                    }
                }

                &__count {
                    position: absolute;
                    top: 1px;
                    right: 0;
                    padding: 1px 5px;
                    border-radius: 0 5px 0 5px;
                    background: rgba(0, 0, 0, 0.4);
                    backdrop-filter: blur(4px);
                    color: #fff;
                }

                &__add {
                    position: absolute;
                    right: 8px;
                    bottom: 8px;
                    z-index: 1;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 44px;
                    height: 44px;
                    border-radius: 50%;
                    background: #2199F8;
                    color: #fff;
                    font-size: 20px;
                    box-shadow: 0 2px 8px rgba(33, 153, 248, 0.35);
                }

                &__name {
                    margin-top: 10px;
                    color: #1F1F1F;
                }
            }
        }

        .report-card {
            margin-bottom: 10px;
            border-radius: 8px;
            background: #fff;

            &:last-child {
                margin-bottom: 0;
            }

            &__cover {
                position: relative;
                width: 100%;
                height: 158px;

                img {
                    display: block;
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    border-radius: 5px;
                }
            }

            &__date {
                position: absolute;
                top: 0;
                padding: 5px 12px;
                border-radius: 4px;
                background: rgba(0, 0, 0, 0.45);
                backdrop-filter: blur(4px);
                color: #fff;
                font-size: 16px;
                border-radius: 5px 0 5px 0;
            }

            &__status {
                position: absolute;
                top: 10px;
                right: 0;
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 2px 13px;
                border-radius: 20px 0 0 20px;
                background: #FF5454;
                color: #fff;
                font-size: 12px;
            }

            &__dot {
                width: 6px;
                height: 6px;
                border-radius: 50%;
                background: #fff;
            }

            &__body {
                padding: 10px;
                margin-top: 4px;
            }

            &__title {
                font-size: 16px;
                font-weight: 500;
            }

            &__desc {
                margin-top: 4px;
                color: #9E9B9B;
            }
        }

        .tracking-item {
            width: 100%;
            margin-bottom: 16px;
            box-shadow: 0px 4px 4px 0px rgba(33, 153, 248, 0.1);


            &:last-of-type {
                margin-bottom: 0;
            }

            &__header {
                position: relative;
                padding: 10px 10px 20px;
                border-radius: 10px 10px 0 0;
                background: linear-gradient(180deg, #86CAFF 0%, #2199F8 48.5%);
            }

            &__header-row {
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            &__header-left {
                display: flex;
                align-items: center;
                gap: 5px;
            }

            &__level {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 1px 4px;
                border-radius: 2px;
                background: #fff;
                color: #FF6A6A;
                font-size: 12px;
            }

            &__title {
                color: #fff;
                font-size: 16px;
                font-weight: 500;
            }

            &__zone {
                font-size: 12px;
            }

            &__share {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 2px 10px;
                border-radius: 25px;
                background: #fff;
                color: #2199F8;
                font-size: 12px;
            }

            &__body {
                position: relative;
                padding: 10px;
                margin-top: -8px;
                border-radius: 10px;
                background: #fff;

                &::before {
                    content: "";
                    position: absolute;
                    top: -7px;
                    left: 21%;
                    width: 0;
                    height: 0;
                    border-left: 7px solid transparent;
                    border-right: 7px solid transparent;
                    border-bottom: 7px solid #fff;
                    transform: translateX(-50%);
                }
            }

            &__action {
                display: flex;
                align-items: center;
                justify-content: space-between;
                border: 1px solid rgba(33, 153, 248, 0.2);
                border-radius: 6px;
                padding: 8px;
            }

            &__icon {
                display: flex;
                align-items: center;
                gap: 5px;

                img {
                    width: 18px;
                    height: 16px;
                }
            }

            &__reason {
                color: #2199f8;
                font-weight: 500;
            }

            &__issue {
                margin-top: 2px;
                color: #2199f8;
                font-size: 12px;
            }

            &__btn {
                display: flex;
                align-items: center;
                gap: 2px;
                padding: 7px 10px;
                border-radius: 5px;
                background: #2199f8;
                color: #fff;
                font-size: 12px;
            }
        }

        .crop-archive {
            padding: 10px;
            border-radius: 10px;
            background: #fff;

            &__title {
                position: relative;
                display: inline-block;
                z-index: 1;
                font-size: 16px;
                font-weight: 500;
                margin-bottom: 5px;

                &::after {
                    content: "";
                    position: absolute;
                    left: 0;
                    bottom: 2px;
                    z-index: -1;
                    width: 90px;
                    height: 6px;
                    border-radius: 25px;
                    background: linear-gradient(90deg, #2199f8 0%, rgba(255, 255, 255, 0.37) 100%);
                    opacity: 0.4; 
                }
            }
        }
    }
}
</style>
