// app/projects/code/page.tsx

import MatrixRain from '@/app/components/MatrixRain';
import { FaCodeBranch, FaGithub, FaGitlab, FaGlobe, FaStar } from 'react-icons/fa';

interface GithubProfile {
    html_url: string;
    avatar_url: string;
    name: string;
    login: string;
    bio: string;
    followers: number;
    public_repos: number;
}

interface GithubRepo {
    id: number;
    name: string;
    description: string;
    html_url: string;
    language: string;
    stargazers_count: number;
    forks: number;
}

interface GitlabRepo {
    id: number;
    name: string;
    description: string;
    web_url: string;
    star_count: number;
    forks_count: number;
    language?: string;
}

async function getProfile(): Promise<GithubProfile | null> {
    try {
        const res = await fetch('https://api.github.com/users/WilliamSoderberg', { next: { revalidate: 60 } });
        if (!res.ok) return null;
        return res.json();
    } catch (e) {
        return null;
    }
}

async function getGithubRepos(): Promise<GithubRepo[]> {
    try {
        const res = await fetch('https://api.github.com/users/WilliamSoderberg/repos?sort=updated', { next: { revalidate: 60 } });
        if (!res.ok) return [];
        return res.json();
    } catch (e) {
        return [];
    }
}

async function getGitlabRepos(): Promise<GitlabRepo[]> {
    try {
        const res = await fetch('https://gitlab.soderberg.tech/api/v4/groups/soderberg-tech/projects', {
            next: { revalidate: 60 }
        });

        if (!res.ok) return [];
        const projects: GitlabRepo[] = await res.json();
        const projectsWithLanguages = await Promise.all(
            projects.map(async (repo) => {
                try {
                    const langRes = await fetch(`https://gitlab.soderberg.tech/api/v4/projects/${repo.id}/languages`, {
                        next: { revalidate: 60 }
                    });

                    if (langRes.ok) {
                        const languages = await langRes.json();
                        const topLanguage = Object.keys(languages).sort((a, b) => languages[b] - languages[a])[0];
                        return { ...repo, language: topLanguage };
                    }
                } catch (e) {
                    console.error(`Failed to fetch language for GitLab repo: ${repo.id}`);
                }
                return repo;
            })
        );

        return projectsWithLanguages;
    } catch (e) {
        console.error("GitLab fetch failed, returning empty array");
        return [];
    }
}

const langColors: Record<string, string> = {
    JavaScript: 'bg-[#f1e05a]',
    TypeScript: 'bg-[#2b7489]',
    Python: 'bg-[#3572A5]',
    PHP: 'bg-[#4F5D95]',
    CSS: 'bg-[#563d7c]',
    HTML: 'bg-[#e44b23]',
    Vue: 'bg-[#41b883]'
};

