"use client";
import { useSystemStore } from "@/stores/useSystemStore";
import { Button, Popup } from "antd-mobile";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useEffect, useRef } from "react";

/**
 * @description 检测pwa是否下载
 * if 下载 不弹窗 ， else 弹窗
 *
 */
const Desktop = () => {
    const prompt = useRef<Event | null>(null);

    const t = useTranslations("HomePage");
    const { isHasDesktop, setHasDesktop } = useSystemStore((state) => {
        return {
            isHasDesktop: state.isHasDesktop,
            setHasDesktop: state.setHasDesktop,
        };
    });
    const downloadHandler = () => {
        // @ts-ignore
        prompt.current?.prompt();
        // 不判断是否真的包含
        setHasDesktop(false);
    };

    const initDesktop = (e: Event) => {
        if (window.matchMedia("(display-mode: standalone)").matches) {
            setHasDesktop(false);
            return;
        }
        // 有pwa 则不会触发
        prompt.current = e;
        // 只触发一次
        if (useSystemStore.getState().isHasDesktop === undefined) {
            setHasDesktop(true);
        }
    };

    useEffect(() => {
        window.addEventListener("beforeinstallprompt", initDesktop);
        // @ts-ignore
        window.onappinstalled = function (ev) {
            // 安装完成
            console.log("The application was installed.");
        };
        return () => window.removeEventListener("beforeinstallprompt", initDesktop);
    }, []);
    return (
        <Popup
            visible={!!isHasDesktop}
            getContainer={null}
            bodyStyle={{ padding: "0.2rem", background: "#fff" }}
        >
            <div className={"flex text-[0.12rem] text-[#8d8d8d]"}>
                <Image
                    src={"/icon-192x192.png"}
                    alt={"logo"}
                    className={"mr-[10px] flex-shrink-0"}
                    width={80}
                    height={80}
                />
                {t("saveTips")}
            </div>
            <div className={"mb-[0.16rem] mt-[0.1rem] text-right"}>
                <Button
                    color="default"
                    className={"mr-[10px]"}
                    style={{ "--text-color": "#8d8d8d" }}
                    fill="none"
                    onClick={() => setHasDesktop(false)}
                >
                    {t("cancel")}
                </Button>
                <Button
                    color="primary"
                    style={{
                        "--text-color": "#ff6a01",
                        "--border-color": "#ff6a01",
                        "--border-radius": "10px",
                    }}
                    fill="outline"
                    onClick={downloadHandler}
                >
                    {t("save")}
                </Button>
            </div>
        </Popup>
    );
};
export default Desktop;
