import React from 'react';
import { Page } from './_util';
import { useNavigate } from 'react-router-dom';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';

export default function LandingPage() {
  const nav = useNavigate();
  const [slug, setSlug] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  async function join() {
    const s = slug.trim();
    if (!s) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/v1/events/${encodeURIComponent(s)}`);
      if (!res.ok) {
        setError('Event nicht gefunden oder geschlossen.');
        return;
      }
      nav(`/e/${encodeURIComponent(s)}`);
    } catch (e) {
      setError('Netzwerkfehler. Bitte später erneut versuchen.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <Page title="Willkommen bei Fotochallenge 🎉">
      {error && (
        <Alert className="mb-3" variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}
      <Input
        value={slug}
        onChange={(e) => setSlug(e.target.value)}
        placeholder="QR/PIN oder Event-Slug eingeben"
      />
      <div className="h-3" />
      <Button disabled={loading || !slug.trim()} onClick={join}>
        {loading ? 'Prüfe…' : 'Event beitreten'}
      </Button>
    </Page>
  );
}
