---
import Layout from '../layouts/Layout.astro';
import fs from 'node:fs';
import path from 'node:path';
import yaml from 'js-yaml';

interface Event {
  name: string;
  date: string;
}

interface EventData {
  events: Event[];
}

let nextEvent: (Event & { dateISO: string; dateText: string }) | null = null;
let followingEvents: (Event & { dateText: string })[] = [];

try {
  const rootDir = process.cwd();
  let eventsPath = path.join(rootDir, 'src', 'events.yaml');
  if (!fs.existsSync(eventsPath)) {
    eventsPath = path.join(rootDir, 'src', 'events-example.yaml');
  }

  if (fs.existsSync(eventsPath)) {
    const fileContents = fs.readFileSync(eventsPath, 'utf8');
    const data = yaml.load(fileContents) as EventData;
    
    if (data && data.events) {
      const now = new Date();
      const futureEvents = data.events
        .map(e => ({
          ...e,
          dateObj: new Date(e.date)
        }))
        .filter(e => e.dateObj > now)
        .sort((a, b) => a.dateObj.getTime() - b.dateObj.getTime());

      if (futureEvents.length > 0) {
        const first = futureEvents[0];
        nextEvent = {
          name: first.name,
          date: first.date,
          dateISO: first.dateObj.toISOString(),
          dateText: first.dateObj.toLocaleString('en-US', { 
            year: 'numeric', month: 'short', day: 'numeric', 
            hour: '2-digit', minute: '2-digit' 
          })
        };

        followingEvents = futureEvents.slice(1).map(e => ({
          name: e.name,
          date: e.date,
          dateText: e.dateObj.toLocaleString('en-US', { 
            year: 'numeric', month: 'short', day: 'numeric', 
            hour: '2-digit', minute: '2-digit' 
          })
        }));
      }
    }
  }
} catch (e) {
  console.error('Failed to load events:', e);
}
---

