---
import Layout from '../layouts/Layout.astro';

const GITEA_API_BASE_URL = 'https://git.teletype.hu/api/v1';
const GITEA_TOKEN = import.meta.env.WEBAPP_GITEA_TOKEN;

interface GiteaRepo {
  owner: {
    login: string;
  };
  name: string;
  description: string;
  language?: string;
  html_url: string;
  updated_at: string;
}

interface Commit {
  sha: string;
  message: string;
  author: { name: string; email: string; };
  date: string;
  url: string;
  repo: {
    owner: string;
    name: string;
    html_url: string;
  };
}

let allCommits: Commit[] = [];
let error: string | null = null;
let publicRepos: GiteaRepo[] = [];

if (!GITEA_TOKEN) {
  error = "Gitea API token (WEBAPP_GITEA_TOKEN) is not configured. Please set it in your .env file and docker-compose.yml.";
} else {
  try {
    // Step 1: Fetch public repositories
    const reposResponse = await fetch(`${GITEA_API_BASE_URL}/repos/search?q=&private=false&limit=50`, {
      headers: {
        'Authorization': `token ${GITEA_TOKEN}`,
        'Accept': 'application/json'
      }
    });

    if (!reposResponse.ok) {
      const errorText = await reposResponse.text();
      throw new Error(`Gitea API (repos/search) responded with status ${reposResponse.status}: ${errorText}`);
    }

    const reposData = await reposResponse.json();
    publicRepos = reposData.data || [];

    // Step 2: Fetch recent commits directly for each repository
    const commitPromises = publicRepos.map(async (repo) => {
      try {
        const commitsResponse = await fetch(
          `${GITEA_API_BASE_URL}/repos/${repo.owner.login}/${repo.name}/commits?limit=10&page=1`,
          {
            headers: {
              'Authorization': `token ${GITEA_TOKEN}`,
              'Accept': 'application/json'
            }
          }
        );

        if (!commitsResponse.ok) {
          console.warn(`Failed to fetch commits for ${repo.owner.login}/${repo.name}: ${commitsResponse.status}`);
          return [];
        }

        const commitsData = await commitsResponse.json();

        if (!Array.isArray(commitsData)) {
          console.warn(`Unexpected response for ${repo.owner.login}/${repo.name}:`, commitsData);
          return [];
        }

        const commits: Commit[] = commitsData.map((c: any) => ({
          sha: c.sha,
          message: c.commit?.message ?? '',
          author: {
            name: c.commit?.author?.name ?? 'Unknown',
            email: c.commit?.author?.email ?? '',
          },
          date: c.commit?.author?.date ?? c.created,
          url: c.html_url,
          repo: {
            owner: repo.owner.login,
            name: repo.name,
            html_url: repo.html_url,
          }
        }));

        return commits;
      } catch (repoCommitError: any) {
        console.warn(`Error fetching commits for ${repo.owner.login}/${repo.name}: ${repoCommitError.message}`);
        return [];
      }
    });

    const allCommitsArrays = await Promise.all(commitPromises);
    allCommits = allCommitsArrays.flat();

    // Step 3: Sort all commits by date descending
    allCommits.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  } catch (e: any) {
    console.error('Failed to fetch Gitea data:', e);
    error = `Failed to fetch Gitea data: ${e.message}`;
  }
}

// Limit to top 20 commits for display
const recentCommits = allCommits.slice(0, 20);
---

<Layout>
  <header class="hero-section-gradient from-teal-600 to-green-600 py-20">
    <div class="hero-container max-w-4xl">
      <h1 class="hero-title">Codebase</h1>
      <p class="hero-subtitle text-teal-50 mb-10">
        Explore our collection of open-source projects, study our source code, and contribute to our independent game development tools.
      </p>
      <a 
        href="https://git.teletype.hu" 
        target="_blank" 
        class="btn-hero-teal"
      >
        Open Gitea
      </a>
    </div>
  </header>

  <main class="main-container">
    {error && (
      <div class="error-alert" role="alert">
        <strong class="font-bold">Error!</strong>
        <span class="block sm:inline"> {error}</span>
      </div>
    )}

    {!error && publicRepos.length > 0 && (
      <div class="card-grid mb-16">
        {publicRepos.map((repo) => (
          <div class="card-base">
            <h3 class="repo-card-title">
              <a href={repo.html_url} target="_blank" class="repo-link">
                {repo.owner.login}/{repo.name}
              </a>
            </h3>
            {repo.description && <p class="repo-card-desc">{repo.description}</p>}
            {repo.language && <p class="repo-card-meta">Language: {repo.language}</p>}
            <p class="repo-card-meta">Updated: {new Date(repo.updated_at).toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'})}</p>
          </div>
        ))}
      </div>
    )}

    <h2 class="commits-section-title">Recent Commits</h2>

    {!error && recentCommits.length === 0 && (
      <p class="empty-commits-msg">No recent commits found or accessible from public repositories.</p>
    )}

    <div class="commits-list">
      {recentCommits.map((commit) => (
        <div class="commit-item">
          <div class="commit-icon">
            🚀
          </div>
          <div class="commit-content">
            <p class="commit-message">
              <a href={commit.repo.html_url} target="_blank" class="commit-repo-link">
                <span class="font-bold">{commit.repo.owner}</span> / <span class="font-bold">{commit.repo.name}</span>
              </a>
              : <span class="text-gray-700">{commit.message.split('\n')[0]}</span>
            </p>
            <p class="commit-meta">
              Authored by <span class="font-bold">{commit.author.name}</span> on {new Date(commit.date).toLocaleDateString('en-US', {
                year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
              })}
              <a href={commit.url} target="_blank" class="commit-sha-link">
                <span class="font-mono text-xs">{commit.sha.substring(0, 7)}</span>
              </a>
            </p>
          </div>
        </div>
      ))}
    </div>
  </main>
</Layout>

<style>
  .error-alert {
    @apply bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-8;
  }
  
  /* Repo Cards */
  .repo-card-title {
    @apply text-xl font-semibold mb-2;
  }
  .repo-link {
    @apply text-blue-600 hover:text-blue-800;
  }
  .repo-card-desc {
    @apply text-gray-700 text-sm;
  }
  .repo-card-meta {
    @apply text-gray-500 text-xs mt-1;
  }
  
  /* Commits */
  .commits-section-title {
    @apply text-3xl font-bold mb-8 text-center text-gray-800;
  }
  .empty-commits-msg {
    @apply text-center text-gray-600 text-lg;
  }
  .commits-list {
    @apply space-y-4 mb-12;
  }
  .commit-item {
    @apply bg-white shadow-lg rounded-lg p-4 flex items-center space-x-4 border border-gray-100;
  }
  .commit-icon {
    @apply flex-shrink-0 text-3xl;
  }
  .commit-content {
    @apply flex-grow;
  }
  .commit-message {
    @apply text-gray-800 font-semibold;
  }
  .commit-repo-link {
    @apply text-blue-600 hover:text-blue-800;
  }
  .commit-meta {
    @apply text-gray-600 text-sm mt-1;
  }
  .commit-sha-link {
    @apply ml-2 text-blue-500 hover:text-blue-700;
  }
</style>
