"use client";

/**
 * 深链落地：把 deviceId + fbid/avatarUrl 写进本地存储，然后跳 `/chat`。
 *
 * 设计：
 *   - 不走 Server `redirect()`：避免把 fbid 暴露在 URL 里。
 *   - deviceId / fbid / avatarUrl 统一交给 `lib/chat` 落地。
 *   - 写入完成后 `router.replace('/chat')`，URL 不留深链痕迹。
 */

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

import { persistExternalBrowserChatDeepLink } from "@/lib/chat/chat_external_browser";
import { ROUTES } from "@/router/routes";
import { Logger } from "@/utils";

const log = new Logger("AppChatDeviceidDeviceIdDeepLinkPersist");

interface DeepLinkPersistProps {
  deviceId: string;
  fbid: string | null;
  avatarUrl: string | null;
}

export default function DeepLinkPersist({
  deviceId,
  fbid,
  avatarUrl,
}: DeepLinkPersistProps) {
  const router = useRouter();
  const [done, setDone] = useState(false);

  useEffect(() => {
    void (async () => {
      try {
        await persistExternalBrowserChatDeepLink({
          deviceId,
          facebookId: fbid,
          avatarUrl,
        });
      } catch (err) {
        // 写不进 localStorage 时（例如隐私模式）也不阻塞跳转；记录到 console 即可。
        log.warn("[DeepLinkPersist] failed to persist", err);
      } finally {
        setDone(true);
        router.replace(ROUTES.chat);
      }
    })();
  }, [avatarUrl, deviceId, fbid, router]);

  return (
    <div
      className="flex flex-1 items-center justify-center"
      style={{ minHeight: "100dvh" }}
    >
      <div
        aria-label={done ? "Redirecting" : "Loading"}
        className="size-10 animate-spin rounded-full border-4 border-t-transparent"
        style={{ borderColor: "var(--color-accent)" }}
      />
    </div>
  );
}
