// component/FootballDashboard.tsx
'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Button } from "@/components/ui/button"
import { RefreshCw, Play, LogIn, LogOut } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import LiveScore from './LiveScore'
import LeagueSelector from './LeagueSelector'
import NewsArticles from './NewsArticles'
import PlayerSearch from './PlayerSearch'
import TeamHistory from './TeamHistory'
import FantasySports from './FantasySports'
import VideoContent from './VideoContent'
import AdminDashboard from './AdminDashboard'

const API_BASE_URL = 'http://localhost:5000'

export default function HomePage() {
  const [liveScores, setLiveScores] = useState<{ [key: string]: any[] } | null>(null)
  const [articles, setArticles] = useState<any[]>([])
  const [videos, setVideos] = useState<any[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [isAdmin, setIsAdmin] = useState(false)

  useEffect(() => {
    const token = localStorage.getItem('adminToken')
    setIsAdmin(!!token)

    const fetchData = async () => {
      setIsLoading(true)
      try {
        const [scoresRes, articlesRes, videosRes] = await Promise.all([
          fetch(`${API_BASE_URL}/api/scores`),
          fetch(`${API_BASE_URL}/api/articles`),
          fetch(`${API_BASE_URL}/api/videos/recent`)
        ])

        const scoresData = await scoresRes.json()
        const articlesData = await articlesRes.json()
        const videosData = await videosRes.json()

        setLiveScores(scoresData.data || {})
        setArticles(articlesData.slice(0, 5)) // Limit to 5 articles
        setVideos(videosData.response.slice(0, 3)) // Limit to 3 videos
        setError(null)
      } catch (error) {
        console.error("Fetching error:", error)
        setError("Failed to load data. Please try again later.")
      } finally {
        setIsLoading(false)
      }
    }

    fetchData()
    const intervalId = setInterval(fetchData, 60000) // Refresh every minute
    return () => clearInterval(intervalId)
  }, [])

  const handleLogout = () => {
    localStorage.removeItem('adminToken')
    setIsAdmin(false)
  }

  const MatchRow = ({ match }: { match: any }) => (
    <div className="flex items-center justify-between py-2 px-4 border-b last:border-b-0">
      <div className="flex items-center space-x-2 w-5/12">
        <Image src={match.homeTeam.crest} alt={match.homeTeam.name} width={24} height={24} className="rounded-full" />
        <span className="font-medium text-sm">{match.homeTeam.shortName}</span>
      </div>
      <div className="flex flex-col items-center w-2/12">
        <div className="text-sm font-bold">
         {match.score.fullTime.home != null ? match.score.fullTime.home : '-'} - 
          {match.score.fullTime.away != null ? match.score.fullTime.away : '-'}
        </div>
        <div className="text-xs text-gray-500">
          {match.status === 'FINISHED' ? 'FT' : match.status === 'IN_PLAY' ? "LIVE" : ""}
        </div>
      </div>
      <div className="flex items-center justify-end space-x-2 w-5/12">
        <span className="font-medium text-sm">{match.awayTeam.shortName}</span>
        <Image src={match.awayTeam.crest} alt={match.awayTeam.name} width={24} height={24} className="rounded-full" />
      </div>
    </div>
  )

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-4xl font-bold">FootballBuzz</h1>
        {isAdmin ? (
          <Button onClick={handleLogout} variant="outline">
            <LogOut className="mr-2 h-4 w-4" /> Logout
          </Button>
        ) : (
          <Link href="/admin/login">
            <Button variant="outline">
              <LogIn className="mr-2 h-4 w-4" /> Admin Login
            </Button>
          </Link>
        )}
      </div>

      <Tabs defaultValue="home">
        <TabsList className="mb-6">
          <TabsTrigger value="home">Home</TabsTrigger>
          <TabsTrigger value="liveScore">Live Score</TabsTrigger>
          <TabsTrigger value="leagues">Leagues</TabsTrigger>
          <TabsTrigger value="news">News</TabsTrigger>
          <TabsTrigger value="players">Players</TabsTrigger>
          <TabsTrigger value="teams">Teams</TabsTrigger>
          <TabsTrigger value="fantasy">Fantasy</TabsTrigger>
          <TabsTrigger value="videos">Videos</TabsTrigger>
          {isAdmin && <TabsTrigger value="admin">Admin</TabsTrigger>}
        </TabsList>

        <TabsContent value="home">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Live Scores Section */}
            <div className="lg:col-span-2">
              <Card className="mb-8">
                <CardHeader className="flex flex-row items-center justify-between pb-2">
                  <CardTitle className="text-2xl font-bold">Live Scores</CardTitle>
                  <Button variant="ghost" size="sm" onClick={() => window.location.reload()}>
                    <RefreshCw size={16} />
                  </Button>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-[400px] pr-4">
                    {isLoading ? (
                      <p>Loading live scores...</p>
                    ) : error ? (
                      <p className="text-red-500">{error}</p>
                    ) : liveScores && Object.keys(liveScores).length > 0 ? (
                      Object.entries(liveScores).map(([league, matches]) => (
                        <div key={league} className="mb-4">
                          <h3 className="font-semibold text-lg mb-2">{league}</h3>
                          {Array.isArray(matches) ? (
                            matches.map((match: any) => (
                              <MatchRow key={match.id} match={match} />
                            ))
                          ) : (
                            <p className="text-red-500">Invalid data format for league: {league}</p>
                          )}
                        </div>
                      ))
                    ) : (
                      <p>No live scores available at the moment.</p>
                    )}
                  </ScrollArea>
                </CardContent>
              </Card>

              {/* News Articles Section */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-2xl font-bold">Latest News</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {articles.map(article => (
                      <Card key={article.id} className="overflow-hidden">
                        <Image src={article.headingImage} alt={article.title} width={300} height={200} className="w-full h-40 object-cover" />
                        <CardContent className="p-4">
                          <h3 className="font-semibold text-lg mb-2">{article.title}</h3>
                          <p className="text-sm text-gray-600">{article.content.substring(0, 100)}...</p>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Videos Section */}
            <div>
              <Card>
                <CardHeader>
                  <CardTitle className="text-2xl font-bold">Featured Videos</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {videos.map(video => (
                      <div key={video.id} className="relative">
                        <Image src={video.thumbnail} alt={video.title} width={300} height={200} className="w-full rounded-lg" />
                        <div className="absolute inset-0 flex items-center justify-center">
                          <Play className="h-12 w-12 text-white bg-black bg-opacity-50 rounded-full p-3" />
                        </div>
                        <h4 className="mt-2 font-semibold">{video.title}</h4>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="liveScore">
          <LiveScore />
        </TabsContent>
        <TabsContent value="leagues">
          <LeagueSelector />
        </TabsContent>
        <TabsContent value="news">
          <NewsArticles />
        </TabsContent>
        <TabsContent value="players">
          <PlayerSearch />
        </TabsContent>
        <TabsContent value="teams">
          <TeamHistory />
        </TabsContent>
        <TabsContent value="fantasy">
          <FantasySports />
        </TabsContent>
        <TabsContent value="videos">
          <VideoContent />
        </TabsContent>
        {isAdmin && (
          <TabsContent value="admin">
            <AdminDashboard />
          </TabsContent>
        )}
      </Tabs>
    </div>
  )
}
This is football Dashboard 
Other than error there is problem with images kinda of not seeing image that is uploaded and 
Unhandled Runtime Error
TypeError: article.content.substring is not a function

Source
component\FootballDashboard.tsx (171:81) @ substring

  169 |                         <CardContent className="p-4">
  170 |                           <h3 className="font-semibold text-lg mb-2">{article.title}</h3>
> 171 |                           <p className="text-sm text-gray-600">{article.content.substring(0, 100)}...</p>
      |                                                                                 ^
  172 |                         </CardContent>
  173 |                       </Card>
  174 |                     ))}
