/** Shared helpers for SWI personal dashboard widgets (SAT embed). */

export function countByStatus(assignments, statusId) {
  return assignments.filter(
    (row) => Number(row.document_status_id) === Number(statusId)
  ).length;
}

export function isCompleted(statusId) {
  return Number(statusId) === 4;
}

export function remainingSummary(assignments) {
  const total = assignments.length;
  const completed = assignments.filter((row) =>
    isCompleted(row.document_status_id)
  ).length;
  const remaining = total - completed;
  const progress = total > 0 ? Math.round((completed / total) * 100) : 0;
  return { total, completed, remaining, progress };
}

export function undoneAssignments(assignments, limit = 5) {
  return assignments
    .filter((row) => !isCompleted(row.document_status_id))
    .sort((a, b) => {
      const ta = a.assigned_at ? new Date(a.assigned_at).getTime() : 0;
      const tb = b.assigned_at ? new Date(b.assigned_at).getTime() : 0;
      return tb - ta;
    })
    .slice(0, limit);
}

export function locationSeries(documents) {
  const map = new Map();
  for (const doc of documents) {
    const label = (doc.location_name || "Unknown plant").trim() || "Unknown plant";
    map.set(label, (map.get(label) || 0) + 1);
  }
  return Array.from(map.entries())
    .map(([label, value]) => ({ label, value }))
    .sort((a, b) => b.value - a.value);
}

export function statusSeries(assignments) {
  const labels = [
    { id: 1, label: "Opened", tone: "opened" },
    { id: 2, label: "Assigned", tone: "assigned" },
    { id: 3, label: "In Progress", tone: "in-progress" },
    { id: 4, label: "Completed", tone: "completed" },
  ];
  return labels.map((item) => ({
    ...item,
    value: countByStatus(assignments, item.id),
  }));
}

function monthKey(date) {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}

/** Last 12 months assignment counts. */
export function monthlyAssignmentTrend(assignments) {
  const now = new Date();
  const buckets = [];
  for (let offset = 11; offset >= 0; offset -= 1) {
    const date = new Date(now.getFullYear(), now.getMonth() - offset, 1);
    buckets.push({
      label: date.toLocaleDateString(undefined, {
        month: "short",
        year: "2-digit",
      }),
      count: 0,
      key: monthKey(date),
    });
  }
  for (const row of assignments) {
    if (!row.assigned_at) continue;
    const date = new Date(row.assigned_at);
    if (Number.isNaN(date.getTime())) continue;
    const key = monthKey(date);
    const bucket = buckets.find((b) => b.key === key);
    if (bucket) bucket.count += 1;
  }
  return buckets;
}
