Index: backend/controllers/forumController.js
===================================================================
--- backend/controllers/forumController.js	(revision 5aad212e3841deb8dc83be010da5f3e04a8a8401)
+++ backend/controllers/forumController.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -162,15 +162,145 @@
 const getForumPosts = async (req, res) => {
   try {
-    const { page = 0, limit = 20 } = req.query;
-    const skip = parseInt(page) * parseInt(limit);
-    const take = parseInt(limit);
-
-    // Fetch all posts regardless of topic
+    console.log("Received query params:", req.query);
+    console.log("Request URL:", req.originalUrl);
+    
+    // Extract parameters with strict type checking and debug output
+    const page = req.query.page !== undefined ? parseInt(req.query.page) : 0;
+    const limit = req.query.limit !== undefined ? parseInt(req.query.limit) : 20;
+    
+    // Topic needs special handling
+    const topic = req.query.topic || null;
+    console.log(`Topic parameter received: "${topic}"`);
+    
+    const sort = req.query.sort || null;
+    const date = req.query.date || null;
+    const commentSort = req.query.commentSort || null;
+    
+    console.log("Parsed parameters:", { page, limit, topic, sort, date, commentSort });
+    
+    const skip = page * limit;
+    const take = limit;
+
+    // Build filter conditions
+    const whereCondition = {};
+    
+    // Filter by topic if provided
+    if (topic && topic !== 'all') {
+      console.log(`Filtering by topic: "${topic}" (type: ${typeof topic})`);
+      
+      // Force string comparison with trim to handle potential whitespace issues
+      const trimmedTopic = topic.toString().trim();
+      console.log(`Trimmed topic: "${trimmedTopic}"`);
+      
+      // Debug all current topics in database
+      console.log("DEBUG - Will now run a direct DB query to check topics");
+      
+      try {
+        // This will log the actual filtered posts count directly from the database
+        const dbPosts = await prisma.forum_posts.findMany({
+          where: { topic: trimmedTopic },
+          select: { id: true }
+        });
+        console.log(`DIRECT DB QUERY: Found ${dbPosts.length} posts with topic "${trimmedTopic}"`);
+        
+        // Set the correct topic filter
+        whereCondition.topic = trimmedTopic;
+      } catch (err) {
+        console.error("Error in direct DB query:", err);
+        // Fallback to original behavior
+        whereCondition.topic = topic;
+      }
+      
+      console.log("Final whereCondition.topic set to:", whereCondition.topic);
+    }
+    
+    // Filter by specific date if provided
+    if (date) {
+      console.log(`Filtering by specific date: "${date}"`);
+      
+      try {
+        // Create a date object from the provided date string
+        const selectedDate = new Date(date);
+        
+        // Ensure the date is valid
+        if (isNaN(selectedDate.getTime())) {
+          console.error(`Invalid date provided: "${date}"`);
+        } else {
+          // Set to beginning of the day (midnight)
+          selectedDate.setHours(0, 0, 0, 0);
+          
+          // Calculate the end of the day (next day midnight)
+          const nextDay = new Date(selectedDate);
+          nextDay.setDate(nextDay.getDate() + 1);
+          
+          console.log(`Date range: ${selectedDate.toISOString()} to ${nextDay.toISOString()}`);
+          
+          // Add to where condition
+          whereCondition.date_created = {
+            gte: selectedDate,
+            lt: nextDay
+          };
+          
+          // Verify with a direct database query to check post count for this date
+          try {
+            const dateCheckResult = await prisma.forum_posts.count({
+              where: {
+                date_created: {
+                  gte: selectedDate,
+                  lt: nextDay
+                }
+              }
+            });
+            console.log(`DIRECT DB CHECK: Found ${dateCheckResult} posts on date ${date}`);
+          } catch (err) {
+            console.error("Error in direct DB date check:", err);
+          }
+        }
+      } catch (err) {
+        console.error(`Error processing date filter "${date}":`, err);
+      }
+    }
+    
+    console.log("Using where condition:", JSON.stringify(whereCondition));
+    
+    // Determine ordering - using an array to support multiple sorting criteria
+    let orderBy = [];
+    
+    // First, handle comment popularity sorting if specified
+    if (commentSort === 'most-popular') {
+      console.log("Applying MOST popular sorting");
+      orderBy.push({ comment_count: 'desc' });
+      
+      // Add date as secondary sort to make results consistent
+      orderBy.push({ date_created: 'desc' });
+      console.log("Added secondary date sorting (newest first) for consistency");
+    } else if (commentSort === 'least-popular') {
+      console.log("Applying LEAST popular sorting");
+      orderBy.push({ comment_count: 'asc' });
+      
+      // Add date as secondary sort to make results consistent
+      orderBy.push({ date_created: 'desc' });
+      console.log("Added secondary date sorting (newest first) for consistency");
+    } 
+    // Only apply date sorting as primary sort if comment sorting isn't specified
+    else {
+      // Always apply date sorting (either as primary or secondary criterion)
+      if (sort === 'oldest') {
+        console.log("Applying oldest first date sorting as primary criterion");
+        orderBy.push({ date_created: 'asc' });
+      } else {
+        console.log("Applying newest first date sorting as primary criterion");
+        orderBy.push({ date_created: 'desc' });
+      }
+    }
+    
+    console.log("Final sort order:", JSON.stringify(orderBy));
+
+    // Fetch posts with filters
     const allPosts = await prisma.forum_posts.findMany({
       skip: skip,
       take: take,
-      orderBy: {
-        date_created: "desc"
-      },
+      where: whereCondition,
+      orderBy: orderBy,
       include: {
         challenges: {
@@ -188,4 +318,93 @@
     }));
 
+    // Enhanced debug output
+    console.log(`Returning ${forumPosts.length} posts with filters:`, {
+      whereCondition,
+      orderBy,
+      skip,
+      take
+    });
+    
+    // Log topic distribution to help debug topic filtering issues
+    if (topic && topic !== 'all') {
+      const topicsInResult = {};
+      forumPosts.forEach(post => {
+        topicsInResult[post.topic] = (topicsInResult[post.topic] || 0) + 1;
+      });
+      
+      console.log("TOPIC DISTRIBUTION IN RESULTS:", topicsInResult);
+      
+      // Check if filtering was successful
+      const nonMatchingCount = forumPosts.filter(post => post.topic !== topic).length;
+      if (nonMatchingCount > 0) {
+        console.warn(`WARNING: Found ${nonMatchingCount} posts with wrong topic in results!`);
+      }
+    }
+    
+    // Log sorting analysis to help with debugging
+    if (forumPosts.length > 0) {
+      // Comment count analysis for popularity sort debugging
+      if (commentSort) {
+        console.log("COMMENT COUNT ANALYSIS:");
+        const counts = forumPosts.map(p => p.comment_count);
+        console.log(`- Min: ${Math.min(...counts)}, Max: ${Math.max(...counts)}`);
+      }
+      
+      // Date sorting and filtering analysis
+      console.log("DATE ANALYSIS:");
+      const dates = forumPosts.map(p => new Date(p.date_created).getTime());
+      
+      if (dates.length > 0) {
+        const minDate = new Date(Math.min(...dates));
+        const maxDate = new Date(Math.max(...dates));
+        console.log(`- Posts date range: ${minDate.toISOString()} to ${maxDate.toISOString()}`);
+        
+        // If specific date filter was applied, verify it's working
+        if (date) {
+          const filterDate = new Date(date);
+          filterDate.setHours(0, 0, 0, 0);
+          const nextDay = new Date(filterDate);
+          nextDay.setDate(nextDay.getDate() + 1);
+          
+          console.log(`- Specific date filter: ${filterDate.toISOString()} to ${nextDay.toISOString()}`);
+          
+          // Check if all posts are within the filtered date range
+          const postsInRange = forumPosts.filter(p => {
+            const postDate = new Date(p.date_created);
+            return postDate >= filterDate && postDate < nextDay;
+          });
+          
+          console.log(`- Posts matching date filter: ${postsInRange.length}/${forumPosts.length}`);
+          
+          if (postsInRange.length < forumPosts.length) {
+            console.warn('⚠️ WARNING: Some posts do not match the date filter!');
+          }
+        }
+      } else {
+        console.log('- No posts to analyze dates');
+      }
+      
+      // First three posts details
+      console.log(`FIRST THREE POSTS:`, forumPosts.slice(0, 3).map(p => ({
+        id: p.id,
+        topic: p.topic,
+        comments: p.comment_count,
+        date: new Date(p.date_created).toISOString().split('T')[0]
+      })));
+    }
+
+    // Set cache control headers to prevent caching
+    res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
+    res.set('Pragma', 'no-cache');
+    res.set('Expires', '0');
+    
+    // Add response information to help debug the filtering
+    res.set('X-Total-Posts', forumPosts.length.toString());
+    res.set('X-Filter-Topic', topic || 'none');
+    res.set('X-Filter-Applied', JSON.stringify(whereCondition));
+    res.set('X-Sort-Order', JSON.stringify(orderBy));
+    
+    console.log(`RESPONSE: Sending ${forumPosts.length} posts with filter:`, whereCondition);
+    
     res.status(200).json(forumPosts);
   } catch (err) {
Index: backend/routers/forumRouter.js
===================================================================
--- backend/routers/forumRouter.js	(revision 5aad212e3841deb8dc83be010da5f3e04a8a8401)
+++ backend/routers/forumRouter.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -2,4 +2,12 @@
 const router = express.Router();
 const forumController = require("../controllers/forumController");
+
+// Debug middleware for the posts route
+router.use('/posts', (req, res, next) => {
+  console.log('Forum request received:');
+  console.log('  Query params:', req.query);
+  console.log('  URL:', req.originalUrl);
+  next();
+});
 
 router.post("/posts", forumController.createForumPost);
Index: backend/scripts/apiTest.js
===================================================================
--- backend/scripts/apiTest.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
+++ backend/scripts/apiTest.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -0,0 +1,72 @@
+const axios = require('axios');
+
+async function testApi() {
+  try {
+    // Get a JWT token first (this is just a placeholder, you'll need to get a real token)
+    const token = "your_jwt_token";
+    
+    // Make a request to the API with different filters
+    console.log("Testing general posts filter...");
+    const generalResponse = await axios.get('http://localhost:5001/forum/posts?page=0&limit=20&topic=general', {
+      headers: {
+        Authorization: `Bearer ${token}`
+      }
+    });
+    
+    console.log(`Status: ${generalResponse.status}`);
+    console.log(`Received ${generalResponse.data.length} general posts`);
+    
+    // Test daily challenge filter
+    console.log("\nTesting daily challenge posts filter...");
+    const challengeResponse = await axios.get('http://localhost:5001/forum/posts?page=0&limit=20&topic=daily-challenge', {
+      headers: {
+        Authorization: `Bearer ${token}`
+      }
+    });
+    
+    console.log(`Status: ${challengeResponse.status}`);
+    console.log(`Received ${challengeResponse.data.length} daily challenge posts`);
+    
+    // Output response headers to check for caching
+    console.log("\nResponse headers:", challengeResponse.headers);
+  } catch (error) {
+    console.error("Error testing API:", error.message);
+    if (error.response) {
+      console.log("Response status:", error.response.status);
+      console.log("Response data:", error.response.data);
+    }
+  }
+}
+
+console.log("This script would test the API endpoints directly, but it needs a valid JWT token.");
+console.log("Instead, let's try a local test with the filter function...");
+
+const forumController = require('../controllers/forumController');
+
+// Mock Express request and response
+const mockReq = (query) => ({ query });
+const mockRes = {
+  status: (code) => ({
+    json: (data) => {
+      console.log(`Status ${code}, returned ${data.length} posts`);
+      console.log("Sample data:", data.slice(0, 2));
+    }
+  })
+};
+
+// Test the controller directly
+async function testController() {
+  console.log("\nTesting controller with topic=general:");
+  await forumController.getForumPosts(
+    mockReq({ page: 0, limit: 20, topic: 'general' }),
+    mockRes
+  );
+  
+  console.log("\nTesting controller with topic=daily-challenge:");
+  await forumController.getForumPosts(
+    mockReq({ page: 0, limit: 20, topic: 'daily-challenge' }),
+    mockRes
+  );
+}
+
+testController();
Index: backend/scripts/checkDb.js
===================================================================
--- backend/scripts/checkDb.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
+++ backend/scripts/checkDb.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -0,0 +1,56 @@
+const prisma = require("../lib/prisma");
+
+async function main() {
+  // Count total posts
+  const totalCount = await prisma.forum_posts.count();
+  console.log(`Total posts: ${totalCount}`);
+
+  // Check distinct topics
+  const topics = await prisma.forum_posts.groupBy({
+    by: ['topic'],
+    _count: {
+      _all: true
+    }
+  });
+  console.log("Topics distribution:", topics);
+
+  // Check distinct dates (just the count by date)
+  const dates = await prisma.forum_posts.groupBy({
+    by: ['date_created'],
+    _count: {
+      _all: true
+    }
+  });
+  console.log("Dates count:", dates.length);
+
+  // Check comment counts distribution
+  const commentCounts = await prisma.forum_posts.groupBy({
+    by: ['comment_count'],
+    _count: {
+      _all: true
+    }
+  });
+  console.log("Comment counts distribution:", commentCounts);
+
+  // Sample some posts with their topic
+  const samplePosts = await prisma.forum_posts.findMany({
+    take: 5,
+    select: {
+      id: true,
+      title: true,
+      topic: true,
+      comment_count: true,
+      date_created: true
+    }
+  });
+  console.log("Sample posts:", samplePosts);
+}
+
+main()
+  .catch(e => {
+    console.error(e);
+    process.exit(1);
+  })
+  .finally(async () => {
+    await prisma.$disconnect();
+  });
Index: backend/scripts/checkTopics.js
===================================================================
--- backend/scripts/checkTopics.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
+++ backend/scripts/checkTopics.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -0,0 +1,75 @@
+const prisma = require("../lib/prisma");
+
+async function main() {
+  console.log("Checking all forum posts topics and values:");
+  
+  // Get all posts with minimal info to check topic values
+  const posts = await prisma.forum_posts.findMany({
+    select: {
+      id: true,
+      title: true,
+      topic: true
+    },
+    orderBy: {
+      topic: 'asc'
+    }
+  });
+  
+  console.log(`Retrieved ${posts.length} posts`);
+  
+  // Show all topic values and counts
+  const topicCounts = {};
+  posts.forEach(post => {
+    const topic = post.topic || 'null';
+    if (!topicCounts[topic]) topicCounts[topic] = 0;
+    topicCounts[topic]++;
+  });
+  
+  console.log("Topic counts:", topicCounts);
+  
+  // Show a sample of each topic
+  console.log("\nSample posts by topic:");
+  Object.keys(topicCounts).forEach(topic => {
+    const sample = posts.find(p => (p.topic || 'null') === topic);
+    console.log(`Topic "${topic}": "${sample.title}" (${sample.id})`);
+  });
+  
+  // Try a direct query for 'general' posts
+  console.log("\nTesting direct query for 'general' posts:");
+  const generalPosts = await prisma.forum_posts.findMany({
+    where: {
+      topic: 'general'
+    },
+    select: {
+      id: true,
+      title: true,
+      topic: true
+    }
+  });
+  
+  console.log(`Found ${generalPosts.length} general posts`);
+  
+  // Try a direct query for 'daily-challenge' posts
+  console.log("\nTesting direct query for 'daily-challenge' posts:");
+  const challengePosts = await prisma.forum_posts.findMany({
+    where: {
+      topic: 'daily-challenge'
+    },
+    select: {
+      id: true,
+      title: true,
+      topic: true
+    }
+  });
+  
+  console.log(`Found ${challengePosts.length} daily-challenge posts`);
+}
+
+main()
+  .catch(e => {
+    console.error(e);
+    process.exit(1);
+  })
+  .finally(async () => {
+    await prisma.$disconnect();
+  });
Index: backend/scripts/testFilters.js
===================================================================
--- backend/scripts/testFilters.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
+++ backend/scripts/testFilters.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -0,0 +1,46 @@
+const prisma = require("../lib/prisma");
+
+async function testFilter() {
+  console.log("Testing topic filter for 'general'");
+  
+  // Test filter by topic = general
+  const generalPosts = await prisma.forum_posts.findMany({
+    where: { 
+      topic: 'general' 
+    }
+  });
+  
+  console.log(`Found ${generalPosts.length} general posts`);
+  console.log(generalPosts.map(p => ({ id: p.id, title: p.title, topic: p.topic })));
+  
+  // Test filter by topic = daily-challenge
+  console.log("\nTesting topic filter for 'daily-challenge'");
+  const challengePosts = await prisma.forum_posts.findMany({
+    where: { 
+      topic: 'daily-challenge' 
+    }
+  });
+  
+  console.log(`Found ${challengePosts.length} daily challenge posts`);
+  console.log(challengePosts.map(p => ({ id: p.id, title: p.title, topic: p.topic })));
+  
+  // Test filter by comment_count in descending order
+  console.log("\nTesting comment count sorting (most popular)");
+  const popularPosts = await prisma.forum_posts.findMany({
+    orderBy: {
+      comment_count: 'desc'
+    }
+  });
+  
+  console.log("Posts ordered by popularity:");
+  console.log(popularPosts.map(p => ({ id: p.id, title: p.title, comment_count: p.comment_count })));
+}
+
+testFilter()
+  .catch(e => {
+    console.error(e);
+    process.exit(1);
+  })
+  .finally(async () => {
+    await prisma.$disconnect();
+  });
Index: backend/scripts/testOrderBy.js
===================================================================
--- backend/scripts/testOrderBy.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
+++ backend/scripts/testOrderBy.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -0,0 +1,54 @@
+const prisma = require("../lib/prisma");
+
+async function testOrderBy() {
+  console.log("Testing orderBy as an array with multiple criteria");
+  
+  try {
+    // Test using orderBy as an array
+    const postsArrayOrder = await prisma.forum_posts.findMany({
+      orderBy: [
+        { comment_count: 'desc' },
+        { date_created: 'desc' }
+      ],
+      select: {
+        id: true,
+        title: true,
+        comment_count: true,
+        date_created: true
+      }
+    });
+    
+    console.log("Posts ordered by comment_count DESC, date_created DESC:");
+    postsArrayOrder.forEach(post => {
+      console.log(`- ${post.title}: ${post.comment_count} comments, ${post.date_created}`);
+    });
+    
+    // Test using orderBy as a single object
+    const postsObjectOrder = await prisma.forum_posts.findMany({
+      orderBy: { comment_count: 'desc' },
+      select: {
+        id: true,
+        title: true,
+        comment_count: true,
+        date_created: true
+      }
+    });
+    
+    console.log("\nPosts ordered by comment_count DESC (object style):");
+    postsObjectOrder.forEach(post => {
+      console.log(`- ${post.title}: ${post.comment_count} comments, ${post.date_created}`);
+    });
+    
+  } catch (err) {
+    console.error("Error testing orderBy:", err);
+  }
+}
+
+testOrderBy()
+  .catch(e => {
+    console.error(e);
+    process.exit(1);
+  })
+  .finally(async () => {
+    await prisma.$disconnect();
+  });
Index: client/src/Dashboard/components/Forum.jsx
===================================================================
--- client/src/Dashboard/components/Forum.jsx	(revision 5aad212e3841deb8dc83be010da5f3e04a8a8401)
+++ client/src/Dashboard/components/Forum.jsx	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -6,4 +6,6 @@
 import { getForumPosts, deleteForumPost } from "@/services/forumService";
 import { useAuth } from "@/contexts/AuthContext";
+import { DatePicker } from "react-daisyui-timetools";
+import "react-datepicker/dist/react-datepicker.css";
 
 const Forum = () => {
@@ -23,4 +25,18 @@
   const postsPerPage = 20;
   const { user } = useAuth();
+
+  // Filter states
+  // Default filters used throughout the component
+  const defaultFilters = {
+    topic: "all", // "all", "general", "daily-challenge"
+    dateSort: "newest", // "newest", "oldest"
+    selectedDate: null, // specific date filter
+    commentSort: "none", // "none", "most-popular", "least-popular"
+  };
+
+  // Initialize filters state with the default values
+  const [filters, setFilters] = useState({ ...defaultFilters });
+  const [showFilters, setShowFilters] = useState(false);
+
   console.log(user);
 
@@ -41,9 +57,25 @@
   };
 
+  // Only fetch posts on component mount
   useEffect(() => {
-    fetchPosts();
+    // Always use the default filters for the initial fetch
+    console.log("Initial fetch with default filters");
+    fetchPosts(0, false, { ...defaultFilters });
+
+    // Adding event listener to help with debugging
+    window.addEventListener("forumFilterDebug", () => {
+      console.log("Current filters:", filters);
+    });
+
+    return () => {
+      window.removeEventListener("forumFilterDebug", () => {});
+    };
   }, []);
 
-  const fetchPosts = async (pageNum = 0, append = false) => {
+  const fetchPosts = async (
+    pageNum = 0,
+    append = false,
+    activeFilters = null
+  ) => {
     try {
       if (!append) {
@@ -53,7 +85,237 @@
       }
 
-      const data = await getForumPosts(pageNum, postsPerPage);
+      // Use the provided filters or the current state
+      // Make sure to use a new object to avoid reference issues
+      const filtersToApply = activeFilters
+        ? { ...activeFilters }
+        : { ...filters };
+
+      console.log(
+        `FETCH POSTS: Page=${pageNum}, Append=${append}, Filters:`,
+        JSON.stringify(filtersToApply)
+      );
+
+      // Validate filters to ensure they're not null or undefined
+      Object.keys(filtersToApply).forEach((key) => {
+        if (filtersToApply[key] === undefined) {
+          console.warn(`Filter value for ${key} is undefined, setting to null`);
+          filtersToApply[key] = null;
+        }
+      });
+
+      console.log("Sending filters to API:", filtersToApply);
+
+      const response = await getForumPosts(
+        pageNum,
+        postsPerPage,
+        filtersToApply
+      );
+      // The response is already the data due to the apiClient interceptor
+      let data = response || [];
       console.log("Fetched forum posts:", data);
       console.log("Total posts fetched:", data.length);
+      console.log("API returned data for filters:", filtersToApply);
+
+      // COMPREHENSIVE CLIENT-SIDE FILTERING WORKAROUND
+      // Apply client-side filtering for any filter that the server might have missed
+      let appliedClientSideFiltering = false;
+
+      // 1. Filter by topic if needed
+      if (
+        filtersToApply.topic &&
+        filtersToApply.topic !== "all" &&
+        data.length > 0
+      ) {
+        // Check if we need topic filtering by seeing if any posts don't match the requested topic
+        const nonMatchingPosts = data.some(
+          (post) => post.topic !== filtersToApply.topic
+        );
+
+        if (nonMatchingPosts) {
+          console.log(
+            "Applying client-side topic filtering for:",
+            filtersToApply.topic
+          );
+          const beforeCount = data.length;
+          data = data.filter((post) => post.topic === filtersToApply.topic);
+          console.log(
+            `Client-side topic filtered: ${beforeCount} → ${data.length} posts`
+          );
+          appliedClientSideFiltering = true;
+        }
+      }
+
+      // 2. Apply comment popularity sorting if needed
+      if (
+        filtersToApply.commentSort &&
+        filtersToApply.commentSort !== "none" &&
+        data.length > 1
+      ) {
+        // Check if the data is already properly sorted by comment count
+        const isAlreadySorted = (() => {
+          // For "most-popular", check if posts are sorted in descending order by comment_count
+          if (filtersToApply.commentSort === "most-popular") {
+            for (let i = 0; i < data.length - 1; i++) {
+              if (data[i].comment_count < data[i + 1].comment_count) {
+                return false; // Found an out-of-order pair
+              }
+            }
+          }
+          // For "least-popular", check if posts are sorted in ascending order by comment_count
+          else if (filtersToApply.commentSort === "least-popular") {
+            for (let i = 0; i < data.length - 1; i++) {
+              if (data[i].comment_count > data[i + 1].comment_count) {
+                return false; // Found an out-of-order pair
+              }
+            }
+          }
+          return true; // Data is properly sorted
+        })();
+
+        if (!isAlreadySorted) {
+          console.log(
+            `Applying client-side ${filtersToApply.commentSort} sorting`
+          );
+
+          data = [...data].sort((a, b) => {
+            if (filtersToApply.commentSort === "most-popular") {
+              // Sort by comment count (high to low), then by date (new to old)
+              return (
+                b.comment_count - a.comment_count ||
+                new Date(b.date_created) - new Date(a.date_created)
+              );
+            } else {
+              // Sort by comment count (low to high), then by date (new to old)
+              return (
+                a.comment_count - b.comment_count ||
+                new Date(b.date_created) - new Date(a.date_created)
+              );
+            }
+          });
+
+          console.log("Applied client-side popularity sorting");
+          appliedClientSideFiltering = true;
+        }
+      }
+
+      // 3. Apply specific date filtering if needed
+      if (filtersToApply.selectedDate && data.length > 0) {
+        console.log(
+          `Checking for specific date filtering:`,
+          filtersToApply.selectedDate
+        );
+
+        try {
+          // Create date objects for comparison (start and end of selected day)
+          // Handle both Date objects and string representations
+          const filterDate =
+            filtersToApply.selectedDate instanceof Date
+              ? new Date(filtersToApply.selectedDate)
+              : new Date(String(filtersToApply.selectedDate));
+
+          // Validate date before proceeding
+          if (!isNaN(filterDate.getTime())) {
+            filterDate.setHours(0, 0, 0, 0); // Start of day
+
+            const nextDay = new Date(filterDate);
+            nextDay.setDate(nextDay.getDate() + 1); // Start of next day
+
+            // Count posts outside the date range
+            const invalidDateCount = data.filter((post) => {
+              const postDate = new Date(post.date_created);
+              return postDate < filterDate || postDate >= nextDay;
+            }).length;
+
+            if (invalidDateCount > 0) {
+              console.log(
+                `Found ${invalidDateCount} posts outside of selected date. Applying client-side date filtering.`
+              );
+
+              // Filter to include only posts from the selected date
+              const beforeCount = data.length;
+              data = data.filter((post) => {
+                const postDate = new Date(post.date_created);
+                return postDate >= filterDate && postDate < nextDay;
+              });
+
+              console.log(
+                `Client-side date filtered: ${beforeCount} → ${data.length} posts`
+              );
+              appliedClientSideFiltering = true;
+            } else {
+              console.log("All posts already match the selected date filter");
+            }
+          } else {
+            console.error(
+              "Invalid date selected for filtering:",
+              filtersToApply.selectedDate
+            );
+          }
+        } catch (err) {
+          console.error("Error in date filtering:", err);
+        }
+      }
+
+      // 4. Apply date sorting if needed (and if comment sorting wasn't applied)
+      if (
+        filtersToApply.dateSort &&
+        data.length > 1 &&
+        (!filtersToApply.commentSort || filtersToApply.commentSort === "none")
+      ) {
+        // Check if the data is already properly sorted by date
+        const isDateSorted = (() => {
+          if (filtersToApply.dateSort === "oldest") {
+            // Check if sorted ascending by date (oldest first)
+            for (let i = 0; i < data.length - 1; i++) {
+              if (
+                new Date(data[i].date_created) >
+                new Date(data[i + 1].date_created)
+              ) {
+                return false;
+              }
+            }
+          } else {
+            // Check if sorted descending by date (newest first)
+            for (let i = 0; i < data.length - 1; i++) {
+              if (
+                new Date(data[i].date_created) <
+                new Date(data[i + 1].date_created)
+              ) {
+                return false;
+              }
+            }
+          }
+          return true;
+        })();
+
+        if (!isDateSorted) {
+          console.log(
+            `Applying client-side date sorting: ${filtersToApply.dateSort}`
+          );
+
+          data = [...data].sort((a, b) => {
+            const dateA = new Date(a.date_created);
+            const dateB = new Date(b.date_created);
+
+            if (filtersToApply.dateSort === "oldest") {
+              // Sort by date (oldest first)
+              return dateA - dateB;
+            } else {
+              // Sort by date (newest first)
+              return dateB - dateA;
+            }
+          });
+
+          console.log("Applied client-side date sorting");
+          appliedClientSideFiltering = true;
+        }
+      }
+
+      if (appliedClientSideFiltering) {
+        console.log(
+          "CLIENT-SIDE FILTERING APPLIED - Final post count:",
+          data.length
+        );
+      }
 
       if (append) {
@@ -68,4 +330,14 @@
     } catch (error) {
       console.error("Error fetching forum posts:", error);
+
+      // Show error details in console for debugging
+      if (error.response) {
+        console.error("Error response:", error.response);
+      }
+
+      // Set empty posts array if there was an error
+      if (!append) {
+        setPosts([]);
+      }
     } finally {
       setLoading(false);
@@ -76,5 +348,57 @@
   const loadMore = async () => {
     const nextPage = page + 1;
-    await fetchPosts(nextPage, true);
+    // Explicitly pass current filters to ensure they're applied when loading more
+    await fetchPosts(nextPage, true, filters);
+  };
+
+  // Apply all selected filters
+  const applyFilters = async () => {
+    // Make a copy of the current filters to ensure we're using the latest state
+    const currentFilters = { ...filters };
+    console.log("Applying filters:", currentFilters);
+
+    // Show visual confirmation that filters are being applied
+    setLoading(true);
+
+    // Log the current filter state
+    console.log("FILTER APPLICATION - Current filter state:", {
+      filters,
+      currentFilters,
+      page: 0,
+    });
+
+    // Reset to page 0 when applying new filters
+    setPage(0);
+
+    // Force a small delay to ensure state updates have propagated
+    setTimeout(async () => {
+      try {
+        console.log("Starting fetchPosts with filters:", currentFilters);
+        await fetchPosts(0, false, currentFilters);
+        console.log("Filters applied successfully");
+      } catch (err) {
+        console.error("Error applying filters:", err);
+      }
+    }, 100);
+  };
+
+  // Clear all filters and reset to default
+  const clearFilters = async () => {
+    console.log("Clearing filters, using defaults:", defaultFilters);
+
+    // Show visual confirmation that filters are being cleared
+    setLoading(true);
+
+    // Update the filters state with a fresh copy of default filters
+    const freshDefaultFilters = { ...defaultFilters };
+    setFilters(freshDefaultFilters);
+
+    // Reset to page 0 and fetch with default filters after a small delay
+    setPage(0);
+
+    // Force a small delay to ensure state updates have propagated
+    setTimeout(async () => {
+      await fetchPosts(0, false, freshDefaultFilters);
+    }, 100);
   };
 
@@ -83,6 +407,6 @@
       await deleteForumPost(postId);
 
-      // Refresh the posts after deletion
-      await fetchPosts();
+      // Refresh the posts after deletion with current filters
+      await fetchPosts(0, false, { ...filters });
       showModal("Post deleted successfully.", "success");
     } catch (error) {
@@ -123,4 +447,193 @@
         </div>
 
+        {/* Filter Navbar */}
+        <div className="sticky top-[73px] z-10 bg-base-200 border-b border-base-300 shadow-sm">
+          <div className="p-3 sm:p-4 sm:pl-12 w-full max-w-7xl mx-auto">
+            {/* Mobile Filter Toggle */}
+            <div className="flex items-center justify-between mb-3 lg:hidden">
+              <h3 className="text-lg font-semibold">Filters</h3>
+              <button
+                onClick={() => setShowFilters(!showFilters)}
+                className="btn btn-sm btn-ghost"
+              >
+                <svg
+                  className={`w-4 h-4 transition-transform ${
+                    showFilters ? "rotate-180" : ""
+                  }`}
+                  fill="none"
+                  stroke="currentColor"
+                  viewBox="0 0 24 24"
+                >
+                  <path
+                    strokeLinecap="round"
+                    strokeLinejoin="round"
+                    strokeWidth="2"
+                    d="M19 9l-7 7-7-7"
+                  />
+                </svg>
+              </button>
+            </div>
+
+            {/* Filter Controls */}
+            <div className={`${showFilters ? "block" : "hidden"} lg:block`}>
+              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-3 mb-3 max-w-6xl">
+                {/* Topic Filter */}
+                <div className="flex flex-col gap-1">
+                  <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">
+                    Topic
+                  </label>
+                  <select
+                    value={filters.topic}
+                    onChange={(e) =>
+                      setFilters({ ...filters, topic: e.target.value })
+                    }
+                    className="select select-sm select-bordered w-full text-sm"
+                  >
+                    <option value="all">All Topics</option>
+                    <option value="general">General</option>
+                    <option value="daily-challenge">Daily Challenge</option>
+                  </select>
+                </div>
+
+                {/* Date Sort */}
+                <div className="flex flex-col gap-1">
+                  <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">
+                    Date Order
+                  </label>
+                  <select
+                    value={filters.dateSort}
+                    onChange={(e) =>
+                      setFilters({ ...filters, dateSort: e.target.value })
+                    }
+                    className="select select-sm select-bordered w-full text-sm"
+                  >
+                    <option value="newest">Most Recent</option>
+                    <option value="oldest">Oldest First</option>
+                  </select>
+                </div>
+
+                {/* Specific Date Filter */}
+                <div className="flex flex-col gap-1">
+                  <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">
+                    Specific Date
+                  </label>
+                  <DatePicker
+                    className="input input-sm input-bordered w-full text-sm"
+                    selected={
+                      filters.selectedDate instanceof Date
+                        ? filters.selectedDate
+                        : filters.selectedDate
+                        ? new Date(filters.selectedDate)
+                        : null
+                    }
+                    onChange={(date) => {
+                      // Ensure we're storing a valid Date object
+                      if (date) {
+                        try {
+                          // Create a valid date object
+                          const validDate = new Date(date);
+                          // Check if it's a valid date
+                          if (!isNaN(validDate.getTime())) {
+                            setFilters({ ...filters, selectedDate: validDate });
+                          } else {
+                            console.error("Invalid date selected:", date);
+                            setFilters({ ...filters, selectedDate: null });
+                          }
+                        } catch (err) {
+                          console.error("Error processing date:", err);
+                          setFilters({ ...filters, selectedDate: null });
+                        }
+                      } else {
+                        // Handle clearing the date
+                        setFilters({ ...filters, selectedDate: null });
+                      }
+                    }}
+                    placeholder="Select date"
+                    maxDate={new Date()}
+                    dateFormat="MM/dd/yyyy"
+                    showYearDropdown
+                    showMonthDropdown
+                    isClearable={true}
+                  />
+                </div>
+
+                {/* Comment Sort */}
+                <div className="flex flex-col gap-1">
+                  <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">
+                    Popularity
+                  </label>
+                  <select
+                    value={filters.commentSort}
+                    onChange={(e) =>
+                      setFilters({ ...filters, commentSort: e.target.value })
+                    }
+                    className="select select-sm select-bordered w-full text-sm"
+                  >
+                    <option value="none">No Sorting</option>
+                    <option value="most-popular">Most Popular</option>
+                    <option value="least-popular">Least Popular</option>
+                  </select>
+                </div>
+
+                {/* Clear Filters & Apply Buttons */}
+                <div className="flex flex-col gap-1 sm:col-span-2 lg:col-span-2">
+                  <label className="text-xs font-medium text-gray-500 uppercase tracking-wide opacity-0">
+                    Actions
+                  </label>
+                  <div className="flex gap-2 max-w-md">
+                    <button
+                      onClick={clearFilters}
+                      className="cursor-pointer px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 text-sm font-medium flex-1 max-w-32"
+                    >
+                      Clear
+                    </button>
+                    <button
+                      onClick={applyFilters}
+                      className="cursor-pointer px-4 py-2 bg-yellow-500 text-black rounded hover:bg-yellow-600 text-sm font-medium flex-1 max-w-40"
+                    >
+                      Apply Filters
+                    </button>
+                  </div>
+                </div>
+              </div>
+
+              {/* Active Filters Display */}
+              <div className="flex flex-wrap gap-2">
+                {filters.topic !== "all" && (
+                  <span className="badge badge-outline badge-sm">
+                    Topic:{" "}
+                    {filters.topic === "general"
+                      ? "General"
+                      : "Daily Challenge"}
+                  </span>
+                )}
+                {filters.dateSort !== "newest" && (
+                  <span className="badge badge-outline badge-sm">
+                    Sort:{" "}
+                    {filters.dateSort === "oldest"
+                      ? "Oldest First"
+                      : "Most Recent"}
+                  </span>
+                )}
+                {filters.selectedDate && (
+                  <span className="badge badge-outline badge-sm">
+                    Date:{" "}
+                    {filters.selectedDate instanceof Date
+                      ? filters.selectedDate.toLocaleDateString()
+                      : new Date(filters.selectedDate).toLocaleDateString()}
+                  </span>
+                )}
+                {filters.commentSort !== "none" && (
+                  <span className="badge badge-outline badge-sm">
+                    {filters.commentSort === "most-popular"
+                      ? "Most Popular"
+                      : "Least Popular"}
+                  </span>
+                )}
+              </div>
+            </div>
+          </div>
+        </div>
+
         {/* Main Content Area */}
         <div className="flex-1 ">
@@ -134,36 +647,114 @@
               <div className=" overflow-y-auto">
                 <div className="p-4 sm:p-6 sm:pl-12 w-full">
-                  <div className="grid grid-cols-1 md:grid-cols-2   lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4 sm:gap-6">
-                    {posts.map((post) => (
-                      <div
-                        key={post.id}
-                        className="p-3 sm:p-4 lg:p-6 rounded-lg shadow-sm hover:shadow-md transition relative bg-base-200 h-full flex flex-col"
+                  {posts.length === 0 ? (
+                    <div className="flex flex-col items-center justify-center py-10">
+                      <div className="text-2xl font-semibold text-gray-400 mb-2">
+                        No posts found
+                      </div>
+                      <p className="text-gray-500 text-center">
+                        There are no posts that match your selected filters.
+                      </p>
+                      <button
+                        onClick={clearFilters}
+                        className="mt-4 cursor-pointer px-4 py-2 bg-yellow-500 text-black rounded hover:bg-yellow-600 text-sm font-medium"
                       >
-                        {(post.author_name === user.name ||
-                          post.author_name === user.username ||
-                          user.isModerator) && (
-                          <button
-                            className="absolute top-2 right-2 p-1.5 cursor-pointer rounded-full hover:bg-gray-600 transition-colors"
+                        Clear Filters
+                      </button>
+                    </div>
+                  ) : (
+                    <div className="grid grid-cols-1 md:grid-cols-2   lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4 sm:gap-6">
+                      {posts.map((post) => (
+                        <div
+                          key={post.id}
+                          className="p-3 sm:p-4 lg:p-6 rounded-lg shadow-sm hover:shadow-md transition relative bg-base-200 h-full flex flex-col"
+                        >
+                          {(post.author_name === user.name ||
+                            post.author_name === user.username ||
+                            user.isModerator) && (
+                            <button
+                              className="absolute top-2 right-2 p-1.5 cursor-pointer rounded-full hover:bg-gray-600 transition-colors"
+                              onClick={(e) => {
+                                e.stopPropagation();
+                                showModal(
+                                  "Are you sure you want to delete this post? This action cannot be undone.",
+                                  "confirm",
+                                  post.id
+                                );
+                              }}
+                            >
+                              <img
+                                src={trashIcon}
+                                alt="Delete"
+                                className="w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6"
+                              />
+                            </button>
+                          )}
+
+                          <div className="flex items-center gap-2 sm:gap-4 mt-2 pr-8 sm:pr-10">
+                            <h3
+                              className="text-lg sm:text-xl lg:text-2xl font-semibold mb-2 cursor-pointer hover:underline line-clamp-2 text-center sm:text-left w-full"
+                              onClick={() => {
+                                navigate(`/dashboard/forum-detail/${post.id}`, {
+                                  state: { post },
+                                });
+                              }}
+                            >
+                              {post.title}
+                            </h3>
+                          </div>
+
+                          <div className="flex flex-wrap items-center gap-2 mb-2">
+                            <p className="text-xs sm:text-sm text-gray-500 flex flex-col sm:flex-row items-center sm:justify-start gap-0 sm:gap-2">
+                              <span>
+                                By{" "}
+                                <span className="font-semibold underline">
+                                  {post.author_name}
+                                </span>
+                              </span>
+                              <span className="hidden sm:inline mx-1 text-gray-400">
+                                •
+                              </span>
+                              <span className="italic text-gray-400">
+                                {new Date(post.date_created).toLocaleDateString(
+                                  "en-US",
+                                  {
+                                    year: "numeric",
+                                    month: "short",
+                                    day: "numeric",
+                                  }
+                                )}
+                              </span>
+                            </p>
+
+                            {/* Topic Badge */}
+                            <span
+                              className={`inline-block text-xs font-semibold px-2 py-1 rounded ${
+                                post.topic === "general"
+                                  ? "bg-blue-100 text-blue-800"
+                                  : "bg-green-100 text-green-800"
+                              }`}
+                            >
+                              {post.topic === "general"
+                                ? "General"
+                                : "Daily Challenge"}
+                            </span>
+
+                            {/* Challenge Title Badge */}
+                            {post.challengeTitle && (
+                              <span className="inline-block bg-yellow-100 text-yellow-800 text-xs font-semibold px-2 py-1 rounded">
+                                {post.challengeTitle}
+                              </span>
+                            )}
+                          </div>
+
+                          <p className="mt-2 text-gray-400 text-sm sm:text-base line-clamp-3 text-center sm:text-left flex-grow">
+                            {post.content && post.content.length > 100
+                              ? post.content.slice(0, 100) + "..."
+                              : post.content}
+                          </p>
+
+                          <div
+                            className="mt-3 sm:mt-4 flex justify-center sm:justify-end items-center gap-2 cursor-pointer"
                             onClick={(e) => {
-                              e.stopPropagation();
-                              showModal(
-                                "Are you sure you want to delete this post? This action cannot be undone.",
-                                "confirm",
-                                post.id
-                              );
-                            }}
-                          >
-                            <img
-                              src={trashIcon}
-                              alt="Delete"
-                              className="w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6"
-                            />
-                          </button>
-                        )}
-
-                        <div className="flex items-center gap-2 sm:gap-4 mt-2 pr-8 sm:pr-10">
-                          <h3
-                            className="text-lg sm:text-xl lg:text-2xl font-semibold mb-2 cursor-pointer hover:underline line-clamp-2 text-center sm:text-left w-full"
-                            onClick={() => {
                               navigate(`/dashboard/forum-detail/${post.id}`, {
                                 state: { post },
@@ -171,78 +762,17 @@
                             }}
                           >
-                            {post.title}
-                          </h3>
+                            <p className="text-sm sm:text-base">
+                              {post.comment_count}
+                            </p>
+                            <img
+                              src={commentIcon}
+                              alt="Comment"
+                              className="w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6 hover:opacity-80"
+                            />
+                          </div>
                         </div>
-
-                        <div className="flex flex-wrap items-center gap-2 mb-2">
-                          <p className="text-xs sm:text-sm text-gray-500 flex flex-col sm:flex-row items-center sm:justify-start gap-0 sm:gap-2">
-                            <span>
-                              By{" "}
-                              <span className="font-semibold underline">
-                                {post.author_name}
-                              </span>
-                            </span>
-                            <span className="hidden sm:inline mx-1 text-gray-400">
-                              •
-                            </span>
-                            <span className="italic text-gray-400">
-                              {new Date(post.date_created).toLocaleDateString(
-                                "en-US",
-                                {
-                                  year: "numeric",
-                                  month: "short",
-                                  day: "numeric",
-                                }
-                              )}
-                            </span>
-                          </p>
-
-                          {/* Topic Badge */}
-                          <span
-                            className={`inline-block text-xs font-semibold px-2 py-1 rounded ${
-                              post.topic === "general"
-                                ? "bg-blue-100 text-blue-800"
-                                : "bg-green-100 text-green-800"
-                            }`}
-                          >
-                            {post.topic === "general"
-                              ? "General"
-                              : "Daily Challenge"}
-                          </span>
-
-                          {/* Challenge Title Badge */}
-                          {post.challengeTitle && (
-                            <span className="inline-block bg-yellow-100 text-yellow-800 text-xs font-semibold px-2 py-1 rounded">
-                              {post.challengeTitle}
-                            </span>
-                          )}
-                        </div>
-
-                        <p className="mt-2 text-gray-400 text-sm sm:text-base line-clamp-3 text-center sm:text-left flex-grow">
-                          {post.content && post.content.length > 100
-                            ? post.content.slice(0, 100) + "..."
-                            : post.content}
-                        </p>
-
-                        <div
-                          className="mt-3 sm:mt-4 flex justify-center sm:justify-end items-center gap-2 cursor-pointer"
-                          onClick={(e) => {
-                            navigate(`/dashboard/forum-detail/${post.id}`, {
-                              state: { post },
-                            });
-                          }}
-                        >
-                          <p className="text-sm sm:text-base">
-                            {post.comment_count}
-                          </p>
-                          <img
-                            src={commentIcon}
-                            alt="Comment"
-                            className="w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6 hover:opacity-80"
-                          />
-                        </div>
-                      </div>
-                    ))}
-                  </div>
+                      ))}
+                    </div>
+                  )}
 
                   {/* Load More Button */}
Index: client/src/services/forumService.js
===================================================================
--- client/src/services/forumService.js	(revision 5aad212e3841deb8dc83be010da5f3e04a8a8401)
+++ client/src/services/forumService.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -1,6 +1,227 @@
 import apiClient from "./apiClient";
 
-export const getForumPosts = async (page, limit) => {
-  return await apiClient.get(`/forum/posts?page=${page}&limit=${limit}`);
+export const getForumPosts = async (page, limit, filters = null) => {
+  // Force clean parameters
+  page = Number(page) || 0;
+  limit = Number(limit) || 20;
+  
+  // Add timestamp to prevent caching
+  const timestamp = new Date().getTime();
+  let url = `/forum/posts?page=${page}&limit=${limit}&_t=${timestamp}`;
+  
+  // Add filters to the URL if they exist
+  if (filters) {
+    console.log("Service processing filters:", JSON.stringify(filters));
+    
+    // Add topic filter - make sure it's really topic=daily-challenge, not topic=daily%2Dchallenge
+    if (filters.topic && filters.topic !== 'all') {
+      console.log(`Adding topic filter: ${filters.topic}`);
+      url += `&topic=${filters.topic}`;
+    }
+    
+    // Add sort filter - always include date sort preference
+    if (filters.dateSort) {
+      console.log(`Adding date sort filter: ${filters.dateSort}`);
+      url += `&sort=${filters.dateSort}`;
+      
+      // Log the expected behavior
+      if (filters.dateSort === 'oldest') {
+        console.log("Expecting posts sorted with oldest first");
+      } else {
+        console.log("Expecting posts sorted with newest first");
+      }
+    }
+    
+    // Add specific date filter
+    if (filters.selectedDate) {
+      try {
+        // Ensure we have a proper Date object
+        const dateObj = filters.selectedDate instanceof Date ? 
+          filters.selectedDate : 
+          new Date(String(filters.selectedDate));
+          
+        // Validate the date before proceeding
+        if (!isNaN(dateObj.getTime())) {
+          const formattedDate = dateObj.toISOString().split('T')[0];
+          console.log(`Adding specific date filter: ${formattedDate}`);
+          url += `&date=${formattedDate}`;
+          
+          // Log combined filter details when using specific date with other filters
+          if (filters.topic && filters.topic !== 'all') {
+            console.log(`COMBINED FILTERS: Topic=${filters.topic} with specific date=${formattedDate}`);
+          }
+          
+          if (filters.commentSort && filters.commentSort !== 'none') {
+            console.log(`COMBINED FILTERS: Specific date=${formattedDate} with ${filters.commentSort} sorting`);
+          }
+          
+          if (filters.dateSort === 'oldest') {
+            console.log(`COMBINED FILTERS: Specific date=${formattedDate} with oldest-first sorting`);
+            console.log('NOTE: When using specific date, time-of-day ordering still applies');
+          }
+        } else {
+          console.error("Invalid date object:", filters.selectedDate);
+        }
+      } catch (err) {
+        console.error("Error formatting date:", err, filters.selectedDate);
+      }
+    }
+    
+    // Add comment sort filter
+    if (filters.commentSort && filters.commentSort !== 'none') {
+      console.log(`Adding comment sort filter: ${filters.commentSort}`);
+      url += `&commentSort=${filters.commentSort}`;
+      
+      // Add debug info about the expected effect
+      if (filters.commentSort === 'most-popular') {
+        console.log("Expecting posts sorted by highest comment count first");
+      } else if (filters.commentSort === 'least-popular') {
+        console.log("Expecting posts sorted by lowest comment count first");
+      }
+      
+      // Log the combined filter details
+      if (filters.topic && filters.topic !== 'all') {
+        console.log(`COMBINED FILTERS: Topic=${filters.topic} with ${filters.commentSort} sorting`);
+        console.log(`Expected behavior: First filter by ${filters.topic}, then sort by comment count`);
+      }
+    }
+  }
+  
+  console.log("Making API request to:", url);
+  
+  try {
+    // Use apiClient to ensure authentication works properly
+    const apiResponse = await apiClient.get(url);
+    
+    // We'll only use this log to see what's coming from the API
+    console.log(`API topic filter analysis:`, {
+      requestedFilter: filters && filters.topic ? filters.topic : 'all',
+      receivedPosts: apiResponse ? apiResponse.length : 0,
+      postsWithRequestedTopic: apiResponse ? apiResponse.filter(p => 
+        (filters && filters.topic && filters.topic !== 'all') ? 
+        p.topic === filters.topic : true
+      ).length : 0
+    });
+    
+    // Check sorting accuracy and filtering correctness
+    if (apiResponse && apiResponse.length > 1) {
+      // 1. Check specific date filtering accuracy if applied
+      if (filters && filters.selectedDate) {
+        try {
+          // Ensure we have a proper Date object
+          const filterDate = filters.selectedDate instanceof Date ? 
+            new Date(filters.selectedDate) : 
+            new Date(String(filters.selectedDate));
+            
+          // Only proceed if we have a valid date
+          if (!isNaN(filterDate.getTime())) {
+            filterDate.setHours(0, 0, 0, 0); // Normalize to start of day
+            
+            const nextDay = new Date(filterDate);
+            nextDay.setDate(nextDay.getDate() + 1);
+            
+            // Check if all posts are from the selected date
+            const invalidDatePosts = apiResponse.filter(post => {
+              try {
+                const postDate = new Date(post.date_created);
+                return postDate < filterDate || postDate >= nextDay;
+              } catch (err) {
+                console.error("Error parsing post date:", post.date_created);
+                return true; // Count as invalid if we can't parse the date
+              }
+            });
+            
+            if (invalidDatePosts.length > 0) {
+              console.log(`⚠️ SPECIFIC DATE FILTER ISSUE: Found ${invalidDatePosts.length} posts outside selected date range`);
+              console.log('First mismatched post:', {
+                id: invalidDatePosts[0].id,
+                date: new Date(invalidDatePosts[0].date_created).toISOString(),
+                expectedDate: filterDate.toISOString().split('T')[0]
+              });
+            } else {
+              console.log(`✓ Specific date filter applied correctly: All posts are from ${filterDate.toISOString().split('T')[0]}`);
+            }
+          } else {
+            console.error("Invalid date object for filtering validation:", filters.selectedDate);
+          }
+        } catch (err) {
+          console.error("Error validating date filtering:", err);
+        }
+      }
+      
+      // 2. Analyze comment popularity sorting
+      if (filters && filters.commentSort && filters.commentSort !== 'none') {
+        let isPopularitySorted = true;
+        for (let i = 0; i < apiResponse.length - 1; i++) {
+          if (filters.commentSort === 'most-popular') {
+            if (apiResponse[i].comment_count < apiResponse[i + 1].comment_count) {
+              isPopularitySorted = false;
+              break;
+            }
+          } else if (filters.commentSort === 'least-popular') {
+            if (apiResponse[i].comment_count > apiResponse[i + 1].comment_count) {
+              isPopularitySorted = false;
+              break;
+            }
+          }
+        }
+        
+        console.log(`Popularity sort check (${filters.commentSort}): ${isPopularitySorted ? '✓ CORRECT' : '⚠️ NEEDS CLIENT FIXING'}`);
+        
+        if (!isPopularitySorted) {
+          console.log('Will rely on client-side sorting for popularity');
+        }
+      } 
+      
+      // 3. Analyze date sorting (if comment sort is not active)
+      else if (filters && filters.dateSort) {
+        let isDateSorted = true;
+        for (let i = 0; i < apiResponse.length - 1; i++) {
+          const dateA = new Date(apiResponse[i].date_created).getTime();
+          const dateB = new Date(apiResponse[i + 1].date_created).getTime();
+          
+          if (filters.dateSort === 'oldest') {
+            if (dateA > dateB) {
+              isDateSorted = false;
+              break;
+            }
+          } else {
+            // Newest first (default)
+            if (dateA < dateB) {
+              isDateSorted = false;
+              break;
+            }
+          }
+        }
+        
+        console.log(`Date sort check (${filters.dateSort}): ${isDateSorted ? '✓ CORRECT' : '⚠️ NEEDS CLIENT FIXING'}`);
+        
+        if (!isDateSorted) {
+          console.log('Will rely on client-side sorting for date ordering');
+        }
+      }
+      
+      // Log first few posts with dates to help with debugging
+      if (apiResponse.length > 0) {
+        console.log("Date ordering check:", apiResponse.slice(0, 3).map(p => ({
+          id: p.id,
+          date: new Date(p.date_created).toISOString(),
+          comments: p.comment_count
+        })));
+      }
+    }
+    
+    console.log(`API response for ${url}:`, apiResponse ? apiResponse.length : 0, "posts");
+    if (apiResponse && apiResponse.length > 0) {
+      // Log a sample of topics to verify what we're getting
+      const topicSample = apiResponse.slice(0, 3).map(p => ({id: p.id, topic: p.topic, title: p.title}));
+      console.log("First 3 posts:", topicSample);
+    }
+    
+    return apiResponse;
+  } catch (err) {
+    console.error(`API error for ${url}:`, err);
+    throw err;
+  }
 };
 
Index: testServer.js
===================================================================
--- testServer.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
+++ testServer.js	(revision 5bfe774f9a487e2cc07c9012f5e22a33ab79ccda)
@@ -0,0 +1,53 @@
+const express = require('express');
+const app = express();
+const prisma = require('./backend/lib/prisma');
+
+// Middleware to log all requests
+app.use((req, res, next) => {
+  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
+  console.log('Query params:', req.query);
+  next();
+});
+
+// Test forum endpoint
+app.get('/test-forum', async (req, res) => {
+  try {
+    const { topic } = req.query;
+    
+    // Create whereCondition based on topic
+    const whereCondition = {};
+    if (topic && topic !== 'all') {
+      console.log(`Filtering by topic: "${topic}"`);
+      whereCondition.topic = topic;
+    }
+    
+    console.log('Where condition:', whereCondition);
+    
+    // Fetch posts with filter
+    const posts = await prisma.forum_posts.findMany({
+      where: whereCondition,
+      select: {
+        id: true,
+        title: true,
+        topic: true
+      }
+    });
+    
+    console.log(`Found ${posts.length} posts`);
+    
+    // Set cache control headers to prevent caching
+    res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
+    res.set('Pragma', 'no-cache');
+    res.set('Expires', '0');
+    
+    res.status(200).json(posts);
+  } catch (err) {
+    console.error('Error:', err);
+    res.status(500).json({ error: err.message });
+  }
+});
+
+const PORT = 5005;
+app.listen(PORT, () => {
+  console.log(`Test server running at http://localhost:${PORT}`);
+});
