"use client";

import React, { createContext, useContext, useEffect, useState } from "react";
import type { Affiliate, Project, WorkExperience } from "../types";

interface ProfileContextType {
  projects: Project[];
  experiences: WorkExperience[];
  affiliates: Affiliate[];
  loading: boolean;
}

const ProfileContext = createContext<ProfileContextType | undefined>(undefined);

export function ProfileProvider({ children }: { children: React.ReactNode }) {
  const [projects, setProjects] = useState<Project[]>([]);
  const [experiences, setExperiences] = useState<WorkExperience[]>([]);
  const [affiliates, setAffiliates] = useState<Affiliate[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;

    async function load<T>(url: string, set: (v: T[]) => void) {
      try {
        const res = await fetch(url);
        if (!res.ok) return;
        const json = await res.json();
        if (!cancelled) set(Array.isArray(json) ? json : []);
      } catch {
        /* leave empty on failure */
      }
    }

    Promise.all([
      load<Project>("/api/projects", setProjects),
      load<WorkExperience>("/api/experience", setExperiences),
      load<Affiliate>("/api/affiliates", setAffiliates),
    ]).finally(() => {
      if (!cancelled) setLoading(false);
    });

    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <ProfileContext.Provider value={{ projects, experiences, affiliates, loading }}>
      {children}
    </ProfileContext.Provider>
  );
}

export function useProfile() {
  const context = useContext(ProfileContext);
  if (context === undefined) throw new Error("useProfile must be used within a ProfileProvider");
  return context;
}
