"use client";

import { useState, useEffect, useCallback } from "react";
import { ActiveAppContext, type AppData } from "@/hooks/use-active-app";

function getCookie(name: string): string | null {
  const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
  return match ? decodeURIComponent(match[1]) : null;
}

function setCookie(name: string, value: string, days = 365) {
  const expires = new Date(Date.now() + days * 864e5).toUTCString();
  document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
}

export function ActiveAppProvider({ children }: { children: React.ReactNode }) {
  const [apps, setApps] = useState<AppData[]>([]);
  const [activeApp, setActiveAppState] = useState<AppData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/apps")
      .then((r) => {
        if (!r.ok) return [];
        return r.json();
      })
      .then((data) => {
        if (!Array.isArray(data)) return;
        setApps(data);
        const savedSlug = getCookie("active-app");
        const matched = data.find((a: AppData) => a.slug === savedSlug);
        setActiveAppState(matched || data[0] || null);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const setActiveApp = useCallback(
    (slug: string) => {
      setCookie("active-app", slug);
      const app = apps.find((a) => a.slug === slug);
      if (app) setActiveAppState(app);
      // Refresh the page to update server-side queries
      window.location.reload();
    },
    [apps]
  );

  return (
    <ActiveAppContext value={{ apps, activeApp, setActiveApp, loading }}>
      {children}
    </ActiveAppContext>
  );
}
