import { ref } from "vue";

export interface Transfer {
  id: string;
  fileName: string;
  percentage: number;
  speed: string;
  direction: "upload" | "download";
}

// Module-level singleton — shared across all components that import this composable.
const transfers = ref<Transfer[]>([]);

let _nextId = 0;

function addTransfer(fileName: string, direction: "upload" | "download"): string {
  const id = `transfer-${++_nextId}`;
  transfers.value.push({ id, fileName, percentage: 0, speed: "", direction });
  return id;
}

function completeTransfer(id: string): void {
  const t = transfers.value.find((t) => t.id === id);
  if (t) {
    t.percentage = 100;
    t.speed = "";
  }
  // Remove after 3 seconds
  setTimeout(() => {
    transfers.value = transfers.value.filter((t) => t.id !== id);
  }, 3000);
}

function failTransfer(id: string): void {
  transfers.value = transfers.value.filter((t) => t.id !== id);
}

export function useTransfers() {
  return { transfers, addTransfer, completeTransfer, failTransfer };
}
