import { getAppInfo } from "@/lib/platform/app-info";

export function getDeviceName(): string {
  try {
    if (typeof window === "undefined" || !navigator) {
      return "Unknown Device";
    }

    // Apps: the native bootstrap sets the label; the User-Agent would describe the WebView.
    const nativeName = getAppInfo().deviceName;
    if (nativeName) {
      return nativeName;
    }

    const ua = navigator.userAgent || "";
    const platform = navigator.platform || "Unknown";

    // device type
    const isMobile = /Mobi|Android/i.test(ua);
    const isTablet = /Tablet|iPad/i.test(ua);
    const deviceType = isTablet ? "Tablet" : isMobile ? "Mobile" : "Desktop";

    // OS detection
    let os = "Unknown OS";

    if (/Windows NT 10.0/i.test(ua)) os = "Windows 10";
    else if (/Windows NT 11.0/i.test(ua)) os = "Windows 11";
    else if (/Android ([\d.]+)/i.test(ua)) os = `Android ${ua.match(/Android ([\d.]+)/)?.[1]}`;
    else if (/iPhone OS ([\d_]+)/i.test(ua)) os = `iOS ${ua.match(/iPhone OS ([\d_]+)/)?.[1]?.replace(/_/g, ".")}`;
    else if (/Mac OS X ([\d_]+)/i.test(ua)) os = `MacOS ${ua.match(/Mac OS X ([\d_]+)/)?.[1]?.replace(/_/g, ".")}`;

    // browser detection
    let browser = "Unknown Browser";

    if (/Chrome\/([\d.]+)/i.test(ua)) {
      browser = `Chrome ${ua.match(/Chrome\/([\d.]+)/)?.[1]}`;
    } else if (/Firefox\/([\d.]+)/i.test(ua)) {
      browser = `Firefox ${ua.match(/Firefox\/([\d.]+)/)?.[1]}`;
    } else if (/Safari\/([\d.]+)/i.test(ua) && /Version\/([\d.]+)/i.test(ua)) {
      browser = `Safari ${ua.match(/Version\/([\d.]+)/)?.[1]}`;
    }

    const result = `${deviceType} | ${os} | ${browser} | ${platform}`;

    if (!result || result.trim() === "") {
      return "Unknown Device";
    }

    return result;

  } catch (error: any) {
    return "Unknown Device";
  }
}