// Blog visit counter utilities.
//
// Per-slug counter (getBlogVisitCount / incrementBlogVisitCount):
//   Tracks how many times THIS specific post has been viewed, per browser.
//   Used by BlogProductCta to show a "returning reader" CTA variant.
//   Storage: `rwz_blog_visit_{slug}` in localStorage, TTL 30 days.
//   Session guard: `rwz_blog_session_{slug}` in sessionStorage prevents double-counting.
//
// Global counter (getGlobalBlogVisitCount / incrementGlobalBlogVisitCount):
//   Counts total unique blog slugs viewed across all posts in this browser.
//   TTL: counter resets after VISIT_COUNT_TTL_DAYS days of inactivity.
export const RETURNING_THRESHOLD = 3;

// ---------------------------------------------------------------------------
// Per-slug tracking (used by BlogProductCta)
// ---------------------------------------------------------------------------

const perSlugStorageKey = (slug: string) => `rwz_blog_visit_${slug}`;
const perSlugSessionGuardKey = (slug: string) => `rwz_blog_session_${slug}`;
const PER_SLUG_VISIT_TTL_MS = 30 * 24 * 60 * 60 * 1000;

interface StoredPerSlugVisit {
  count: number;
  ts: number;
}

/**
 * Read the visit count for a specific slug.
 * Returns 0 on SSR, parse errors, or TTL expiry.
 */
export function getBlogVisitCount(blogSlug: string): number {
  if (typeof window === 'undefined') return 0;
  try {
    const raw = localStorage.getItem(perSlugStorageKey(blogSlug));
    if (!raw) return 0;
    const parsed = JSON.parse(raw) as StoredPerSlugVisit;
    if (Date.now() - parsed.ts > PER_SLUG_VISIT_TTL_MS) return 0;
    const n = parseInt(String(parsed.count), 10);
    return Number.isFinite(n) && n > 0 ? n : 0;
  } catch {
    return 0;
  }
}

/**
 * Increment the visit count for a specific slug by 1.
 * Capped to one increment per slug per browser session via sessionStorage guard.
 * Session guard is set ONLY after localStorage write succeeds, so a quota error
 * does not permanently suppress future increments for this session.
 */
export function incrementBlogVisitCount(blogSlug: string): void {
  if (typeof window === 'undefined') return;

  const sk = perSlugSessionGuardKey(blogSlug);

  try {
    if (sessionStorage.getItem(sk)) return;
  } catch {
    // sessionStorage unavailable — proceed without per-session guard
  }

  try {
    const current = getBlogVisitCount(blogSlug);
    const data: StoredPerSlugVisit = { count: current + 1, ts: Date.now() };
    localStorage.setItem(perSlugStorageKey(blogSlug), JSON.stringify(data));
    try {
      sessionStorage.setItem(sk, '1');
    } catch {
      // sessionStorage unavailable — increment was persisted; guard not set
    }
  } catch {
    // localStorage write failed (quota, private browsing) — silent no-op
  }
}

// ---------------------------------------------------------------------------
// Global counter (counts unique slugs viewed across all posts)
// ---------------------------------------------------------------------------

const BLOG_VISIT_COUNT_KEY = 'rwz_blog_visit_count';
const BLOG_VISIT_TIMESTAMP_KEY = 'rwz_blog_visit_ts';
const BLOG_SESSION_SEEN_KEY = 'rwz_blog_seen';
const VISIT_COUNT_TTL_DAYS = 90;

/**
 * Returns the global blog visit count (unique slugs viewed), or 0 if absent, corrupted, or expired.
 * SSR-safe: returns 0 when window/localStorage is unavailable.
 */
export function getGlobalBlogVisitCount(): number {
  if (typeof window === 'undefined') return 0;
  try {
    const tsRaw = localStorage.getItem(BLOG_VISIT_TIMESTAMP_KEY);
    if (tsRaw !== null) {
      const ts = parseInt(tsRaw, 10);
      if (Number.isFinite(ts)) {
        const daysSince = (Date.now() - ts) / (1000 * 60 * 60 * 24);
        if (daysSince > VISIT_COUNT_TTL_DAYS) {
          localStorage.removeItem(BLOG_VISIT_COUNT_KEY);
          localStorage.removeItem(BLOG_VISIT_TIMESTAMP_KEY);
          return 0;
        }
      }
    }
    const n = parseInt(localStorage.getItem(BLOG_VISIT_COUNT_KEY) ?? '0', 10);
    return Number.isFinite(n) && n > 0 ? n : 0;
  } catch {
    return 0;
  }
}

/**
 * Increments the global blog visit count for the given slug, capped to once per slug per
 * browser session. sessionStorage tracks which slugs have already been counted so remounts,
 * back-navigation, and React StrictMode double-invoke do not inflate the counter.
 */
export function incrementGlobalBlogVisitCount(blogSlug: string): void {
  if (typeof window === 'undefined') return;
  try {
    const seenRaw = sessionStorage.getItem(BLOG_SESSION_SEEN_KEY);
    const seen: string[] = seenRaw ? (JSON.parse(seenRaw) as string[]) : [];
    if (seen.includes(blogSlug)) return;

    seen.push(blogSlug);
    sessionStorage.setItem(BLOG_SESSION_SEEN_KEY, JSON.stringify(seen));

    const current = getGlobalBlogVisitCount();
    localStorage.setItem(BLOG_VISIT_COUNT_KEY, String(current + 1));
    localStorage.setItem(BLOG_VISIT_TIMESTAMP_KEY, String(Date.now()));
  } catch {
    // localStorage/sessionStorage unavailable — no-op.
  }
}
