// app/projects/code/page.tsx

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

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 {
        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 {
        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 {
                    console.error(`Failed to fetch language for GitLab repo: ${repo.id}`);
                }
                return repo;
            })
        );

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

const langColors: Record<string, string> = {
    JavaScript: 'bg-[#f1e05a]',
    TypeScript: 'bg-[#2b7489]',
    TSX: '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 bg-slate-50/50 dark:bg-transparent transition-colors duration-300">
            <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-white/90 dark:bg-linear-to-b dark:from-[#333333]/90 dark:to-[#2a2a2a]/90 backdrop-blur-lg rounded-3xl text-center p-8 shadow-xl dark:shadow-[0_8px_32px_rgba(0,0,0,0.5)] w-full max-w-md border border-slate-200 dark:border-white/10 transition-colors duration-300">
                            <a href={profile.html_url} target="_blank" rel="noopener noreferrer">
                                <FaGithub className="absolute text-slate-800 dark:text-white text-[28px] top-5 right-5 hover:text-[#84c0a0] dark:hover:text-[#84c0a0] transition-colors" />
                            </a>
                            <div className="w-full">
                                <div className="relative h-37.5 w-37.5 mx-auto mb-5">
                                    <Image src={profile.avatar_url} alt="Avatar" width={150} height={150} className="h-full w-full rounded-full object-cover border-4 border-[#84c0a0]/50 dark:border-[#84c0a0] shadow-[0_0_15px_rgba(132,192,160,0.3)] dark:shadow-[0_0_15px_rgba(132,192,160,0.5)]" />
                                </div>
                                <h1 className="mb-1">
                                    <a className="text-slate-900 dark:text-white text-[26px] font-bold tracking-wide no-underline hover:text-[#84c0a0] dark: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-slate-500 dark:text-[#a0aab6] font-medium no-underline hover:text-slate-800 dark: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-slate-200 dark:border-white/10 pt-5 flex justify-around transition-colors duration-300">
                                    <div className="relative">
                                        <div className="text-slate-900 dark:text-white text-[22px] font-bold transition-colors">{profile.followers}</div>
                                        <div className="text-[11px] font-bold text-slate-500 dark:text-[#a0aab6] tracking-widest uppercase mt-1 transition-colors">Followers</div>
                                    </div>
                                    <div className="relative">
                                        <div className="text-slate-900 dark:text-white text-[22px] font-bold transition-colors">{profile.public_repos}</div>
                                        <div className="text-[11px] font-bold text-slate-500 dark:text-[#a0aab6] tracking-widest uppercase mt-1 transition-colors">Repositories</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                )}

                {/* 3. GitLab Repositories Section */}
                <section className="bg-[#fc6d26]/15 dark:bg-[#fc6d26]/10 backdrop-blur-lg rounded-3xl border border-[#fc6d26]/20 dark:border-[#fc6d26]/30 p-8 shadow-xl dark:shadow-2xl transition-colors duration-300">
                    <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-slate-900 dark:text-white mt-3.75 text-[32px] md:text-[38px] uppercase font-bold text-center tracking-wider transition-colors">
                            GitLab Projects
                        </h2>
                        <p className="text-slate-600 dark:text-gray-300 text-center max-w-2xl mt-3 transition-colors">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-white/90 dark:bg-linear-to-br dark:from-[#2a2a2a]/90 dark:to-[#222222]/90 border border-slate-200 dark:border-white/10 p-6 rounded-2xl hover:-translate-y-1 hover:border-[#fc6d26]/60 dark:hover:border-[#fc6d26]/60 hover:shadow-[0_8px_24px_rgba(252,109,38,0.15)] dark: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-slate-900 dark:group-hover:text-white transition-colors truncate">
                                            {repo.name}
                                        </h3>
                                        <p className="text-[14px] mb-4 mt-2.5 text-slate-500 dark:text-gray-400 text-left line-clamp-3 leading-relaxed transition-colors">
                                            {repo.description || 'No description provided.'}
                                        </p>
                                    </div>
                                    <div className="flex items-center text-[13px] text-slate-500 dark:text-[#8b949e] mt-4 font-medium transition-colors">
                                        {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-slate-600 dark: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-slate-500 dark:text-gray-400 italic py-8 bg-black/5 dark:bg-black/20 rounded-xl transition-colors">No public GitLab repositories found or API is restricted.</div>
                    )}
                </section>

                {/* 4. GitHub Repositories Section */}
                <section className="bg-[#84c0a0]/15 dark:bg-[#84c0a0]/10 backdrop-blur-lg rounded-3xl border border-[#84c0a0]/20 dark:border-[#84c0a0]/30 p-8 shadow-xl dark:shadow-2xl transition-colors duration-300">
                    <div className="flex justify-center items-center flex-col mb-10">
                        <FaGithub className="text-slate-900 dark:text-white text-[55px] drop-shadow-md dark:drop-shadow-[0_0_15px_rgba(255,255,255,0.2)] transition-colors" />
                        <h2 className="text-slate-900 dark:text-white mt-3.75 text-[32px] md:text-[38px] uppercase font-bold text-center tracking-wider transition-colors">
                            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-white/90 dark:bg-linear-to-br dark:from-[#2a2a2a]/90 dark:to-[#222222]/90 border border-slate-200 dark: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.15)] dark: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-slate-900 dark:group-hover:text-white transition-colors truncate">
                                        {repo.name}
                                    </h3>
                                    <p className="text-[14px] mb-4 mt-2.5 text-slate-500 dark:text-gray-400 text-left line-clamp-3 leading-relaxed transition-colors">
                                        {repo.description || 'No description provided.'}
                                    </p>
                                </div>
                                <div className="flex items-center text-[13px] text-slate-500 dark:text-[#8b949e] mt-4 font-medium transition-colors">
                                    {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-slate-600 dark: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/80 dark:bg-white/5 backdrop-blur-lg rounded-3xl border border-slate-200 dark:border-white/10 p-10 shadow-xl dark:shadow-2xl transition-colors duration-300">
                    <div className="flex justify-center items-center flex-col mb-10">
                        <FaGlobe className="text-slate-900 dark:text-white text-[55px] drop-shadow-md dark:drop-shadow-[0_0_15px_rgba(255,255,255,0.2)] transition-colors" />
                        <h2 className="text-slate-900 dark:text-white mt-3.75 text-[32px] md:text-[38px] uppercase font-bold text-center tracking-wider transition-colors">
                            Hosted Websites
                        </h2>
                    </div>

                    <div className="flex flex-wrap justify-center gap-12 max-w-5xl mx-auto py-6">
                        <a className="w-full md:w-[calc(33.333%-32px)] no-underline text-slate-900 dark:text-white text-[22px] flex flex-col items-center hover:scale-105 transition-transform group" href="https://soderberg.tech">
                            <Image src="/assets/logos/logo.svg" alt="Soderberg Tech" width={90} height={65} className="w-22.5 h-16.25 object-contain mb-5 drop-shadow-md group-hover:drop-shadow-lg dark:group-hover:drop-shadow-[0_0_10px_rgba(255,255,255,0.5)] transition-all dark:invert-0 filter invert" />
                            <span className="font-bold tracking-wide text-center">Soderberg Tech</span>
                        </a>
                        <a className="w-full md:w-[calc(33.333%-32px)] no-underline text-slate-900 dark:text-white text-[22px] flex flex-col items-center hover:scale-105 transition-transform group" href="https://lirkab.se">
                            <Image src="/assets/logos/lirkab.svg" alt="Lirkab" width={90} height={65} className="w-22.5 h-16.25 object-contain mb-5 drop-shadow-md group-hover:drop-shadow-lg dark:group-hover:drop-shadow-[0_0_10px_rgba(255,255,255,0.5)] transition-all dark:invert-0 filter invert" />
                            <span className="font-bold tracking-wide text-center">Lirkab</span>
                        </a>
                        <a className="w-full md:w-[calc(33.333%-32px)] no-underline text-slate-900 dark:text-white text-[22px] flex flex-col items-center hover:scale-105 transition-transform group" href="https://lerbergetsvolleyboll.se">
                            <Image src="/assets/logos/lvs.svg" alt="Lerbergets Volleyboll" width={90} height={65} className="w-22.5 h-16.25 object-contain mb-5 drop-shadow-md group-hover:drop-shadow-lg dark:group-hover:drop-shadow-[0_0_10px_rgba(255,255,255,0.5)] transition-all dark:invert-0 filter invert" />
                            <span className="font-bold tracking-wide text-center">Lerbergets Volleyboll</span>
                        </a>
                        <a className="w-full md:w-[calc(33.333%-32px)] no-underline text-slate-900 dark:text-white text-[22px] flex flex-col items-center hover:scale-105 transition-transform group" href="https://naturvardarna.com">
                            <Image src="/assets/logos/naturvardarna.svg" alt="Naturvärdarna Kullaberg" width={90} height={65} className="w-22.5 h-16.25 object-contain mb-5 drop-shadow-md group-hover:drop-shadow-lg dark:group-hover:drop-shadow-[0_0_10px_rgba(255,255,255,0.5)] transition-all dark:invert-0 filter invert" />
                            <span className="font-bold tracking-wide text-center">Naturvärdarna Kullaberg</span>
                        </a>
                    </div>
                </section>
            </div>
        </main>
    );
}