// /app/league/[code]/page.tsx
'use client'

import React, { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import Image from 'next/image'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { AlertCircle } from 'lucide-react'

interface Team {
  id: number
  name: string
  shortName: string
  tla: string
  crest: string
  venue: string
  website: string
  founded: number
  clubColors: string
}

interface League {
  id: number
  name: string
  code: string
  type: string
  emblem: string
  area: {
    id: number
    name: string
    code: string
    flag: string
  }
  currentSeason: {
    id: number
    startDate: string
    endDate: string
    currentMatchday: number
    winner: null | string
  }
}

interface LeagueData {
  league: League
  teams: Team[]
}

export default function LeaguePage() {
  const params = useParams()
  const { code } = params // Extract 'code' from URL
  const [leagueData, setLeagueData] = useState<LeagueData | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchLeagueData = async () => {
      try {
        const response = await fetch(`http://localhost:5000/api/league/${code}`)
        if (!response.ok) {
          if (response.status === 404) {
            throw new Error('League not found')
          }
          throw new Error('Failed to fetch league data')
        }
        const data: LeagueData = await response.json()
        setLeagueData(data)
      } catch (error) {
        console.error('Error fetching league data:', error)
        setError(error instanceof Error ? error.message : 'An error occurred')
      } finally {
        setIsLoading(false)
      }
    }

    if (code) {
      fetchLeagueData()
    }
  }, [code])

  if (isLoading) {
    return <LeagueSkeleton />
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertTitle>Error</AlertTitle>
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    )
  }

  if (!leagueData) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertTitle>Not Found</AlertTitle>
        <AlertDescription>League not found</AlertDescription>
      </Alert>
    )
  }

  const { league, teams } = leagueData

  return (
    <div className="container mx-auto px-4 py-8">
      <Card className="mb-8">
        <CardHeader className="flex flex-row items-center space-x-4">
          <div className="relative w-16 h-16">
            <Image
              src={league.emblem}
              alt={`${league.name} emblem`}
              width={64}
              height={64}
              className="rounded-full object-contain"
              onError={(e) => {
                const target = e.target as HTMLImageElement
                target.src = '/placeholder.svg'
              }}
            />
          </div>
          <div>
            <CardTitle>{league.name}</CardTitle>
            <p className="text-sm text-gray-500">{league.area.name}</p>
          </div>
        </CardHeader>
        <CardContent>
          <p><strong>Current Season:</strong> {league.currentSeason.startDate} to {league.currentSeason.endDate}</p>
          <p><strong>Current Matchday:</strong> {league.currentSeason.currentMatchday}</p>
        </CardContent>
      </Card>

      <h2 className="text-2xl font-bold mb-4">Teams</h2>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {teams.map((team) => (
          <Card key={team.id}>
            <CardHeader className="flex flex-row items-center space-x-4">
              <div className="relative w-12 h-12">
                <Image
                  src={team.crest}
                  alt={`${team.name} crest`}
                  width={48}
                  height={48}
                  className="rounded-full object-contain"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement
                    target.src = '/placeholder.svg'
                  }}
                />
              </div>
              <CardTitle className="text-lg">{team.name}</CardTitle>
            </CardHeader>
            <CardContent>
              <p><strong>Venue:</strong> {team.venue}</p>
              <p><strong>Founded:</strong> {team.founded}</p>
              <p><strong>Club Colors:</strong> {team.clubColors}</p>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}

function LeagueSkeleton() {
  return (
    <div className="container mx-auto px-4 py-8">
      <Card className="mb-8">
        <CardHeader className="flex flex-row items-center space-x-4">
          <Skeleton className="w-16 h-16 rounded-full" />
          <div>
            <Skeleton className="h-6 w-40 mb-2" />
            <Skeleton className="h-4 w-24" />
          </div>
        </CardHeader>
        <CardContent>
          <Skeleton className="h-4 w-full mb-2" />
          <Skeleton className="h-4 w-3/4" />
        </CardContent>
      </Card>

      <Skeleton className="h-8 w-40 mb-4" />
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {[...Array(6)].map((_, index) => (
          <Card key={index}>
            <CardHeader className="flex flex-row items-center space-x-4">
              <Skeleton className="w-12 h-12 rounded-full" />
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-4 w-full mb-2" />
              <Skeleton className="h-4 w-3/4 mb-2" />
              <Skeleton className="h-4 w-1/2" />
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}
Basically what I want that I need to delete [code] and league folder because it is not working , as data coming from leagueSelector.tsx is not routing here correctly 
I want you to make a file league.tsx and route it from leagueSelector.tsx I will provide leagueSelector.tsx file 
And I will provide backend file So that you can see what data is coming from backend and what is route to each controller 
// controllers/leagueController.js

const axios = require("axios");

/**
 * Fetches detailed information about a specific league and its teams.
 * Route: GET /leagues/:code
 * Example: GET /leagues/PL
 */
async function leagueController(req, res) {
  try {
    const leagueCode = req.params.code.toUpperCase(); // Ensure the league code is uppercase (e.g., 'PL')

    // Define the API endpoints
    const leagueInfoUrl = `https://api.football-data.org/v4/competitions/${leagueCode}`;
    const leagueTeamsUrl = `https://api.football-data.org/v4/competitions/${leagueCode}/teams`;

    // Make parallel API requests for league info and teams
    const [leagueResponse, teamsResponse] = await Promise.all([
      axios.get(leagueInfoUrl, {
        headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
      }),
      axios.get(leagueTeamsUrl, {
        headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
      }),
    ]);

    const leagueData = leagueResponse.data;
    const teamsData = teamsResponse.data.teams;

    // Structure the response
    res.status(200).json({
      league: {
        id: leagueData.id,
        name: leagueData.name,
        code: leagueData.code,
        type: leagueData.type,
        emblem: leagueData.emblem,
        area: leagueData.area,
        currentSeason: leagueData.currentSeason,
      },
      teams: teamsData.map((team) => ({
        id: team.id,
        name: team.name,
        shortName: team.shortName,
        tla: team.tla,
        crest: team.crest,
        venue: team.venue,
        website: team.website,
        founded: team.founded,
        clubColors: team.clubColors,
      })),
    });
  } catch (error) {
    console.error("Error fetching league data:", error.message);

    // Handle specific API errors
    if (error.response) {
      const { status, data } = error.response;
      return res.status(status).json({
        message: data.message || "Error fetching league data from API.",
      });
    }

    // Generic server error
    res.status(500).json({
      message: "Unable to retrieve league data. Please try again later.",
    });
  }
}

module.exports = leagueController;

// controllers/leaguesController.js

const axios = require("axios");

/**
 * Fetches a list of all available leagues (competitions).
 * Route: GET /leagues
 */
async function leaguesController(req, res) {
  try {
    const apiUrl = "https://api.football-data.org/v4/competitions";

    const response = await axios.get(apiUrl, {
      headers: { "X-Auth-Token": process.env.API_FOOTBALL_KEY1 },
      params: {
        plan: "TIER_ONE", // Optional: Filter competitions by plan if needed
      },
    });

    const competitions = response.data.competitions;

    // Map and structure the competitions data
    const leagues = competitions.map((competition) => ({
      id: competition.id,
      name: competition.name,
      code: competition.code,
      type: competition.type,
      emblem: competition.emblem,
      area: competition.area,
    }));

    res.status(200).json({
      count: leagues.length,
      leagues,
    });
  } catch (error) {
    console.error("Error fetching leagues data:", error.message);

    // Handle specific API errors
    if (error.response) {
      const { status, data } = error.response;
      return res.status(status).json({
        message: data.message || "Error fetching leagues data from API.",
      });
    }

    // Generic server error
    res.status(500).json({
      message: "Unable to retrieve leagues data. Please try again later.",
    });
  }
}

module.exports = leaguesController;

// routes/leagueRoutes.js

const express = require("express");
const router = express.Router();
const leagueController = require("../controllers/leagueController");

// Route to get information about a specific league and its teams
router.get("/:code", leagueController);

module.exports = router;

// routes/leaguesRoutes.js

const express = require("express");
const router = express.Router();
const leaguesController = require("../controllers/leaguesController");

// Route to get a list of all leagues
router.get("/", leaguesController);

module.exports = router;


require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const newsRoutes = require("./routes/newsRoutes");
const scoreRoutes = require("./routes/scoreRoutes");
const taskQueue = require("./taskQueue/matchUpdateQueue");
const standingsRoutes = require("./routes/standingsRoutes");
const fixturesRouter = require("./routes/fixturesRouter");
const leagueRoutes = require("./routes/leagueRoutes"); // New
const leaguesRoutes = require("./routes/leaguesRoutes"); // New
const cors = require("cors");

const app = express();

// CORS configuration
app.use(
  cors({
    origin: "http://localhost:3000", // Replace with your frontend URL
    methods: ["GET", "POST", "PUT", "DELETE"],
    allowedHeaders: ["Content-Type", "Authorization"],
  })
);

const PORT = process.env.PORT || 5000;

// Connect to MongoDB
mongoose
  .connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("Connected to MongoDB"))
  .catch((err) => console.error("MongoDB connection error:", err));

// Middleware
app.use(express.json());

// Routes
app.use("/api/news", newsRoutes);
app.use("/api/scores", scoreRoutes);
app.use("/api", standingsRoutes);
app.use("/api", fixturesRouter);
app.use("/api/leagues", leaguesRoutes);
app.use("/api/league", leagueRoutes);

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("Something broke!");
});

// Test route
app.get("/api/test", (req, res) => {
  res.json({ message: "Test route working" });
});

// Start server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

// Start task queue worker (for fetching live scores)
taskQueue.start();

module.exports = app; // Export for testing purposes


Finally 
// /app/components/LeagueSelector.tsx
'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { AlertCircle } from 'lucide-react'
import Link from 'next/link'
import Image from 'next/image'

interface League {
  id: number
  name: string
  code: string
  type: string
  emblem: string
  area: {
    id: number
    name: string
    code: string
    flag: string | null
  }
}

interface LeaguesResponse {
  count: number
  leagues: League[]
}

export default function LeagueSelector() {
  const [leagues, setLeagues] = useState<League[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchLeagues = async () => {
      try {
        const response = await fetch('http://localhost:5000/api/leagues')
        if (!response.ok) {
          throw new Error('Failed to fetch leagues')
        }
        const data: LeaguesResponse = await response.json()
        setLeagues(data.leagues)
      } catch (error) {
        console.error('Error fetching leagues:', error)
        setError('Failed to load leagues. Please try again later.')
      } finally {
        setIsLoading(false)
      }
    }

    fetchLeagues()
  }, [])

  if (isLoading) {
    return <LeagueSkeleton />
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertTitle>Error</AlertTitle>
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    )
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {leagues.map((league) => (
        <Link
          href={`/league/${league.code}`} // Navigate using league.code
          key={league.code}
          className="focus:outline-none focus:ring-2 focus:ring-blue-500 rounded-lg"
        >
          <Card className="hover:shadow-lg transition-shadow duration-300">
            <CardHeader className="flex flex-row items-center space-x-4">
              <div className="relative w-12 h-12">
                <Image
                  src={league.emblem}
                  alt={`${league.name} emblem`}
                  width={48}
                  height={48}
                  className="rounded-full object-contain"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement
                    target.src = '/placeholder.svg'
                  }}
                />
              </div>
              <CardTitle className="text-lg">{league.name}</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-gray-500">{league.area.name}</p>
              <p className="text-sm text-gray-500">{league.type}</p>
            </CardContent>
          </Card>
        </Link>
      ))}
    </div>
  )
}

function LeagueSkeleton() {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {[...Array(6)].map((_, index) => (
        <Card key={index}>
          <CardHeader className="flex flex-row items-center space-x-4">
            <Skeleton className="w-12 h-12 rounded-full" />
            <Skeleton className="h-6 w-32" />
          </CardHeader>
          <CardContent>
            <Skeleton className="h-4 w-full mb-2" />
            <Skeleton className="h-4 w-3/4" />
          </CardContent>
        </Card>
      ))}
    </div>
  )
}
This is my league selector