import { haversineKm } from "./mapGeo";

export function categoryCode(mainFilter) {
  switch (mainFilter) {
    case "News":
      return "NEWS";
    case "Friends":
      return "FRIENDS";
    case "Events":
      return "EVENT";
    case "Market":
      return "MARKET";
    case "All":
    default:
      return "";
  }
}

export function extractPostText(post) {
  const title = post.title || post.text || post.body || "Post";
  const body =
    post.snippet ||
    post.body ||
    post.content ||
    post.text ||
    "No additional details.";
  const short = title.length > 28 ? title.slice(0, 25) + "..." : title;
  return { title, body, short };
}

export function matchesSubFilter(post, subFilter) {
  if (!subFilter || subFilter.toUpperCase() === "ALL" || subFilter === "All") {
    return true;
  }
  const raw = post.sub_category ?? post.subCategory ?? "";
  const sub = raw.toString().toLowerCase();
  return sub === subFilter.toLowerCase();
}

function parseCreatedAt(createdAt) {
  if (!createdAt) return null;
  if (createdAt instanceof Date) return createdAt;

  const s = String(createdAt).trim();
  if (!s) return null;

  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(s)) {
    const isoLocal = s.replace(" ", "T");
    const d = new Date(isoLocal);
    return Number.isNaN(d.getTime()) ? null : d;
  }

  const d = new Date(s);
  return Number.isNaN(d.getTime()) ? null : d;
}

export function matchesTimeFilter(createdAt, timeFilter) {
  if (!timeFilter) return true;
  if (timeFilter === "PAST") return true;

  const d = parseCreatedAt(createdAt);
  if (!d) return true;

  const now = Date.now();
  const diffMs = now - d.getTime();
  if (!Number.isFinite(diffMs)) return true;
  if (diffMs < 0) return true;

  const diffHours = diffMs / 3600000;
  const diffDays = diffMs / 86400000;

  switch (timeFilter) {
    case "NOW":
      return diffHours <= 1;
    case "TODAY":
      return diffHours <= 24;
    case "RECENT":
      return diffDays <= 3;
    default:
      return true;
  }
}

export function isInViewRadius(post, center, radiusKm) {
  if (!center || !radiusKm) return true;
  const [lngC, latC] = center;
  const coords = post.coords || [post.lon ?? post.lng, post.lat ?? post.latitude];
  const [lngP, latP] = coords;
  if (
    typeof lngP !== "number" ||
    typeof latP !== "number" ||
    Number.isNaN(lngP) ||
    Number.isNaN(latP)
  ) {
    return true;
  }
  const dKm = haversineKm(latC, lngC, latP, lngP);
  return dKm <= radiusKm * 1.2;
}