Call Stack
Show collapsed frames
Remove this error 
const Article = require("../models/Article");
const { handleControllerError } = require("../utils/errorHandler");

// Function to handle uploading a new article
const addArticle = async (req, res) => {
  try {
    const { title, content, author } = req.body;
    const headingImage = req.file ? `/uploads/${req.file.filename}` : null;

    if (!title || !content || !author) {
      return res.status(400).json({ message: "All fields are required." });
    }

    const newArticle = new Article({
      title,
      content,
      author,
      headingImage,
    });

    await newArticle.save();

    res
      .status(201)
      .json({
        message: "Article uploaded successfully.",
        articleId: newArticle._id,
      });
  } catch (error) {
    handleControllerError(error, res, "addArticle");
  }
};

// Function to fetch all articles
const getArticles = async (req, res) => {
  try {
    const articles = await Article.find().sort({ createdAt: -1 });
    res.json(articles);
  } catch (error) {
    handleControllerError(error, res, "getArticles");
  }
};

// Function to fetch a single article by ID
const getArticleById = async (req, res) => {
  try {
    const { id } = req.params;
    const article = await Article.findById(id);

    if (!article) {
      return res.status(404).json({ message: "Article not found." });
    }

    res.json(article);
  } catch (error) {
    handleControllerError(error, res, "getArticleById");
  }
};

