'use client';

import { useEffect, useState, useCallback } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { apiFetch } from '@/lib/api';

export interface MissionProgressItem {
  id: string;
  mission_id: string;
  status: 'in_progress' | 'completed' | 'failed' | 'abandoned' | string;
  started_at?: string;
  ends_at?: string | null;
  current_step?: number | null;
  total_steps?: number | null;
  mission?: {
    id: string;
    name?: string;
    title?: string;
    category?: string;
    total_steps?: number | null;
  } | null;
}

interface UseActiveMissionResult {
  mission: MissionProgressItem | null;
  loading: boolean;
  refresh: () => Promise<void>;
}

/**
 * Returns the currently active story/autonomous mission (status = in_progress).
 * If the player has none, returns null.
 *
 * Uses the existing `/api/mission/progress?status=in_progress` endpoint —
 * same functional surface that Footer already consumes.
 */
export function useActiveMission(): UseActiveMissionResult {
  const { player } = useGameStore();
  const [mission, setMission] = useState<MissionProgressItem | null>(null);
  const [loading, setLoading] = useState(false);

  const refresh = useCallback(async () => {
    if (!player?.id) return;
    setLoading(true);
    try {
      const data = await apiFetch<MissionProgressItem[]>('/api/mission/progress?status=in_progress');
      const list = Array.isArray(data) ? data : [];
      // Most recent first
      list.sort((a, b) => {
        const ta = a.started_at ? new Date(a.started_at).getTime() : 0;
        const tb = b.started_at ? new Date(b.started_at).getTime() : 0;
        return tb - ta;
      });
      setMission(list[0] ?? null);
    } catch {
      /* silent — Footer surfaces the authoritative errored state */
    } finally {
      setLoading(false);
    }
  }, [player?.id]);

  useEffect(() => {
    refresh();
    const id = setInterval(refresh, 30_000);
    return () => clearInterval(id);
  }, [refresh]);

  return { mission, loading, refresh };
}
