const PROPERTY_STATS_STORAGE_KEY = "ccp-property-stats";

function readLocalPropertyStats() {
  try {
    const saved = JSON.parse(localStorage.getItem(PROPERTY_STATS_STORAGE_KEY) || "{}");
    return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
  } catch (err) {
    return {};
  }
}

function scoreStats(stat = {}) {
  return (
    Number(stat.inquiries || 0) * 12 +
    Number(stat.clicks || 0) * 4 +
    Number(stat.views || 0) * 2 +
    Number(stat.saves || 0) * 3
  );
}

function writeLocalPropertyEvent(propertyId, eventType) {
  if (!propertyId) return;
  const keyByEvent = { view: "views", click: "clicks", save: "saves", inquiry: "inquiries" };
  const key = keyByEvent[eventType];
  if (!key) return;
  const stats = readLocalPropertyStats();
  const current = stats[propertyId] || { views: 0, clicks: 0, saves: 0, inquiries: 0 };
  const next = { ...current, [key]: Number(current[key] || 0) + 1, updatedAt: new Date().toISOString() };
  next.score = scoreStats(next);
  stats[propertyId] = next;
  localStorage.setItem(PROPERTY_STATS_STORAGE_KEY, JSON.stringify(stats));
}

async function loadPropertyStats() {
  try {
    const response = await fetch("/api/property-stats");
    if (!response.ok) throw new Error("Stats load failed");
    const serverStats = await response.json();
    return { ...readLocalPropertyStats(), ...(serverStats || {}) };
  } catch (err) {
    return readLocalPropertyStats();
  }
}

function trackPropertyEvent(propertyId, eventType) {
  if (!propertyId || !eventType) return;
  const body = JSON.stringify({
    propertyId,
    eventType,
    page: window.location.pathname.split("/").pop() || "index.html",
    createdAt: new Date().toISOString(),
  });

  try {
    if (navigator.sendBeacon) {
      const sent = navigator.sendBeacon("/api/property-events", new Blob([body], { type: "application/json" }));
      if (sent) return;
    }
  } catch (err) {}

  fetch("/api/property-events", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body,
    keepalive: true,
  }).catch(() => writeLocalPropertyEvent(propertyId, eventType));
}

function propertyEngagementScore(property, stats = {}) {
  const stat = stats[property.id] || {};
  return Number(stat.score || scoreStats(stat) || 0);
}

function sortListingsByEngagement(listings, stats = {}) {
  return [...listings].sort((a, b) => {
    const scoreDiff = propertyEngagementScore(b, stats) - propertyEngagementScore(a, stats);
    if (scoreDiff) return scoreDiff;
    const badgeWeight = (b.badge ? 1 : 0) - (a.badge ? 1 : 0);
    if (badgeWeight) return badgeWeight;
    return Number(b.price || 0) - Number(a.price || 0);
  });
}

window.loadPropertyStats = loadPropertyStats;
window.trackPropertyEvent = trackPropertyEvent;
window.propertyEngagementScore = propertyEngagementScore;
window.sortListingsByEngagement = sortListingsByEngagement;