module.exports = {
  getArticles,
  addArticle,
  getArticleById,
};

This is articleController.js


// controllers/adminController.js
const Article = require("../models/Article");
const News = require("../models/News");
const { handleControllerError } = require("../utils/errorHandler");
const fs = require("fs");
const path = require("path");

// Helper function to delete files
const deleteFile = (filePath) => {
  fs.unlink(path.join(__dirname, "..", filePath), (err) => {
    if (err) console.error(`Failed to delete file ${filePath}:`, err);
  });
};

// --- Articles CRUD Operations ---

// Create a new article
const addArticle = async (req, res) => {
  try {
    const { title, content, author } = req.body;
    const headingImage = req.file ? `/uploads/${req.file.filename}` : null;

    if (!title || !content || !author) {
      return res.status(400).json({ message: "All fields are required." });
    }

    const newArticle = new Article({
      title,
      content,
      author,
      headingImage,
      createdBy: req.admin._id,
    });

    await newArticle.save();

    res.status(201).json({
      message: "Article created successfully.",
      article: newArticle,
    });
  } catch (error) {
    handleControllerError(error, res, "addArticle");
  }
};

// Get all articles
const getAllArticles = async (req, res) => {
  try {
    const articles = await Article.find()
      .populate("createdBy", "username")
      .sort({ createdAt: -1 });
    res.json(articles);
  } catch (error) {
    handleControllerError(error, res, "getAllArticles");
  }
};

// Get a single article by ID
const getArticleById = async (req, res) => {
  try {
    const { id } = req.params;
    const article = await Article.findById(id).populate(
      "createdBy",
      "username"
    );

    if (!article) {
      return res.status(404).json({ message: "Article not found." });
    }

    res.json(article);
  } catch (error) {
    handleControllerError(error, res, "getArticleById");
  }
};

// Update an existing article
const updateArticle = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content, author } = req.body;
    let headingImage;

    const article = await Article.findById(id);
    if (!article) {
      return res.status(404).json({ message: "Article not found." });
    }

    if (req.file) {
      // Delete the old image if it exists
      if (article.headingImage) {
        deleteFile(article.headingImage);
      }
      headingImage = `/uploads/${req.file.filename}`;
      article.headingImage = headingImage;
    }

    // Update fields if provided
    if (title) article.title = title;
    if (content) article.content = content;
    if (author) article.author = author;

    await article.save();

    res.json({ message: "Article updated successfully.", article });
  } catch (error) {
    handleControllerError(error, res, "updateArticle");
  }
};

// Delete an article
const deleteArticle = async (req, res) => {
  try {
    const { id } = req.params;

    const article = await Article.findByIdAndDelete(id);
    if (!article) {
      return res.status(404).json({ message: "Article not found." });
    }

    // Delete the heading image if it exists
    if (article.headingImage) {
      deleteFile(article.headingImage);
    }

    res.json({ message: "Article deleted successfully." });
  } catch (error) {
    handleControllerError(error, res, "deleteArticle");
  }
};
const reviewArticle = async (req, res) => {
  try {
    const { id } = req.params;
    const { review } = req.body;

    const article = await Article.findById(id);
    if (!article) {
      return res.status(404).json({ message: "Article not found." });
    }

    // Assuming you have a reviews array in your Article model
    article.reviews.push({
      reviewer: req.admin._id,
      review,
      reviewedAt: new Date(),
    });

    await article.save();

    res
      .status(200)
      .json({ message: "Article reviewed successfully.", article });
  } catch (error) {
    handleControllerError(error, res, "reviewArticle");
  }
};