<Layout>
  <div class="home-container">
    <!-- Header Section -->
    <header class="hero-section-slate">
      <div class="home-header-decor">
        <div class="hero-decor-blob -top-24 -left-24 h-96 w-96 bg-indigo-600"></div>
        <div class="hero-decor-blob -bottom-24 -right-24 h-96 w-96 bg-purple-600"></div>
      </div>
      
      <div class="hero-container">
        <div class="hero-badge">
          Welcome to
        </div>
        <h1 class="hero-title">
          Teletype <span class="text-transparent bg-clip-text bg-gradient-to-r from-violet-400 to-fuchsia-400">Games</span>
        </h1>
        <p class="hero-subtitle">
          Teletype Games is an independent game development community built on creative freedom, equality, and an open-source mindset. Our goal is to create experimental and full-fledged games with short development cycles.
        </p>
      </div>
    </header>

    <main class="main-container max-w-6xl">
      <!-- Countdown Section -->
      {nextEvent && (
        <section class="mb-12">
          <div class="countdown-card">
            <h2 class="countdown-event-name">{nextEvent.name}</h2>
            <div id="countdown" data-date={nextEvent.dateISO} class="countdown-timer">
              -- : -- : -- : --
            </div>
            <p class="countdown-date">Starts on: <span class="font-semibold">{nextEvent.dateText}</span></p>

            {followingEvents.length > 0 && (
              <div class="upcoming-events-section">
                <h3 class="upcoming-events-title">Upcoming Events</h3>
                <div class="space-y-4">
                  {followingEvents.map(event => (
                    <div class="upcoming-event-item">
                      <span class="font-bold text-gray-800">{event.name}</span>
                      <span class="text-sm text-gray-500 font-mono">{event.dateText}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </section>
      )}

      <!-- Navigation Grid -->
      <section class="card-grid">
        <!-- Catalog Section -->
        <div class="nav-card group card-interactive">
          <div class="nav-card-icon bg-purple-50 group-hover:bg-purple-100">
            <span class="text-3xl">🎮</span>
          </div>
          <h2 class="nav-card-title">Catalog</h2>
          <p class="nav-card-desc">Here you can find our games. Discover our creations for TIC-80 and other platforms, many of which you can try directly in your browser.</p>
          <a href="/catalog" class="btn-primary bg-purple-600 hover:bg-purple-700 text-white hover:shadow-purple-200">
            Browse Games
          </a>
        </div>

        <!-- Wiki Section -->
        <div class="nav-card group card-interactive">
          <div class="nav-card-icon bg-green-50 group-hover:bg-green-100">
            <span class="text-3xl">📚</span>
          </div>
          <h2 class="nav-card-title">Wiki</h2>
          <p class="nav-card-desc">We gather our public interest development knowledge here. Read through technical descriptions and development logs.</p>
          <a href="https://wiki.teletype.hu" target="_blank" rel="noopener noreferrer" class="btn-primary bg-green-600 hover:bg-green-700 text-white hover:shadow-green-200">
            Knowledge Base
          </a>
        </div>

        <!-- Git Section -->
        <div class="nav-card group card-interactive">
          <div class="nav-card-icon bg-slate-50 group-hover:bg-slate-100">
            <span class="text-3xl">💻</span>
          </div>
          <h2 class="nav-card-title">Git Repos</h2>
          <p class="nav-card-desc">All our projects are open source. Browse our code, study our solutions, or even participate in the development.</p>
          <a href="https://git.teletype.hu" target="_blank" rel="noopener noreferrer" class="btn-primary bg-slate-800 hover:bg-slate-900 text-white hover:shadow-slate-200">
            Gitea
          </a>
        </div>
      </section>
      <!-- AI Content Notice -->
      <div class="mb-12 mt-12 bg-white rounded-2xl border border-indigo-100 p-6 shadow-sm flex items-center gap-4">
        <div class="w-12 h-12 rounded-full bg-indigo-50 flex items-center justify-center text-2xl flex-shrink-0">🤖</div>
        <div class="flex-grow text-slate-600 text-sm md:text-base italic">
          <strong>Note:</strong> Our HowTo-s and blog posts are written by AI with human supervision.
        </div>
      </div>
    </main>
  </div>
</Layout>

<style>
  .home-container {
    @apply bg-gray-50 min-h-screen pb-20;
  }
  .home-header-decor {
    @apply absolute inset-0 opacity-30;
  }
  
  /* Countdown Card */
  .countdown-card {
    @apply bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100 p-8 md:p-12 text-center transition-all duration-300;
  }
  .countdown-event-name {
    @apply text-2xl font-bold text-gray-400 uppercase tracking-widest mb-2;
  }
  .countdown-timer {
    @apply text-5xl md:text-7xl font-mono font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-600 to-fuchsia-600 my-6;
  }
  .countdown-date {
    @apply text-gray-500 text-lg;
  }
  
  /* Upcoming Events */
  .upcoming-events-section {
    @apply mt-12 pt-12 border-t border-gray-100 text-left max-w-2xl mx-auto;
  }
  .upcoming-events-title {
    @apply text-xl font-bold text-gray-900 mb-6;
  }
  .upcoming-event-item {
    @apply flex items-center justify-between p-4 bg-gray-50 rounded-xl border border-gray-100;
  }

  /* Nav Cards */
  .nav-card {
    @apply flex flex-col h-full;
  }
  .nav-card-icon {
    @apply w-14 h-14 rounded-xl flex items-center justify-center mb-6 transition-colors;
  }
  .nav-card-title {
    @apply text-2xl font-bold text-gray-900 mb-3;
  }
  .nav-card-desc {
    @apply text-gray-600 mb-6 flex-grow leading-relaxed;
  }
</style>

<script>
  function updateCountdown() {
    const countdownElement = document.getElementById('countdown');
    if (!countdownElement) return;

    const targetDateStr = countdownElement.getAttribute('data-date');
    if (!targetDateStr) return;

    const targetDate = new Date(targetDateStr).getTime();

    function update() {
      const now = Date.now();
      const distance = targetDate - now;

      if (distance < 0) {
        countdownElement.innerHTML = "LIVE NOW!";
        return;
      }

      const days = Math.floor(distance / (1000 * 60 * 60 * 24));
      const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((distance % (1000 * 60)) / 1000);

      const d = String(days).padStart(2, '0');
      const h = String(hours).padStart(2, '0');
      const m = String(minutes).padStart(2, '0');
      const s = String(seconds).padStart(2, '0');

      countdownElement.innerHTML = `${d}d ${h}h ${m}m ${s}s`;
    }

    update();
    setInterval(update, 1000);
  }

  // Initialize countdown
  updateCountdown();
</script>
