import { toast } from "@xtablo/shared";
import { useEffect, useRef } from "react";
import { useOrganization } from "../hooks/organization";
import { useMaybeUser } from "../providers/UserStoreProvider";

const PLAN_ANNOUNCED_KEY = "xtablo_plan_announced";

const PLAN_LABELS: Record<string, { title: string; description: string }> = {
  solo: {
    title: "Plan Solo activé",
    description: "Bienvenue sur le plan Solo — profitez de toutes vos fonctionnalités.",
  },
  team: {
    title: "Plan Teams activé",
    description: "Bienvenue sur le plan Teams — collaborez sans limite avec votre équipe.",
  },
  annual: {
    title: "Plan Founder activé",
    description: "Bienvenue sur le plan Founder — accès illimité à toutes les fonctionnalités.",
  },
};

export function PlanAnnouncement() {
  const user = useMaybeUser();
  const { data: organizationData, isLoading } = useOrganization();
  const hasAnnounced = useRef(false);

  useEffect(() => {
    if (hasAnnounced.current) return;
    if (!user || isLoading || !organizationData) return;

    const { active_subscription_plan } = organizationData;
    if (!active_subscription_plan) return;

    const lastAnnouncedPlan = sessionStorage.getItem(PLAN_ANNOUNCED_KEY);
    if (lastAnnouncedPlan === active_subscription_plan) return;

    hasAnnounced.current = true;
    sessionStorage.setItem(PLAN_ANNOUNCED_KEY, active_subscription_plan);

    const label = PLAN_LABELS[active_subscription_plan];
    if (!label) return;

    toast.add(
      {
        title: label.title,
        description: label.description,
        type: "success",
        position: "top-center",
      },
      { timeout: 6000 }
    );
  }, [user, isLoading, organizationData]);

  return null;
}