// --- News CRUD Operations ---

// Create a new news item
const addNews = async (req, res) => {
  try {
    const { title, content } = req.body;
    const headingImage = req.files["headingImage"]
      ? `/uploads/${req.files["headingImage"][0].filename}`
      : null;
    const images = req.files["images"]
      ? req.files["images"].map((file) => `/uploads/${file.filename}`)
      : [];

    if (!title || !content) {
      return res
        .status(400)
        .json({ message: "Title and content are required." });
    }

    const newNews = new News({
      title,
      content,
      headingImage,
      images,
      createdBy: req.admin._id,
    });

    await newNews.save();

    res.status(201).json({
      message: "News created successfully.",
      news: newNews,
    });
  } catch (error) {
    handleControllerError(error, res, "addNews");
  }
};

// Get all news
const getAllNews = async (req, res) => {
  try {
    const newsList = await News.find()
      .populate("createdBy", "username")
      .sort({ createdAt: -1 });
    res.json(newsList);
  } catch (error) {
    handleControllerError(error, res, "getAllNews");
  }
};

// Get a single news item by ID
const getNewsById = async (req, res) => {
  try {
    const { id } = req.params;
    const news = await News.findById(id).populate("createdBy", "username");

    if (!news) {
      return res.status(404).json({ message: "News not found." });
    }

    res.json(news);
  } catch (error) {
    handleControllerError(error, res, "getNewsById");
  }
};

// Update an existing news item
const updateNews = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content } = req.body;
    let headingImage;
    let images;

    const news = await News.findById(id);
    if (!news) {
      return res.status(404).json({ message: "News not found." });
    }

    if (req.files["headingImage"]) {
      // Delete the old heading image if it exists
      if (news.headingImage) {
        deleteFile(news.headingImage);
      }
      headingImage = `/uploads/${req.files["headingImage"][0].filename}`;
      news.headingImage = headingImage;
    }

    if (req.files["images"] && req.files["images"].length > 0) {
      // Optionally delete old carousel images
      news.images.forEach((img) => deleteFile(img));
      images = req.files["images"].map((file) => `/uploads/${file.filename}`);
      news.images = images;
    }

    // Update fields if provided
    if (title) news.title = title;
    if (content) news.content = content;

    await news.save();

    res.json({ message: "News updated successfully.", news });
  } catch (error) {
    handleControllerError(error, res, "updateNews");
  }
};

// Delete a news item
const deleteNews = async (req, res) => {
  try {
    const { id } = req.params;

    const news = await News.findByIdAndDelete(id);
    if (!news) {
      return res.status(404).json({ message: "News not found." });
    }

    // Delete heading and carousel images if they exist
    if (news.headingImage) {
      deleteFile(news.headingImage);
    }
    news.images.forEach((img) => deleteFile(img));

    res.json({ message: "News deleted successfully." });
  } catch (error) {
    handleControllerError(error, res, "deleteNews");
  }
};

module.exports = {
  // Articles
  addArticle,
  getAllArticles,
  getArticleById,
  updateArticle,
  deleteArticle,

  // News
  addNews,
  getAllNews,
  getNewsById,
  updateNews,
  deleteNews,
  reviewArticle,
};

// controllers/newsController.js

const { getCachedData } = require("../utils/cacheHelper");
const axiosInstance = require("../utils/axiosInstance");

