'use client';

import Friends from '@/components/friends/Friends';
import { useCallback, useEffect, useState } from 'react';
import { CalculateReferralsCount } from '@/utils/CalculateReferralsCount';
import { updateFriendAndReferralCounts } from '@/utils/UpdateFriendAndReferralCount';
import { usePlayerStore } from '@/store/player.state';

const FriendsContainer = ({ botLink }: { botLink: string }) => {
    const [isVisible, setIsVisible] = useState<boolean>(false);

    const [userData, setUserData] = useState<{ id: number; username: string } | null>(null);

    const { player } = usePlayerStore();

    useEffect(() => {
        const initDataUnsafe = window.Telegram?.WebApp?.initDataUnsafe;
        if (!initDataUnsafe?.user) {
            return;
        }
        setUserData(initDataUnsafe.user);
    }, []);

    const handleCopyInviteLink = useCallback(async () => {
        setIsVisible(true);
        setTimeout(() => {
            setIsVisible(false);
        }, 3000);
        return await navigator.clipboard.writeText(`${botLink}ref_${userData?.id}`);
    }, [userData, botLink]);

    const handleCloseToastLink = useCallback(() => {
        setIsVisible(false);
    }, []);

    return (
        <Friends
            isVisible={isVisible}
            referral_fee={player?.attributes.referral_fee}
            friendsAndReferralsCount={updateFriendAndReferralCounts(
                player?.attributes.my_referrals?.data?.length || 0,
                CalculateReferralsCount(player),
            )}
            handleCopyInviteLink={handleCopyInviteLink}
            handleCloseToastLink={handleCloseToastLink}
        />
    );
};

export default FriendsContainer;