export default async function CodePage() {
    const [profile, githubRepos, gitlabRepos] = await Promise.all([
        getProfile(),
        getGithubRepos(),
        getGitlabRepos()
    ]);

    return (
        <main className="flex flex-col flex-1 relative min-h-dvh">
            <MatrixRain />

            <div className="h-25 shrink-0"></div>

            <div className="relative z-10 w-full max-w-350 mx-auto px-4 pb-20 flex flex-col gap-16">

                {/* 2. Profile Card Section */}
                {profile && (
                    <section className="flex justify-center mt-10">
                        <div className="relative flex flex-col justify-center items-center bg-linear-to-b from-[#333333]/90 to-[#2a2a2a]/90 backdrop-blur-lg rounded-3xl text-center p-8 shadow-[0_8px_32px_rgba(0,0,0,0.5)] w-full max-w-md border border-white/10">
                            <a href={profile.html_url} target="_blank" rel="noopener noreferrer">
                                <FaGithub className="absolute text-white text-[28px] top-5 right-5 hover:text-[#84c0a0] transition-colors" />
                            </a>
                            <div className="w-full">
                                <div className="relative h-37.5 w-37.5 mx-auto mb-5">
                                    <img src={profile.avatar_url} alt="Avatar" className="h-full w-full rounded-full object-cover border-4 border-[#84c0a0] shadow-[0_0_15px_rgba(132,192,160,0.5)]" />
                                </div>
                                <h1 className="mb-1">
                                    <a className="text-white text-[26px] font-bold tracking-wide no-underline hover:text-[#84c0a0] transition-colors" href={profile.html_url} target="_blank" rel="noopener noreferrer">
                                        {profile.name}
                                    </a>
                                </h1>
                                <div className="mb-5">
                                    <a className="text-[#a0aab6] font-medium no-underline hover:text-white transition-colors" href={profile.html_url} target="_blank" rel="noopener noreferrer">
                                        @{profile.login}
                                    </a>
                                </div>
                                <p className="font-medium mx-auto text-[#84c0a0] mt-2.5 text-[15px] leading-relaxed">
                                    {profile.bio}
                                </p>
                                <div className="mt-8 relative border-t border-white/10 pt-5 flex justify-around">
                                    <div className="relative">
                                        <div className="text-white text-[22px] font-bold">{profile.followers}</div>
                                        <div className="text-[11px] font-bold text-[#a0aab6] tracking-widest uppercase mt-1">Followers</div>
                                    </div>
                                    <div className="relative">
                                        <div className="text-white text-[22px] font-bold">{profile.public_repos}</div>
                                        <div className="text-[11px] font-bold text-[#a0aab6] tracking-widest uppercase mt-1">Repositories</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                )}

                {/* 3. GitLab Repositories Section */}
                <section className="bg-[#fc6d26]/10 backdrop-blur-lg rounded-3xl border border-[#fc6d26]/30 p-8 shadow-2xl">
                    <div className="flex justify-center items-center flex-col mb-10">
                        <a href="https://gitlab.soderberg.tech/WilliamSoderberg" target="_blank" rel="noopener noreferrer">
                            <FaGitlab className="text-[#fc6d26] text-[55px] drop-shadow-[0_0_15px_rgba(252,109,38,0.4)] hover:scale-110 transition-transform cursor-pointer" />
                        </a>
                        <h2 className="text-white mt-3.75 text-[32px] md:text-[38px] uppercase font-bold text-center tracking-wider">
                            GitLab Projects
                        </h2>
                        <p className="text-gray-300 text-center max-w-2xl mt-3">Self-hosted infrastructure and private development.</p>
                    </div>

                    {gitlabRepos.length > 0 ? (
                        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6 justify-center">
                            {gitlabRepos.map((repo) => (
                                <a key={repo.id} href={repo.web_url} target="_blank" rel="noopener noreferrer" className="group flex flex-col justify-between bg-linear-to-br from-[#2a2a2a]/90 to-[#222222]/90 border border-white/10 p-6 rounded-2xl hover:-translate-y-1 hover:border-[#fc6d26]/60 hover:shadow-[0_8px_24px_rgba(252,109,38,0.2)] transition-all duration-300 no-underline">
                                    <div>
                                        <h3 className="text-[#fc6d26] text-[19px] font-bold group-hover:text-white transition-colors truncate">
                                            {repo.name}
                                        </h3>
                                        <p className="text-[14px] mb-4 mt-2.5 text-gray-400 text-left line-clamp-3 leading-relaxed">
                                            {repo.description || 'No description provided.'}
                                        </p>
                                    </div>
                                    <div className="flex items-center text-[13px] text-[#8b949e] mt-4 font-medium">
                                        {/* NEW: GitLab Language Badge */}
                                        {repo.language && (
                                            <div className="flex items-center mr-5">
                                                <span className={`w-2.5 h-2.5 rounded-full mr-2 ${langColors[repo.language] || 'bg-gray-500'}`}></span>
                                                <span className="text-gray-300">{repo.language}</span>
                                            </div>
                                        )}
                                        {repo.star_count > 0 && (
                                            <span className="flex items-center mr-4">
                                                <FaStar className="mr-1.5" /> {repo.star_count}
                                            </span>
                                        )}
                                        {repo.forks_count > 0 && (
                                            <span className="flex items-center">
                                                <FaCodeBranch className="mr-1.5" /> {repo.forks_count}
                                            </span>
                                        )}
                                    </div>
                                </a>
                            ))}
                        </div>
                    ) : (
                        <div className="text-center text-gray-400 italic py-8 bg-black/20 rounded-xl">No public GitLab repositories found or API is restricted.</div>
                    )}
                </section>

                {/* 4. GitHub Repositories Section */}
                <section className="bg-[#84c0a0]/10 backdrop-blur-lg rounded-3xl border border-[#84c0a0]/30 p-8 shadow-2xl">
                    <div className="flex justify-center items-center flex-col mb-10">
                        <FaGithub className="text-white text-[55px] drop-shadow-[0_0_15px_rgba(255,255,255,0.2)]" />
                        <h2 className="text-white mt-3.75 text-[32px] md:text-[38px] uppercase font-bold text-center tracking-wider">
                            Public Repositories
                        </h2>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6 justify-center">
                        {githubRepos.map((repo) => (
                            <a key={repo.id} href={repo.html_url} target="_blank" rel="noopener noreferrer" className="group flex flex-col justify-between bg-linear-to-br from-[#2a2a2a]/90 to-[#222222]/90 border border-white/10 p-6 rounded-2xl hover:-translate-y-1 hover:border-[#84c0a0]/60 hover:shadow-[0_8px_24px_rgba(132,192,160,0.2)] transition-all duration-300 no-underline">
                                <div>
                                    <h3 className="text-[#4e9fff] text-[19px] font-bold group-hover:text-white transition-colors truncate">
                                        {repo.name}
                                    </h3>
                                    <p className="text-[14px] mb-4 mt-2.5 text-gray-400 text-left line-clamp-3 leading-relaxed">
                                        {repo.description || 'No description provided.'}
                                    </p>
                                </div>
                                <div className="flex items-center text-[13px] text-[#8b949e] mt-4 font-medium">
                                    {repo.language && (
                                        <div className="flex items-center mr-5">
                                            <span className={`w-2.5 h-2.5 rounded-full mr-2 ${langColors[repo.language] || 'bg-gray-500'}`}></span>
                                            <span className="text-gray-300">{repo.language}</span>
                                        </div>
                                    )}
                                    {repo.stargazers_count > 0 && (
                                        <span className="flex items-center mr-4">
                                            <FaStar className="mr-1.5" /> {repo.stargazers_count}
                                        </span>
                                    )}
                                    {repo.forks > 0 && (
                                        <span className="flex items-center">
                                            <FaCodeBranch className="mr-1.5" /> {repo.forks}
                                        </span>
                                    )}
                                </div>
                            </a>
                        ))}
                    </div>
                </section>

                {/* 5. Hosted Websites Section */}
                <section className="bg-white/5 backdrop-blur-lg rounded-3xl border border-white/10 p-10 shadow-2xl">
                    <div className="flex justify-center items-center flex-col mb-10">
                        <FaGlobe className="text-white text-[55px] drop-shadow-[0_0_15px_rgba(255,255,255,0.2)]" />
                        <h2 className="text-white mt-3.75 text-[32px] md:text-[38px] uppercase font-bold text-center tracking-wider">
                            Hosted Websites
                        </h2>
                    </div>

                    {/* Changed from Flex to Grid for perfect centering! */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-12 max-w-5xl mx-auto justify-items-center items-center py-6">
                        <a className="no-underline text-white text-[22px] flex flex-col items-center hover:scale-105 transition-transform group" href="https://soderberg.tech">
                            <img src="/assets/logos/logo.svg" alt="Soderberg Tech" className="w-22.5 h-16.25 object-contain mb-5 drop-shadow-md group-hover:drop-shadow-[0_0_10px_rgba(255,255,255,0.5)] transition-all" />
                            <span className="font-bold tracking-wide text-center">Soderberg Tech</span>
                        </a>
                        <a className="no-underline text-white text-[22px] flex flex-col items-center hover:scale-105 transition-transform group" href="https://lirkab.se">
                            <img src="/assets/logos/lirkab.svg" alt="Lirkab" className="w-22.5 h-16.25 object-contain mb-5 drop-shadow-md group-hover:drop-shadow-[0_0_10px_rgba(255,255,255,0.5)] transition-all" />
                            <span className="font-bold tracking-wide text-center">Lirkab</span>
                        </a>
                        <a className="no-underline text-white text-[22px] flex flex-col items-center hover:scale-105 transition-transform group" href="https://lerbergetsvolleyboll.se">
                            <img src="/assets/logos/lvs.svg" alt="Lerbergets Volleyboll" className="w-22.5 h-16.25 object-contain mb-5 drop-shadow-md group-hover:drop-shadow-[0_0_10px_rgba(255,255,255,0.5)] transition-all" />
                            <span className="font-bold tracking-wide text-center">Lerbergets Volleyboll</span>
                        </a>
                    </div>
                </section>

            </div>
        </main>
    );
}