// Centralized Error Handling for Controller
const handleControllerError = (error, res, functionName) => {
  if (error.response) {
    // API responded with a status code outside 2xx
    console.error(
      `Error in ${functionName}: ${error.response.status} - ${JSON.stringify(
        error.response.data
      )}`
    );
    res.status(error.response.status).json({
      message: error.response.data.message || `Error in ${functionName}`,
      details: error.response.data,
    });
  } else if (error.request) {
    // No response received from API
    console.error(`No response received in ${functionName}:`, error.request);
    res.status(503).json({
      message: `No response from Football API during ${functionName}`,
    });
  } else {
    // Other errors
    console.error(`Error in ${functionName}:`, error.message);
    res
      .status(500)
      .json({ message: `Internal server error in ${functionName}` });
  }
};

// Function to fetch top 10 players for a specific club
const getTopPlayersByClub = async (req, res) => {
  const { club } = req.params; // e.g., 'barcelona', 'realmadrid'
  const cacheKey = `top_players_${club.toLowerCase()}`;
  const fetchFn = async () => {
    try {
      const response = await axiosInstance.get(
        `/players/${encodeURIComponent(club.toLowerCase())}`
      );
      // Assuming the API returns an array of player objects
      const topPlayers = response.data.slice(0, 10); // Get top 10 players
      return topPlayers;
    } catch (error) {
      throw error;
    }
  };

  try {
    const topPlayers = await getCachedData(cacheKey, fetchFn);
    res.status(200).json({
      club: club.charAt(0).toUpperCase() + club.slice(1),
      topPlayers,
    });
  } catch (error) {
    handleControllerError(error, res, `getTopPlayersByClub ${club}`);
  }
};

// Existing functions (getAllPlayers, getPlayersTransfers, etc.)

const getAllPlayers = async (req, res) => {
  const cacheKey = "all_players";
  const fetchFn = async () => {
    const response = await axiosInstance.get("/players");
    return response.data; // Assuming it's an array of players
  };

  try {
    const players = await getCachedData(cacheKey, fetchFn);
    res.status(200).json(players);
  } catch (error) {
    handleControllerError(error, res, "getAllPlayers");
  }
};

const getPlayersTransfers = async (req, res) => {
  const cacheKey = "players_transfers";
  const fetchFn = async () => {
    const response = await axiosInstance.get("/players/transfers");
    return response.data; // Assuming it's an array of transfers
  };

  try {
    const transfers = await getCachedData(cacheKey, fetchFn);
    res.status(200).json(transfers);
  } catch (error) {
    handleControllerError(error, res, "getPlayersTransfers");
  }
};

const getPlayersNews = async (req, res) => {
  const cacheKey = "players_news";
  const fetchFn = async () => {
    const response = await axiosInstance.get("/players/news");
    return response.data; // Assuming it's an array of news articles
  };

  try {
    const news = await getCachedData(cacheKey, fetchFn);
    res.status(200).json(news);
  } catch (error) {
    handleControllerError(error, res, "getPlayersNews");
  }
};

const getBettingLaLiga = async (req, res) => {
  const cacheKey = "betting_laliga";
  const fetchFn = async () => {
    const response = await axiosInstance.get("/betting/laliga");
    return response.data; // Assuming it's betting information
  };

  try {
    const laLigaData = await getCachedData(cacheKey, fetchFn);
    res.status(200).json(laLigaData);
  } catch (error) {
    handleControllerError(error, res, "getBettingLaLiga");
  }
};

const getBettingPremierLeague = async (req, res) => {
  const cacheKey = "betting_premierleague";
  const fetchFn = async () => {
    const response = await axiosInstance.get("/betting/premuire-league"); // Fixed endpoint spelling
    return response.data; // Assuming it's betting information
  };

  try {
    const premierLeagueData = await getCachedData(cacheKey, fetchFn);
    res.status(200).json(premierLeagueData);
  } catch (error) {
    handleControllerError(error, res, "getBettingPremierLeague");
  }
};

// ... other functions as needed

module.exports = {
  getAllPlayers,
  getPlayersTransfers,
  getPlayersNews,
  getTopPlayersByClub,
  getBettingLaLiga,
  getBettingPremierLeague,
  // ... other exports
};
// middlewares/upload.js
const multer = require("multer");
const path = require("path");

// Define storage for uploaded files
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/"); // Ensure this directory exists
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  },
});

