export const MARKETING_VISITOR_COOKIE = "official_mail_marketing_visitor";
export const MARKETING_VISITOR_STORAGE_KEY = "official_mail_marketing_visitor";

let memoryVisitorId: string | null = null;

function createVisitorId() {
  if (typeof crypto.randomUUID === "function") {
    return crypto.randomUUID().replace(/-/g, "");
  }

  return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
}

function isValidVisitorId(value: string | null | undefined): value is string {
  return Boolean(value && /^[a-z0-9_-]{16,96}$/i.test(value));
}

function getMarketingVisitorCookie() {
  const cookiePrefix = `${MARKETING_VISITOR_COOKIE}=`;
  const cookie = document.cookie
    .split(";")
    .map((part) => part.trim())
    .find((part) => part.startsWith(cookiePrefix));

  if (!cookie) {
    return null;
  }

  try {
    return decodeURIComponent(cookie.slice(cookiePrefix.length));
  } catch {
    return null;
  }
}

export function getOrCreateMarketingVisitorId() {
  let sharedVisitorId: string | null = null;
  try {
    sharedVisitorId = getMarketingVisitorCookie();
  } catch { /* Cookies may be disabled independently of local storage. */ }
  if (isValidVisitorId(sharedVisitorId)) {
    memoryVisitorId = sharedVisitorId;
    try {
      window.localStorage.setItem(MARKETING_VISITOR_STORAGE_KEY, sharedVisitorId);
    } catch { /* Keep the shared identity even if local storage is blocked. */ }
    return sharedVisitorId;
  }
  try {
    const existing = window.localStorage.getItem(MARKETING_VISITOR_STORAGE_KEY);

    if (isValidVisitorId(existing)) {
      memoryVisitorId = existing;
      return existing;
    }
  } catch { /* Use one in-memory identity per document as a final fallback. */ }
  const visitorId = memoryVisitorId ?? createVisitorId();
  memoryVisitorId = visitorId;
  try {
    window.localStorage.setItem(MARKETING_VISITOR_STORAGE_KEY, visitorId);
  } catch { /* Tracking must not interrupt page rendering. */ }
  return visitorId;
}

export function persistMarketingVisitorCookie(visitorId: string) {
  const hostname = window.location.hostname.toLowerCase();
  const sharedDomain =
    hostname === "officialsite.kr" || hostname.endsWith(".officialsite.kr")
      ? "; domain=.officialsite.kr"
      : "";
  const secure = window.location.protocol === "https:" ? "; Secure" : "";

  try {
    document.cookie = `${MARKETING_VISITOR_COOKIE}=${encodeURIComponent(visitorId)}; path=/; max-age=31536000; SameSite=Lax${sharedDomain}${secure}`;
  } catch { /* The in-memory visitor remains usable with cookies disabled. */ }
}

export function prepareMarketingVisitor() {
  const visitorId = getOrCreateMarketingVisitorId();
  persistMarketingVisitorCookie(visitorId);
  return visitorId;
}
