import { Achievement, Project } from '../data';

// Determine API Base URL dynamically from Vite env, fallback to hardcoded if not set
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'https://api.ifuntanhub.dev';

/**
 * Helper to parse Rank/Juara from Achievement title
 */
function extractRank(title: string): string {
  const match = title.match(/(Juara\s+\d+|Juara\s+Harapan\s*\d*|Top\s+\d+|Finalis|Peringkat\s+\d+|Medali\s+\w+)/i);
  return match ? match[0] : 'Pemenang';
}

/**
 * Helper to parse Level (Nasional, Internasional, Regional) from title/category
 */
function extractLevel(title: string, category: string): 'Nasional' | 'Internasional' | 'Regional' {
  const text = `${title} ${category}`.toLowerCase();
  if (
    text.includes('internasional') ||
    text.includes('international') ||
    text.includes('global') ||
    text.includes('world') ||
    text.includes('asean') ||
    text.includes('unesco')
  ) {
    return 'Internasional';
  }
  if (
    text.includes('regional') ||
    text.includes('kalbar') ||
    text.includes('kalimantan') ||
    text.includes('provinsi') ||
    text.includes('kota') ||
    text.includes('kabupaten') ||
    text.includes('lokal')
  ) {
    return 'Regional';
  }
  return 'Nasional'; // Default fallback
}

/**
 * Helper to extract competition name from full achievement title
 */
function extractCompetition(title: string): string {
  return title
    .replace(/^(Juara\s+\d+|Juara\s+Harapan\s*\d*|Top\s+\d+|Finalis|Peringkat\s+\d+|Medali\s+\w+)\s+(di\s+|pada\s+|dalam\s+)?/i, '')
    .trim();
}

/**
 * Fetch achievements from API
 */
export async function fetchAchievementsFromAPI(): Promise<Achievement[]> {
  const response = await fetch(`${API_BASE_URL}/items/prestasi`);
  if (!response.ok) {
    throw new Error(`Failed to fetch achievements: ${response.statusText}`);
  }
  const result = await response.json();
  const data = result.data || [];

  return data
    .filter((item: any) => item.status === 'published')
    .map((item: any) => {
      const id = String(item.id);
      const title = item.nama_prestasi || 'Untitled Achievement';
      const category = item.bidang || 'Akademik';
      const rank = extractRank(title);
      const level = extractLevel(title, category);
      const competition = extractCompetition(title);
      const year = parseInt(item.tahun) || new Date().getFullYear();
      const team = item.nama_tim || 'Mahasiswa';
      
      // Handle image url mapping for directus assets
      const image = item.foto
        ? `${API_BASE_URL}/assets/${item.foto}`
        : `https://picsum.photos/seed/prestasi-${id}/800/600`;
      
      const avatar = (item.nama_tim || item.nama_prestasi || 'IF')
        .substring(0, 2)
        .toUpperCase();

      // Create a friendly fallback description since Directus model lacks one
      const description = `${team} berhasil meraih prestasi luar biasa sebagai ${rank} dalam ajang ${competition} tahun ${year} pada bidang ${category.toLowerCase()}.`;

      return {
        id,
        title,
        category,
        competition,
        rank,
        year,
        level,
        description,
        team,
        nim: item.nim || undefined,
        generation: item.angkatan ? `Angkatan ${item.angkatan}` : 'Informatika',
        image,
        avatar,
      };
    });
}

/**
 * Fetch projects/portfolio from API
 */
export async function fetchProjectsFromAPI(): Promise<Project[]> {
  const response = await fetch(`${API_BASE_URL}/items/portfolio`);
  if (!response.ok) {
    throw new Error(`Failed to fetch portfolio: ${response.statusText}`);
  }
  const result = await response.json();
  const data = result.data || [];

  return data
    .filter((item: any) => item.status === 'published')
    .map((item: any) => {
      const id = String(item.id);
      const title = item.nama_proyek || 'Untitled Project';
      const studentName = item.nama_mahasiswa || 'Mahasiswa';
      const year = parseInt(item.tahun) || new Date().getFullYear();
      const category = item.bidang || 'Software Development';
      const description = item.deskripsi || 'Tidak ada deskripsi.';
      let link = item.url || undefined;
      if (link && !/^https?:\/\//i.test(link)) {
        link = `https://${link}`;
      }
      
      const image = item.foto
        ? `${API_BASE_URL}/assets/${item.foto}`
        : `https://picsum.photos/seed/project-${id}/800/600`;

      return {
        id,
        title,
        studentName,
        nim: item.nim || undefined,
        year,
        category,
        description,
        image,
        link,
      };
    });
}