// File filter to accept only images and GIFs
const fileFilter = (req, file, cb) => {
  const allowedTypes = /jpeg|jpg|png|gif/;
  const extname = allowedTypes.test(
    path.extname(file.originalname).toLowerCase()
  );
  const mimetype = allowedTypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  }
  cb(new Error("Only images and GIFs are allowed"));
};

// Initialize multer
const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit, adjust as needed
});

module.exports = upload;

// models/Article.js
const mongoose = require("mongoose");

const ContentBlockSchema = new mongoose.Schema({
  type: {
    type: String,
    enum: [
      "heading1",
      "heading2",
      "heading3",
      "heading4",
      "paragraph",
      "image",
      "carousel",
      "gif",
      "bulletList",
      "numberList",
      "link",
      "blockCode",
    ],
    required: true,
  },
  data: mongoose.Schema.Types.Mixed, // Flexible to store different data based on type
});

const ArticleSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    author: {
      // Depending on your needs, this can reference the Admin
      type: String,
      required: true,
    },
    content: [ContentBlockSchema],
    headingImage: {
      type: String,
    },
    createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "Admin" },
    status: {
      // To track if article is published, under review, etc.
      type: String,
      enum: ["draft", "under_review", "published"],
      default: "draft",
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Article", ArticleSchema);


// routes/articleRoutes.js

const express = require("express");
const {
  getAllArticles, // Corrected function name
  addArticle,
  getArticleById,
} = require("../controllers/adminController"); // Corrected path if using adminController.js

const router = express.Router();
const fs = require("fs");
const authenticateToken = require("../middlewares/authMiddleware");
const multer = require("multer");
const path = require("path");

// Configure Multer for file uploads
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/"); // Temporary upload directory
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    cb(null, `${uniqueSuffix}-${file.originalname}`);
  },
});

const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // Limit file size to 5MB
  fileFilter: (req, file, cb) => {
    const filetypes = /jpeg|jpg|png|gif/;
    const mimetype = filetypes.test(file.mimetype);
    const extname = filetypes.test(
      path.extname(file.originalname).toLowerCase()
    );

    if (mimetype && extname) {
      return cb(null, true);
    }
    cb(new Error("Only image files are allowed!"));
  },
});

// Routes for user articles
router.get("/", getAllArticles); // Updated to match the controller function name
router.post(
  "/add",
  authenticateToken,
  upload.single("headingImage"),
  addArticle
); // POST /api/articles/add
router.get("/:id", getArticleById); // GET /api/articles/:id

module.exports = router;
// routes/admin.js
const express = require("express");
const router = express.Router();
const adminController = require("../controllers/adminController");
const { verifyToken } = require("../middlewares/auth");
const authorizeRoles = require("../middlewares/authorizeRoles");
const upload = require("../middlewares/upload");

// Protect all admin routes
router.use(verifyToken);
router.use(authorizeRoles("admin", "superuser"));

// --- Article Routes ---

// Publishers can create and update articles
router.post(
  "/articles",
  authorizeRoles("publisher", "admin", "superuser"),
  upload.single("headingImage"),
  adminController.addArticle
);

// Publishers and Admins can update articles
router.put(
  "/articles/:id",
  authorizeRoles("publisher", "admin", "superuser"),
  upload.single("headingImage"),
  adminController.updateArticle
);

// SuperUsers and Admins can delete any article
router.delete(
  "/articles/:id",
  authorizeRoles("admin", "superuser"),
  adminController.deleteArticle
);

// Reviewers can review articles
router.post(
  "/articles/:id/review",
  authorizeRoles("reviewer", "admin", "superuser"),
  adminController.reviewArticle
);

// Users can read articles
router.get(
  "/articles",
  authorizeRoles("user", "reviewer", "publisher", "admin", "superuser"),
  adminController.getAllArticles
);
router.get(
  "/articles/:id",
  authorizeRoles("user", "reviewer", "publisher", "admin", "superuser"),
  adminController.getArticleById
);


// --- News Routes ---

// Similar role-based access can be applied to news routes

module.exports = router;

Can you correct the error in the front end I'm using shadcn UI with the help of Nextjs in front end