// Phase 8 store for forgiving gamification. Owns the last-7-days series
// of completion counts rendered by the Tasks-page badge + sparkline.
//
// Refresh triggers:
//  - module load (first time)
//  - lumotia:task-completed  (from page.svelte.ts completeTask)
//  - lumotia:step-completed  (from MicroSteps.svelte)
//  - lumotia:task-uncompleted (new event, emitted by uncompleteTask in Task 10)
//  - lumotia:task-deleted    (new event, emitted by deleteTask in Task 10)
//  - window focus        (for day rollover while the app stayed open
//                         past midnight)
//
// We deliberately avoid polling. Every path that changes a row's
// done state or deletes a row emits one of the events above.

import { invoke } from "@tauri-apps/api/core";
import { hasTauriRuntime } from "$lib/utils/runtime.js";
import type { DailyCompletionCount } from "$lib/types/app";

const DAYS = 7;

export const recentCompletions = $state<DailyCompletionCount[]>([]);

// Reactive getter. Svelte 5 does not allow exporting $derived at module
// level ("derived_invalid_export"), so we expose a function instead.
// Template consumers call todayCount() in reactive contexts and it
// recomputes when recentCompletions changes.
export function todayCount(): number {
  return recentCompletions.at(-1)?.count ?? 0;
}

export async function refresh(): Promise<void> {
  if (!hasTauriRuntime()) return;
  try {
    const series = await invoke<DailyCompletionCount[]>(
      "list_recent_completions_cmd",
      { days: DAYS },
    );
    recentCompletions.splice(0, recentCompletions.length, ...series);
  } catch (err) {
    // Do not toast. This is a background read. Log only.
    console.error("completionStats.refresh failed", err);
  }
}

if (typeof window !== "undefined") {
  const handler = () => {
    refresh().catch(() => {});
  };
  window.addEventListener("lumotia:task-completed", handler);
  window.addEventListener("lumotia:step-completed", handler);
  window.addEventListener("lumotia:task-uncompleted", handler);
  window.addEventListener("lumotia:task-deleted", handler);
  window.addEventListener("focus", handler);

  if (hasTauriRuntime()) {
    refresh().catch(() => {});
  }
}
