"use client";

export const DASHBOARD_PINNED_KEY = "videohaus:pinned-tools";
export const DASHBOARD_RECENT_KEY = "videohaus:recent-tools";
export const DASHBOARD_RECENT_UPDATED_EVENT = "videohaus:recent-tools-updated";

export interface RecentToolItem {
  slug: string;
  title: string;
  usedAtLabel: string;
}

interface StoredRecentTool {
  slug: string;
  title: string;
  usedAt: number;
}

function toSafeArray(value: unknown): string[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value.filter((entry): entry is string => typeof entry === "string");
}

function toSafeRecentArray(value: unknown): StoredRecentTool[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .filter((entry): entry is StoredRecentTool => {
      if (!entry || typeof entry !== "object") {
        return false;
      }

      const candidate = entry as Partial<StoredRecentTool>;
      return (
        typeof candidate.slug === "string" &&
        typeof candidate.title === "string" &&
        typeof candidate.usedAt === "number"
      );
    })
    .sort((left, right) => right.usedAt - left.usedAt);
}

function readLocalStorageJson(key: string) {
  if (typeof window === "undefined") {
    return null;
  }

  const rawValue = window.localStorage.getItem(key);
  if (!rawValue) {
    return null;
  }

  try {
    return JSON.parse(rawValue) as unknown;
  } catch {
    return null;
  }
}

export function readPinnedTools(defaultPinned: string[]) {
  const parsedValue = readLocalStorageJson(DASHBOARD_PINNED_KEY);
  const safePinned = toSafeArray(parsedValue);

  if (safePinned.length === 0) {
    return defaultPinned;
  }

  return safePinned;
}

export function writePinnedTools(pinned: string[]) {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.setItem(DASHBOARD_PINNED_KEY, JSON.stringify(pinned));
}

export function recordRecentToolOpen(entry: { slug: string; title: string }, limit = 6) {
  if (typeof window === "undefined") {
    return;
  }

  const parsedValue = readLocalStorageJson(DASHBOARD_RECENT_KEY);
  const currentItems = toSafeRecentArray(parsedValue);

  const withoutDuplicate = currentItems.filter((item) => item.slug !== entry.slug);
  const nextItems: StoredRecentTool[] = [
    {
      slug: entry.slug,
      title: entry.title,
      usedAt: Date.now()
    },
    ...withoutDuplicate
  ].slice(0, limit);

  window.localStorage.setItem(DASHBOARD_RECENT_KEY, JSON.stringify(nextItems));
  window.dispatchEvent(new CustomEvent(DASHBOARD_RECENT_UPDATED_EVENT));
}

export function clearRecentTools() {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.removeItem(DASHBOARD_RECENT_KEY);
  window.dispatchEvent(new CustomEvent(DASHBOARD_RECENT_UPDATED_EVENT));
}

function formatRelativeTimeLabel(usedAt: number) {
  const now = Date.now();
  const seconds = Math.max(0, Math.floor((now - usedAt) / 1000));

  if (seconds < 45) {
    return "Just now";
  }

  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) {
    return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
  }

  const hours = Math.floor(minutes / 60);
  if (hours < 24) {
    return `${hours} hour${hours === 1 ? "" : "s"} ago`;
  }

  const days = Math.floor(hours / 24);
  if (days === 1) {
    return "Yesterday";
  }

  if (days < 7) {
    return `${days} days ago`;
  }

  return new Date(usedAt).toLocaleDateString(undefined, {
    month: "short",
    day: "numeric"
  });
}

export function readRecentTools(fallback: RecentToolItem[], limit = 6): RecentToolItem[] {
  const parsedValue = readLocalStorageJson(DASHBOARD_RECENT_KEY);
  const storedItems = toSafeRecentArray(parsedValue);

  if (storedItems.length === 0) {
    return fallback.slice(0, limit);
  }

  return storedItems.slice(0, limit).map((item) => ({
    slug: item.slug,
    title: item.title,
    usedAtLabel: formatRelativeTimeLabel(item.usedAt)
  }));
}
