import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { Sponsor } from "@/types";

interface SponsorsContextType {
  sponsors: Sponsor[];
  addSponsor: (item: Omit<Sponsor, "id" | "createdAt">) => void;
  updateSponsor: (id: string, item: Omit<Sponsor, "id" | "createdAt">) => void;
  deleteSponsor: (id: string) => void;
}

const SponsorsContext = createContext<SponsorsContextType | null>(null);

export const useSponsors = () => {
  const ctx = useContext(SponsorsContext);
  if (!ctx) throw new Error("useSponsors must be inside SponsorsProvider");
  return ctx;
};

const STORAGE_KEY = "itarota79_sponsors";

const defaultSponsors: Sponsor[] = [
  { id: "s1", name: "JRPV - Proteção Veicular", logo: "🏍️", description: "JRPV BRASIL PROTEÇÃO PATRIMONIAL", link: "https://www.instagram.com/jrpvbrasil?utm_source=ig_web_button_share_sheet&igsh=ZDNlZDc0MzIxNw==", createdAt: Date.now() },
  { id: "s2", name: "AD Motos", logo: "🛞", description: "Revisão e serviços gerais", link: "https://www.instagram.com/admotos.ita?utm_source=ig_web_button_share_sheet&igsh=ZDNlZDc0MzIxNw==", createdAt: Date.now() - 1000 },

];

export const SponsorsProvider = ({ children }: { children: ReactNode }) => {
  const [sponsors, setSponsors] = useState<Sponsor[]>(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : defaultSponsors;
  });

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(sponsors));
  }, [sponsors]);

  const addSponsor = (item: Omit<Sponsor, "id" | "createdAt">) => {
    setSponsors((prev) => [{ ...item, id: crypto.randomUUID(), createdAt: Date.now() }, ...prev]);
  };

  const updateSponsor = (id: string, item: Omit<Sponsor, "id" | "createdAt">) => {
    setSponsors((prev) => prev.map((s) => (s.id === id ? { ...s, ...item } : s)));
  };

  const deleteSponsor = (id: string) => {
    setSponsors((prev) => prev.filter((s) => s.id !== id));
  };

  return (
    <SponsorsContext.Provider value={{ sponsors, addSponsor, updateSponsor, deleteSponsor }}>
      {children}
    </SponsorsContext.Provider>
  );
};
