diff --git a/.gitignore b/.gitignore index 49e96f5..2ad4ad4 100644 --- a/.gitignore +++ b/.gitignore @@ -41,4 +41,5 @@ yarn-error.log* next-env.d.ts #vs code -/.vscode \ No newline at end of file +/.vscode +package-lock.json \ No newline at end of file diff --git a/api/blog.ts b/api/blog.ts new file mode 100644 index 0000000..dc2ef72 --- /dev/null +++ b/api/blog.ts @@ -0,0 +1,398 @@ +import { + BlogListResponse, + BlogDetailResponse, + BlogFeaturedResponse, + BlogRecentResponse, + CategoryListResponse, + CategoryDetailResponse, + TagListResponse, + TagDetailResponse, + BlogQueryParams, +} from '../types/blog'; + +/** + * Lấy API URL từ environment variable + * Hỗ trợ cả REACT_APP_API_URL và NEXT_PUBLIC_API_URL + */ +const getApiUrl = (): string => { + // Trong Next.js, client-side env vars cần prefix NEXT_PUBLIC_ + const apiUrl = process.env.NEXT_PUBLIC_API_URL; + + if (!apiUrl) { + console.warn('NEXT_PUBLIC_API_URL is not set. Using default http://localhost:3001'); + return 'http://localhost:3001'; + } + + return apiUrl; +}; + +/** + * Fetch blog list từ API + * @param params - Query parameters (page, limit, category, tag, search) + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchBlogList = async ( + params?: BlogQueryParams +): Promise => { + const apiUrl = getApiUrl(); + const queryParams = new URLSearchParams(); + + if (params?.page) queryParams.append('page', params.page.toString()); + if (params?.limit) queryParams.append('limit', params.limit.toString()); + if (params?.category) queryParams.append('category', params.category); + if (params?.tag) queryParams.append('tag', params.tag); + if (params?.search) queryParams.append('search', params.search); + + const queryString = queryParams.toString(); + const url = `${apiUrl}/api/blog${queryString ? `?${queryString}` : ''}`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + // Next.js: cache và revalidate + next: { revalidate: 60 }, // Revalidate mỗi 60 giây + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: BlogListResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching blog list:', error); + throw new Error( + `Failed to fetch blog list: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch blog detail by slug từ API + * @param slug - Blog post slug + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchBlogDetail = async ( + slug: string +): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/${slug}`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + // No cache for blog detail so comments/replies show immediately after submit + refresh + cache: 'no-store', + }); + + if (!response.ok) { + if (response.status === 404) { + throw new Error('Blog post not found'); + } + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: BlogDetailResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching blog detail:', error); + throw new Error( + `Failed to fetch blog detail: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch featured blogs từ API + * @param limit - Số lượng blog featured (default: 3) + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchFeaturedBlogs = async ( + limit: number = 5 +): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/featured?limit=${limit}`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + next: { revalidate: 60 }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: BlogFeaturedResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching featured blogs:', error); + throw new Error( + `Failed to fetch featured blogs: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch recent blogs từ API + * @param limit - Số lượng blog recent (default: 5) + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchRecentBlogs = async ( + limit: number = 5 +): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/recent?limit=${limit}`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + next: { revalidate: 60 }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: BlogRecentResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching recent blogs:', error); + throw new Error( + `Failed to fetch recent blogs: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch categories list từ API + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchCategories = async (): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/categories`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + next: { revalidate: 300 }, // Categories ít thay đổi, cache lâu hơn + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: CategoryListResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching categories:', error); + throw new Error( + `Failed to fetch categories: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch category detail by slug từ API + * @param slug - Category slug + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchCategoryDetail = async ( + slug: string +): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/categories/${slug}`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + next: { revalidate: 300 }, + }); + + if (!response.ok) { + if (response.status === 404) { + throw new Error('Category not found'); + } + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: CategoryDetailResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching category detail:', error); + throw new Error( + `Failed to fetch category detail: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch tags list từ API + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchTags = async (): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/tags`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + next: { revalidate: 300 }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: TagListResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching tags:', error); + throw new Error( + `Failed to fetch tags: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch popular tags từ API + * @param limit - Số lượng tags (default: 10) + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchPopularTags = async ( + limit: number = 10 +): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/tags/popular?limit=${limit}`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + next: { revalidate: 300 }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: TagListResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching popular tags:', error); + throw new Error( + `Failed to fetch popular tags: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch tag detail by slug từ API + * @param slug - Tag slug + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchTagDetail = async ( + slug: string +): Promise => { + const apiUrl = getApiUrl(); + const url = `${apiUrl}/api/blog/tags/${slug}`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + next: { revalidate: 300 }, + }); + + if (!response.ok) { + if (response.status === 404) { + throw new Error('Tag not found'); + } + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data: TagDetailResponse = await response.json(); + return data; + } catch (error) { + console.error('Error fetching tag detail:', error); + throw new Error( + `Failed to fetch tag detail: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; + +/** + * Fetch blogs by category từ API + * @param categorySlug - Category slug + * @param params - Query parameters (page, limit) + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchBlogsByCategory = async ( + categorySlug: string, + params?: Omit +): Promise => { + // Lấy category name từ slug + const categoryResponse = await fetchCategoryDetail(categorySlug); + const categoryName = categoryResponse.data.name; + + return fetchBlogList({ + ...params, + category: categoryName, + }); +}; + +/** + * Fetch blogs by tag từ API + * @param tagSlug - Tag slug + * @param params - Query parameters (page, limit) + * @returns Promise + * @throws Error nếu fetch thất bại + */ +export const fetchBlogsByTag = async ( + tagSlug: string, + params?: Omit +): Promise => { + // Lấy tag name từ slug + const tagResponse = await fetchTagDetail(tagSlug); + const tagName = tagResponse.data.name; + + return fetchBlogList({ + ...params, + tag: tagName, + }); +}; diff --git a/api/index.ts b/api/index.ts new file mode 100644 index 0000000..36d466b --- /dev/null +++ b/api/index.ts @@ -0,0 +1,4 @@ +/** + * Export all API functions + */ +export * from './blog'; diff --git a/app/blog/[slug]/components/CommentForm.tsx b/app/blog/[slug]/components/CommentForm.tsx new file mode 100644 index 0000000..c1a95ec --- /dev/null +++ b/app/blog/[slug]/components/CommentForm.tsx @@ -0,0 +1,123 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +interface CommentFormProps { + slug: string; + parentId?: string | null; + replyToName?: string | null; + initialContent?: string; + onSubmitted?: () => void; +} + +export default function CommentForm({ + slug, + parentId = null, + replyToName = null, + initialContent = "", + onSubmitted, +}: CommentFormProps) { + const router = useRouter(); + const [isPending, setIsPending] = useState(false); + const [authorName, setAuthorName] = useState(""); + const [content, setContent] = useState(initialContent); + const [error, setError] = useState(null); + const [success, setSuccess] = useState(null); + + const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"; + + const onSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(null); + setSuccess(null); + + if (!authorName.trim() || !content.trim()) { + setError("Please enter your name and comment."); + return; + } + + try { + setIsPending(true); + const res = await fetch(`${apiUrl}/api/blog/${slug}/comments`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify({ + authorName: authorName.trim(), + content: content.trim(), + ...(parentId ? { parentId } : {}), + }), + }); + + const data = await res.json(); + if (!res.ok || !data?.success) { + throw new Error(data?.message || "Failed to submit comment"); + } + + setAuthorName(""); + setContent(""); + setSuccess("Comment submitted."); + + // Re-fetch server data (blog detail is no-store) to show new comment immediately + router.refresh(); + + onSubmitted?.(); + } catch (err) { + setError(err instanceof Error ? err.message : "Failed to submit comment"); + } finally { + setIsPending(false); + } + }; + + return ( +
+

+ {parentId ? (replyToName ? `Reply to @${replyToName}` : "Reply") : "Leave A Comment"} +

+ + {error &&

{error}

} + {success &&

{success}

} + +
+
+
+
+ Your Name + setAuthorName(e.target.value)} + disabled={isPending} + /> +
+
+ +
+
+ +
+
+ +
+ +
+
+
+
+ ); +} + diff --git a/app/blog/[slug]/components/CommentsSection.tsx b/app/blog/[slug]/components/CommentsSection.tsx new file mode 100644 index 0000000..54a2237 --- /dev/null +++ b/app/blog/[slug]/components/CommentsSection.tsx @@ -0,0 +1,232 @@ +"use client"; + +import type { BlogComment } from "@/types/blog"; +import { useMemo, useState } from "react"; +import CommentForm from "./CommentForm"; +import { formatLongDate } from "@/utils"; + +interface CommentsSectionProps { + slug: string; + comments: BlogComment[]; +} + +export default function CommentsSection({ slug, comments }: CommentsSectionProps) { + const [replyTarget, setReplyTarget] = useState<{ + // Root comment id to store as parentId (keeps 1-level threading on backend) + parentId: string; + // The author we are replying to (used for @mention UI) + replyToName: string; + // Which item in the UI is showing the reply form under it + anchorId: string; + } | null>(null); + + const { parents, repliesByParent } = useMemo(() => { + const parentsLocal = (comments || []).filter((c) => !c.parentId); + const replies = (comments || []).filter((c) => !!c.parentId); + const map = new Map(); + for (const r of replies) { + const pid = r.parentId as string; + map.set(pid, [...(map.get(pid) || []), r]); + } + return { parents: parentsLocal, repliesByParent: map }; + }, [comments]); + // Collect all author names to detect full @mentions (including multi-word names) + const authorNames = useMemo(() => { + return (comments || []) + .map((c) => c.authorName) + .filter((n): n is string => !!n) + // Sort by length desc so we match the longest possible name first + .sort((a, b) => b.length - a.length); + }, [comments]); + + const renderContentWithMention = (text?: string) => { + if (!text) return null; + if (!text.startsWith("@")) return text; + + // Try to match an @mention that corresponds to a known author name. + // This supports multi-word names like "@Bạn Cũng Thấy Thế Hà". + const matchedName = authorNames.find((name) => { + const candidate = `@${name}`; + if (!text.startsWith(candidate)) return false; + + // Ensure the match ends at string end or is followed by a space + const nextChar = text.charAt(candidate.length); + return candidate.length === text.length || nextChar === " "; + }); + + if (!matchedName) { + // Fallback: just return the original text if we can't confidently match a name + return text; + } + + const mention = `@${matchedName}`; + const rest = text.slice(mention.length); // includes leading space if present + + return ( + <> + {mention} + {rest} + + ); + }; + + return ( +
+
+

+ {(comments || []).length} {(comments || []).length === 1 ? "Comment" : "Comments"} +

+
+ + {parents.map((comment, index) => { + const replies = comment._id ? repliesByParent.get(comment._id) || [] : []; + const isReplyingHere = !!comment._id && replyTarget?.anchorId === comment._id; + + return ( +
+
+
+ {comment.authorName} +
+ +
+
+
+ {formatLongDate(comment.createdAt)} +

{comment.authorName}

+
+ + {comment._id && ( + + )} +
+ +

{renderContentWithMention(comment.content)}

+ + {isReplyingHere && comment._id && ( +
+
+ +
+ setReplyTarget(null)} + /> +
+ )} + + {/* Replies */} + {replies.length > 0 && ( +
+ {replies.map((reply, replyIndex) => ( +
+
+
+ {reply.authorName} +
+
+
+
+ {formatLongDate(reply.createdAt)} +

{reply.authorName}

+
+ {reply._id && comment._id && ( + + )} +
+

{renderContentWithMention(reply.content)}

+
+
+ + {/* Reply form under child comment */} + {reply._id && replyTarget?.anchorId === reply._id && ( +
+
+ +
+ setReplyTarget(null)} + /> +
+ )} +
+ ))} +
+ )} +
+
+
+ ); + })} + + {/* New top-level comment */} +
+ +
+
+ ); +} + diff --git a/app/blog/[slug]/components/NewsDetailsContent.tsx b/app/blog/[slug]/components/NewsDetailsContent.tsx index 569f7c8..904ea36 100644 --- a/app/blog/[slug]/components/NewsDetailsContent.tsx +++ b/app/blog/[slug]/components/NewsDetailsContent.tsx @@ -1,224 +1,116 @@ import Link from "next/link"; +import type { BlogPost } from "@/types/blog"; +import { editorjsToHtml, getCmsImageUrl } from "@/utils"; +import { toSlug } from "@/utils/slugify"; +import CommentsSection from "./CommentsSection"; + +interface NewsDetailsContentProps { + post: BlogPost; +} + +export default function NewsDetailsContent({ post }: NewsDetailsContentProps) { + // Get comments from post (already included in API response) + const postComments = post.comments || []; + + // Get base URL for EditorJS images + const baseUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"; + + // Convert EditorJS content to HTML + const renderContent = () => { + const html = editorjsToHtml(post.content, baseUrl); + return { __html: html }; + }; + + // Convert EditorJS contentAfterQuote to HTML + const renderContentAfterQuote = () => { + const html = editorjsToHtml(post.contentAfterQuote, baseUrl); + return { __html: html }; + }; -export default function NewsDetailsContent() { return (
- img + {post.title}
  • - - By Admin + By {post.author}
  • - - 11 March 2025 + {post.publishedAt}
  • - - 0 Comments + {postComments.length} Comments
-

Work Visa vs. Student Visa Which is Right for You?

-

- Choosing between a work visa and a student visa depends on your career and academic goals. A - student visa allows you to pursue higher education abroad, gain international exposure, and - sometimes work part-time while studying. On the other hand, a work visa is for professionals - seeking employment opportunities and long-term career growth in another country. -

-

- Both options have unique benefits, eligibility requirements, and future pathways. Understanding - your personal ambitions, financial plans, and long-term vision will help you decide which visa - option best suits your journey. -

-

Work Visa vs. Student Visa: Which is Right for You?

-

- Choosing between a student visa and a work visa is a major decision that shapes your future - abroad. Both visa types open unique opportunities, but the right choice depends on your goals, - priorities, and resources. A student visa is designed for individuals who wish to pursue higher - education in a foreign country. -

-
-
-
- img -
+

{post.title}

+
+ + {/* Gallery Images */} + {post.galleryImages && post.galleryImages.length > 0 && ( +
+ {post.galleryImages.map((image, index) => ( +
+
+ {`${post.title} +
+
+ ))}
-
-
- img -
+ )} + + {/* Quote/Sidebar */} + {post.quote && ( +
+
{post.quote}
-
-
-
- This blog really helped me understand the difference between student and work visas. The - explanations were clear and practical. -
-
-

- It provides access to world-class universities, cultural exposure, and global networking - opportunities. With a student visa, you may also get part-time work rights, which can help support - your expenses and give you valuable international work experience. However, the primary focus - remains on academics and personal growth. On the other hand, a work visa is perfect for those who - want to establish themselves in a career overseas. -

-

- It provides immediate access to job markets, stable income, and often a pathway to permanent - residency. Work visas are suitable for skilled professionals who are ready to contribute to the - global workforce and achieve long-term career goals. Ultimately, the choice comes down to your - personal aspirations. If education and exploration are your priorities, a student visa is ideal. If - career advancement and stability are your goals, a work visa is the right fit. -

+ )} + + {/* Content After Quote */} + {post.contentAfterQuote && ( +
+ )} + + {/* Tags and Social Share */}
Tags: - WorkVisa - FamilyVisa - StudentVisa + {post.tags.map((tagName) => { + // Generate slug from tag name (Vietnamese-friendly) + const tagSlug = toSlug(tagName); + return ( + + {tagName} + + ); + })}
-
-
-

02 Comments

-
-
-
- image -
-
-
-
- February 10, 2024 -

Frank Flores

-
- - Reply - -
-

- Neque porro est qui dolorem ipsum quia quaed inventor veritatis et quasi architecto var sed - efficitur turpis gilla sed sit amet finibus eros. Lorem Ipsum is simply dummy -

-
-
-
-
- image -
-
-
-
-

Charlie Tushar

- February 10, 2024 -
- - Reply - -
-

- Neque porro est qui dolorem ipsum quia quaed inventor veritatis et quasi architecto var sed - efficitur turpis gilla sed sit amet finibus eros. Lorem Ipsum is simply dummy -

-
-
-
-
- image -
-
-
-
- February 10, 2024 -

Fatma Sariqul

-
- - Reply - -
-

- Neque porro est qui dolorem ipsum quia quaed inventor veritatis et quasi architecto var sed - efficitur turpis gilla sed sit amet finibus eros. Lorem Ipsum is simply dummy -

-
-
-
-

Leave A Comment

-
-
-
-
- Your Name - -
-
-
-
- Your Email - -
-
-
-
- Your Phone - -
-
-
-
- Your Address - -
-
-
-
- Your Date - -
-
-
-
- -
-
-
- -
-
-
+ +
diff --git a/app/blog/[slug]/components/NewsDetailsSection.tsx b/app/blog/[slug]/components/NewsDetailsSection.tsx index 8f088f7..de4d86d 100644 --- a/app/blog/[slug]/components/NewsDetailsSection.tsx +++ b/app/blog/[slug]/components/NewsDetailsSection.tsx @@ -1,13 +1,18 @@ import NewsDetailsContent from "./NewsDetailsContent"; import Sidebar from "@/app/blog/components/Sidebar"; +import type { BlogPost } from "@/types/blog"; -export default function NewsDetailsSection() { +interface NewsDetailsSectionProps { + post: BlogPost; +} + +export default function NewsDetailsSection({ post }: NewsDetailsSectionProps) { return (
- +
diff --git a/app/blog/[slug]/page.tsx b/app/blog/[slug]/page.tsx index eec7592..937a767 100644 --- a/app/blog/[slug]/page.tsx +++ b/app/blog/[slug]/page.tsx @@ -1,17 +1,72 @@ +import Link from "next/link"; import Breadcrumb from "@/app/components/Breadcrumb"; import NewsDetailsSection from "./components/NewsDetailsSection"; +import { fetchBlogList, fetchBlogDetail } from "@/api/blog"; +import Sidebar from "@/app/blog/components/Sidebar"; + +// Generate static params for all blog posts +export async function generateStaticParams() { + try { + const blogResponse = await fetchBlogList({ page: 1, limit: 100 }); + return blogResponse.data.blogs.map((post) => ({ + slug: post.slug, + })); + } catch (error) { + console.error("Error generating static params:", error); + return []; + } +} interface BlogDetailsPageProps { - params: { + params: Promise<{ + slug: string; + }> | { slug: string; }; } -export default function BlogDetailsPage(_props: BlogDetailsPageProps) { +export default async function BlogDetailsPage({ params }: BlogDetailsPageProps) { + // Handle both Promise and direct object + const resolvedParams = params instanceof Promise ? await params : params; + const slug = resolvedParams.slug; + + // Fetch blog detail from API + let blogResponse; + try { + blogResponse = await fetchBlogDetail(slug); + } catch { + return ( + <> + +
+
+
+
+
+
+

Post not found

+

The blog post you are looking for does not exist.

+ + Back to Blog + +
+
+ {/* Sidebar on the right */} + +
+
+
+
+ + ); + } + + const post = blogResponse.data; + return ( <> - - + + ); } diff --git a/app/blog/blog.json b/app/blog/blog.json index c547032..4a6b1d2 100644 --- a/app/blog/blog.json +++ b/app/blog/blog.json @@ -1,93 +1,170 @@ { - "title": "Blog & Tin Tức", - "subtitle": "Cập nhật thông tin mới nhất về visa và du lịch", - "featured": { - "id": "visa-schengen-2024", - "title": "Hướng Dẫn Xin Visa Schengen 2024 - Cập Nhật Mới Nhất", - "excerpt": "Thủ tục xin visa Schengen đã có những thay đổi quan trọng trong năm 2024. Cùng tìm hiểu chi tiết...", - "image": "/images/schengen-visa.jpg", - "date": "2024-01-15", - "author": "Nguyễn Văn A", - "category": "Visa", - "readTime": "5 phút đọc" - }, "categories": [ { - "name": "Tất cả", - "slug": "all", - "count": 24 + "name": "Visa & Immigration", + "slug": "visa-immigration", + "description": "Tin tức và hướng dẫn về visa, định cư." }, { - "name": "Visa", - "slug": "visa", - "count": 12 + "name": "Study Abroad", + "slug": "study-abroad", + "description": "Kinh nghiệm du học, trường học, học bổng." }, { - "name": "Du lịch", - "slug": "travel", - "count": 8 + "name": "Travel Tips", + "slug": "travel-tips", + "description": "Mẹo du lịch, chuẩn bị hành lý, bảo hiểm." + } + ], + "tags": [ + { + "name": "WorkVisa", + "slug": "work-visa" }, { - "name": "Thủ tục", - "slug": "procedures", - "count": 4 + "name": "StudentVisa", + "slug": "student-visa" + }, + { + "name": "Canada", + "slug": "canada" + }, + { + "name": "Scholarship", + "slug": "scholarship" + }, + { + "name": "TravelSafety", + "slug": "travel-safety" } ], "posts": [ { - "id": "visa-my-2024", - "title": "Thay Đổi Mới Trong Thủ Tục Xin Visa Mỹ 2024", - "excerpt": "Lãnh sự quán Mỹ đã công bố những thay đổi quan trọng trong quy trình xin visa...", - "image": "/images/us-visa.jpg", - "date": "2024-01-10", - "author": "Trần Thị B", - "category": "Visa", - "readTime": "7 phút đọc", - "tags": ["Visa Mỹ", "Thủ tục", "2024"] + "title": "Ultimate Guide To Getting A Work Visa In Canada", + "slug": "ultimate-guide-work-visa-canada", + "excerpt": "Tổng hợp đầy đủ các bước xin work visa tại Canada cho người mới bắt đầu, từ điều kiện, hồ sơ đến thời gian xử lý.", + "content": "

Trong bài viết này, chúng ta sẽ đi qua từng bước cụ thể để xin work visa Canada, từ việc chuẩn bị hồ sơ, chọn chương trình phù hợp đến cách theo dõi tiến độ xử lý hồ sơ. Bạn cũng sẽ tìm thấy một số mẹo thực tế để tránh những sai lầm phổ biến.

", + "category": ["Visa & Immigration", "Canada"], + "tags": ["WorkVisa", "Canada"], + "author": "Admin", + "status": "published", + "publishedAt": "11 March 2025", + "isFeatured": true, + "featuredImage": "/assets/img/inner-page/news-details/details-1.jpg", + "galleryImages": [ + "/assets/img/inner-page/news-details/details-2.jpg", + "/assets/img/inner-page/news-details/details-3.jpg" + ], + "quote": "This blog really helped me understand the difference between student and work visas. The explanations were clear and practical.", + "contentAfterQuote": "

It provides access to world-class universities, cultural exposure, and global networking opportunities. With a student visa, you may also get part-time work rights, which can help support your expenses and give you valuable international work experience. However, the primary focus remains on academics and personal growth. On the other hand, a work visa is perfect for those who want to establish themselves in a career overseas.

It provides immediate access to job markets, stable income, and often a pathway to permanent residency. Work visas are suitable for skilled professionals who are ready to contribute to the global workforce and achieve long-term career goals. Ultimately, the choice comes down to your personal aspirations. If education and exploration are your priorities, a student visa is ideal. If career advancement and stability are your goals, a work visa is the right fit.

", + "commentsCount": 3 }, { - "id": "du-lich-nhat-ban", - "title": "Top 10 Địa Điểm Du Lịch Nhật Bản Không Thể Bỏ Qua", - "excerpt": "Khám phá những điểm đến tuyệt vời nhất tại đất nước mặt trời mọc...", - "image": "/images/japan-travel.jpg", - "date": "2024-01-08", - "author": "Lê Văn C", - "category": "Du lịch", - "readTime": "6 phút đọc", - "tags": ["Nhật Bản", "Du lịch", "Điểm đến"] + "title": "Top 5 Scholarship Programs For International Students", + "slug": "top-5-scholarship-programs-international-students", + "excerpt": "Danh sách 5 chương trình học bổng nổi bật dành cho sinh viên quốc tế với mức hỗ trợ hấp dẫn.", + "content": "

Nếu bạn đang tìm kiếm học bổng để giảm chi phí du học, đây là 5 chương trình bạn không nên bỏ qua. Mỗi chương trình đều có tiêu chí xét tuyển, mức hỗ trợ và thời hạn đăng ký khác nhau.

Học bổng là một trong những cách tốt nhất để giảm gánh nặng tài chính khi du học. Các chương trình học bổng không chỉ hỗ trợ về mặt tài chính mà còn mở ra nhiều cơ hội phát triển nghề nghiệp và mở rộng mạng lưới quan hệ quốc tế.

", + "category": ["Study Abroad"], + "tags": ["StudentVisa", "Scholarship"], + "author": "Admin", + "status": "published", + "publishedAt": "20 March 2025", + "isFeatured": false, + "featuredImage": "/assets/img/inner-page/news-details/details-1.jpg", + "galleryImages": [ + "/assets/img/inner-page/news-details/details-2.jpg", + "/assets/img/inner-page/news-details/details-3.jpg" + ], + "quote": "These scholarship programs opened doors I never thought possible. The application process was straightforward, and the support I received was incredible.", + "contentAfterQuote": "

Applying for scholarships requires careful planning and preparation. Start by researching each program's requirements, deadlines, and eligibility criteria. Make sure to prepare all necessary documents well in advance, including transcripts, recommendation letters, and personal statements. Each scholarship has its own unique focus, so tailor your application to highlight how you align with their values and goals.

Remember that scholarship applications are competitive, so it's important to stand out. Showcase your academic achievements, extracurricular activities, and community involvement. Be authentic in your personal statement and demonstrate how the scholarship will help you achieve your educational and career aspirations. With dedication and proper preparation, you can increase your chances of securing financial support for your studies abroad.

", + "commentsCount": 2 }, { - "id": "visa-han-quoc-tips", - "title": "Bí Quyết Xin Visa Hàn Quốc Thành Công 100%", - "excerpt": "Những kinh nghiệm quý báu từ chuyên gia để tăng tỷ lệ thành công...", - "image": "/images/korea-visa.jpg", - "date": "2024-01-05", - "author": "Phạm Thị D", - "category": "Visa", - "readTime": "8 phút đọc", - "tags": ["Visa Hàn Quốc", "Kinh nghiệm", "Thành công"] + "title": "10 Travel Safety Tips You Should Know Before Flying", + "slug": "10-travel-safety-tips-before-flying", + "excerpt": "Những lưu ý quan trọng để đảm bảo an toàn cho chuyến bay và hành trình của bạn.", + "content": "

An toàn luôn là ưu tiên hàng đầu khi đi du lịch. Dưới đây là 10 tips giúp bạn yên tâm hơn trên mọi chuyến đi, từ việc chuẩn bị giấy tờ, bảo hiểm đến cách bảo vệ tài sản cá nhân.

Du lịch là một trải nghiệm tuyệt vời, nhưng điều quan trọng là phải chuẩn bị kỹ lưỡng để đảm bảo an toàn. Những tips này được đúc kết từ kinh nghiệm thực tế của nhiều du khách và sẽ giúp bạn tránh được những rủi ro không đáng có.

", + "category": ["Travel Tips"], + "tags": ["TravelSafety"], + "author": "Admin", + "status": "published", + "publishedAt": "05 April 2025", + "isFeatured": false, + "featuredImage": "/assets/img/inner-page/news-details/details-1.jpg", + "galleryImages": [ + "/assets/img/inner-page/news-details/details-2.jpg", + "/assets/img/inner-page/news-details/details-3.jpg" + ], + "quote": "These safety tips saved me from potential problems during my trip. I especially appreciated the advice about travel insurance and document preparation.", + "contentAfterQuote": "

Before you travel, make sure to research your destination thoroughly. Understand local customs, laws, and potential safety concerns. Keep copies of important documents like your passport, visa, and travel insurance in multiple places - both physical and digital. Inform family or friends about your itinerary and check in regularly during your trip.

When packing, prioritize essential items and keep valuables secure. Use luggage locks and consider travel insurance for expensive items. Stay aware of your surroundings, especially in crowded areas, and trust your instincts if something feels off. By following these safety tips, you can focus on enjoying your journey while staying protected throughout your travels.

", + "commentsCount": 1 + } + ], + "recentPosts": [ + { + "title": "Ultimate Guide To Getting A Work Visa In Canada", + "slug": "ultimate-guide-work-visa-canada", + "thumbnail": "/assets/img/inner-page/news-details/post-1.jpg", + "publishedAt": "11 March 2025" }, { - "id": "du-lich-chau-au", - "title": "Lịch Trình Du Lịch Châu Âu 14 Ngày Hoàn Hảo", - "excerpt": "Khám phá 7 quốc gia châu Âu với lịch trình được thiết kế tối ưu...", - "image": "/images/europe-travel.jpg", - "date": "2024-01-03", - "author": "Hoàng Văn E", - "category": "Du lịch", - "readTime": "10 phút đọc", - "tags": ["Châu Âu", "Lịch trình", "14 ngày"] + "title": "Top 5 Scholarship Programs For International Students", + "slug": "top-5-scholarship-programs-international-students", + "thumbnail": "/assets/img/inner-page/news-details/post-2.jpg", + "publishedAt": "20 March 2025" }, { - "id": "thu-tuc-ho-so", - "title": "Checklist Hồ Sơ Xin Visa - Không Bỏ Sót Gì", - "excerpt": "Danh sách chi tiết các giấy tờ cần thiết cho từng loại visa...", - "image": "/images/documents.jpg", - "date": "2024-01-01", - "author": "Vũ Thị F", - "category": "Thủ tục", - "readTime": "4 phút đọc", - "tags": ["Hồ sơ", "Checklist", "Visa"] + "title": "10 Travel Safety Tips You Should Know Before Flying", + "slug": "10-travel-safety-tips-before-flying", + "thumbnail": "/assets/img/inner-page/news-details/post-3.jpg", + "publishedAt": "05 April 2025" + } + ], + "comments": [ + { + "postSlug": "ultimate-guide-work-visa-canada", + "authorName": "Frank Flores", + "authorAvatar": "/assets/img/inner-page/news-details/comment-1.png", + "content": "Bài viết rất hữu ích, cảm ơn bạn đã chia sẻ!", + "createdAt": "February 10, 2024", + "status": "approved", + "parentAuthorName": null + }, + { + "postSlug": "ultimate-guide-work-visa-canada", + "authorName": "Courtney Henry", + "authorAvatar": "/assets/img/inner-page/news-details/comment-2.png", + "content": "Mình đã làm theo hướng dẫn và hồ sơ được duyệt nhanh hơn hẳn.", + "createdAt": "February 12, 2024", + "status": "approved", + "parentAuthorName": "Frank Flores" + }, + { + "postSlug": "top-5-scholarship-programs-international-students", + "authorName": "Sarah Johnson", + "authorAvatar": "/assets/img/inner-page/news-details/comment-1.png", + "content": "Cảm ơn bạn đã chia sẻ thông tin về các chương trình học bổng này. Mình đã apply và đang chờ kết quả!", + "createdAt": "March 15, 2025", + "status": "approved", + "parentAuthorName": null + }, + { + "postSlug": "top-5-scholarship-programs-international-students", + "authorName": "Michael Chen", + "authorAvatar": "/assets/img/inner-page/news-details/comment-2.png", + "content": "Bài viết rất chi tiết và hữu ích. Mình đã tìm thấy một chương trình phù hợp với mình.", + "createdAt": "March 18, 2025", + "status": "approved", + "parentAuthorName": null + }, + { + "postSlug": "10-travel-safety-tips-before-flying", + "authorName": "Jenny Wilson", + "authorAvatar": "/assets/img/inner-page/news-details/comment-3.png", + "content": "Những tip này rất thực tế, đặc biệt là phần chuẩn bị bảo hiểm!", + "createdAt": "March 02, 2024", + "status": "approved", + "parentAuthorName": null } ] } diff --git a/app/blog/category/[slug]/page.tsx b/app/blog/category/[slug]/page.tsx new file mode 100644 index 0000000..e95fdad --- /dev/null +++ b/app/blog/category/[slug]/page.tsx @@ -0,0 +1,58 @@ +import Breadcrumb from "@/app/components/Breadcrumb"; +import NewsSection from "@/app/blog/components/NewsSection"; +import Sidebar from "@/app/blog/components/Sidebar"; +import { fetchBlogsByCategory, fetchCategoryDetail } from "@/api/blog"; + +interface CategoryPageProps { + params: Promise<{ + slug: string; + }> | { + slug: string; + }; +} + +export default async function CategoryPage({ params }: CategoryPageProps) { + // Handle both Promise and direct object + const resolvedParams = params instanceof Promise ? await params : params; + const slug = resolvedParams.slug; + + // Fetch category detail and blogs + let categoryResponse, blogsResponse; + try { + [categoryResponse, blogsResponse] = await Promise.all([ + fetchCategoryDetail(slug), + fetchBlogsByCategory(slug, { page: 1, limit: 10 }), + ]); + } catch { + return ( + <> + +
+
+
+
+
+
+

Category not found

+

The category you are looking for does not exist.

+
+
+ +
+
+
+
+ + ); + } + + const category = categoryResponse.data; + const blogs = blogsResponse.data.blogs; + + return ( + <> + + + + ); +} diff --git a/app/blog/components/NewsList.tsx b/app/blog/components/NewsList.tsx index cb1736c..bf717a1 100644 --- a/app/blog/components/NewsList.tsx +++ b/app/blog/components/NewsList.tsx @@ -1,92 +1,62 @@ import Link from "next/link"; +import type { BlogPost } from "@/types/blog"; +import { getCmsImageUrl } from "@/utils"; + +interface NewsListProps { + blogs?: BlogPost[]; + categorySlug?: string; + tagSlug?: string; +} + +export default function NewsList({ blogs = [], categorySlug, tagSlug }: NewsListProps) { + // Use blogs from props (already filtered by API) + const posts = blogs; + + // Additional client-side filtering if needed (though API should handle this) + if (categorySlug || tagSlug) { + // If filters are provided but blogs are not pre-filtered, filter here + // This is a fallback - ideally API should handle filtering + } -export default function NewsList() { return (
- {/* News Post 1 */} -
-
- img + {posts.map((post, index) => ( +
+
+ {post.title} +
+
+
    +
  • + By {post.author} +
  • +
  • + {post.publishedAt} +
  • +
  • + {post.commentsCount} Comments +
  • +
+

+ {post.title} +

+

{post.excerpt}

+ + VIEW MORE + +
-
-
    -
  • - By Admin -
  • -
  • - 11 March 2025 -
  • -
  • - 0 Comments -
  • -
-

- How to Avoid Common Mistakes in Visa Applications -

-

- A business consultant provides expert guidance, strategic planning, and problem-solving support—helping startups avoid mistakes, grow faster, and operate more efficiently from day one. -

- - VIEW MORE - -
-
- {/* News Post 2 */} -
-
- img -
-
-
    -
  • - By Admin -
  • -
  • - 11 March 2025 -
  • -
  • - 0 Comments -
  • -
-

- The Role of Immigration Consultants in Your Journey -

-

- Immigration consultants play a vital role in guiding applicants, simplifying complex processes, offering expert advice, and ensuring successful outcomes for study, work, or permanent residency abroad. -

- - VIEW MORE - -
-
- {/* News Post 3 */} -
-
- img -
-
-
    -
  • - By Admin -
  • -
  • - 11 March 2025 -
  • -
  • - 0 Comments -
  • -
-

- Latest Immigration Policy Updates You Should Know -

-

- Stay informed with the latest immigration policy updates, ensuring you understand new rules, visa requirements, and opportunities that impact your study, work, or migration journey abroad. -

- - VIEW MORE - -
-
+ ))}
); } \ No newline at end of file diff --git a/app/blog/components/NewsSection.tsx b/app/blog/components/NewsSection.tsx index 4ddd43d..64a8ddf 100644 --- a/app/blog/components/NewsSection.tsx +++ b/app/blog/components/NewsSection.tsx @@ -1,15 +1,38 @@ import NewsList from "./NewsList"; import Sidebar from "./Sidebar"; +import Pagination from "./Pagination"; +import type { BlogPost, BlogPagination } from "@/types"; -export default function NewsSection() { +interface NewsSectionProps { + blogs?: BlogPost[]; + categorySlug?: string; + tagSlug?: string; + searchQuery?: string; + pagination?: BlogPagination; +} + +export default function NewsSection({ + blogs, + categorySlug, + tagSlug, + searchQuery, + pagination, +}: NewsSectionProps) { return (
- - + +
+ {pagination && pagination.total > 1 && ( +
+
+ +
+
+ )}
diff --git a/app/blog/components/Pagination.tsx b/app/blog/components/Pagination.tsx new file mode 100644 index 0000000..78c3dbc --- /dev/null +++ b/app/blog/components/Pagination.tsx @@ -0,0 +1,79 @@ +import Link from "next/link"; +import type { BlogPagination } from "@/types"; + +interface PaginationProps { + basePath: string; + pagination: BlogPagination; + searchQuery?: string; +} + +export default function Pagination({ basePath, pagination, searchQuery }: PaginationProps) { + const { current, total } = pagination; + + if (total <= 1) return null; + + const makeHref = (page: number) => { + const params = new URLSearchParams(); + if (page > 1) params.set("page", page.toString()); + if (searchQuery) params.set("search", searchQuery); + const qs = params.toString(); + return qs ? `${basePath}?${qs}` : basePath; + }; + + const pages: number[] = []; + for (let i = 1; i <= total; i++) { + if (i === 1 || i === total || (i >= current - 2 && i <= current + 2)) { + pages.push(i); + } + } + + const items: (number | "...")[] = []; + for (let i = 0; i < pages.length; i++) { + const page = pages[i]; + items.push(page); + if (i < pages.length - 1 && pages[i + 1] !== page + 1) { + items.push("..."); + } + } + + return ( + + ); +} + diff --git a/app/blog/components/Sidebar.tsx b/app/blog/components/Sidebar.tsx index 2842f4c..68321b1 100644 --- a/app/blog/components/Sidebar.tsx +++ b/app/blog/components/Sidebar.tsx @@ -1,14 +1,35 @@ import Link from "next/link"; +import { fetchCategories, fetchRecentBlogs, fetchPopularTags } from "@/api/blog"; + +interface SidebarProps { + searchQuery?: string; +} + +export default async function Sidebar({ searchQuery }: SidebarProps) { + // Fetch data from API + const [categoriesResponse, recentBlogsResponse, tagsResponse] = await Promise.all([ + fetchCategories(), + fetchRecentBlogs(5), + fetchPopularTags(10), + ]); + + const categories = categoriesResponse.data; + const recentPosts = recentBlogsResponse.data; + const tags = tagsResponse.data; -export default function Sidebar() { return (
{/* Search Widget */}
-
- + + @@ -22,11 +43,17 @@ export default function Sidebar() {
    -
  • Permanent Residency (PR)(04)
  • -
  • Immigration Policy Updates(09)
  • -
  • Scholarships & Grants(00)
  • -
  • Citizenship & Naturalization(04)
  • -
  • Visa Interview Preparation(01)
  • + {categories.map((category) => { + const postCount = category.postCount || 0; + return ( +
  • + + {category.name} + + ({String(postCount).padStart(2, "0")}) +
  • + ); + })}
@@ -36,45 +63,27 @@ export default function Sidebar() {

Recent Post

-
-
- img + {recentPosts.map((post) => ( +
+
+ {post.title} +
+
+
+ {post.title} +
+
    +
  • {post.publishedAt}
  • +
+
-
-
- Top Countries for Higher Education in 2025 -
-
    -
  • March 26, 2025
  • -
-
-
-
-
- img -
-
-
- The Benefits of Hiring a Visa Consultant -
-
    -
  • March 26, 2025
  • -
-
-
-
-
- img -
-
-
- How to Prepare for Your Immigration Interview -
-
    -
  • March 26, 2025
  • -
-
-
+ ))}
{/* Tag Cloud */} @@ -84,12 +93,11 @@ export default function Sidebar() {
- WorkVisa - FamilyVisa - StudentVisa - VisaUpdates - TravelVisa - StudyAbroad + {tags.map((tag) => ( + + {tag.name} + + ))}
diff --git a/app/blog/page.tsx b/app/blog/page.tsx index 50883a4..3c2d193 100644 --- a/app/blog/page.tsx +++ b/app/blog/page.tsx @@ -1,11 +1,33 @@ import Breadcrumb from "@/app/components/Breadcrumb"; import NewsSection from "./components/NewsSection"; +import { fetchBlogList } from "@/api/blog"; + +interface NewsPageProps { + searchParams?: Promise<{ search?: string; page?: string }> | { search?: string; page?: string }; +} + +export default async function NewsPage({ searchParams }: NewsPageProps) { + const resolvedSearchParams = + searchParams instanceof Promise ? await searchParams : searchParams; + const searchQuery = resolvedSearchParams?.search?.toString() || ""; + const pageParam = resolvedSearchParams?.page?.toString() || "1"; + const currentPage = Number.parseInt(pageParam, 10) || 1; + + // Fetch blog list from API + const blogResponse = await fetchBlogList({ + page: currentPage, + limit: 10, + ...(searchQuery ? { search: searchQuery } : {}), + }); + const { blogs, pagination } = blogResponse.data; -export default function NewsPage() { return ( <> - - + + ); } \ No newline at end of file diff --git a/app/blog/tag/[slug]/page.tsx b/app/blog/tag/[slug]/page.tsx new file mode 100644 index 0000000..c2c48cb --- /dev/null +++ b/app/blog/tag/[slug]/page.tsx @@ -0,0 +1,58 @@ +import Breadcrumb from "@/app/components/Breadcrumb"; +import NewsSection from "@/app/blog/components/NewsSection"; +import Sidebar from "@/app/blog/components/Sidebar"; +import { fetchBlogsByTag, fetchTagDetail } from "@/api/blog"; + +interface TagPageProps { + params: Promise<{ + slug: string; + }> | { + slug: string; + }; +} + +export default async function TagPage({ params }: TagPageProps) { + // Handle both Promise and direct object + const resolvedParams = params instanceof Promise ? await params : params; + const slug = resolvedParams.slug; + + // Fetch tag detail and blogs + let tagResponse, blogsResponse; + try { + [tagResponse, blogsResponse] = await Promise.all([ + fetchTagDetail(slug), + fetchBlogsByTag(slug, { page: 1, limit: 10 }), + ]); + } catch { + return ( + <> + +
+
+
+
+
+
+

Tag not found

+

The tag you are looking for does not exist.

+
+
+ +
+
+
+
+ + ); + } + + const tag = tagResponse.data; + const blogs = blogsResponse.data.blogs; + + return ( + <> + + + + ); +} diff --git a/app/components/layout/Header/HeaderTop.tsx b/app/components/layout/Header/HeaderTop.tsx index 50539b5..782dddf 100644 --- a/app/components/layout/Header/HeaderTop.tsx +++ b/app/components/layout/Header/HeaderTop.tsx @@ -6,24 +6,24 @@ const HeaderTop = () => {
-
+
  • + + get-info@hai.edu.vn +
  • + +
    diff --git a/app/layout.tsx b/app/layout.tsx index bf4d9d3..7aa78ba 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -1,16 +1,11 @@ import type { Metadata } from "next"; import "./globals.css"; - -<<<<<<< HEAD -======= - ->>>>>>> 64845c60b32397ad46cc4109974ab616fe186836 -// import Header from "./components/Header"; -// import Footer from "./components/Footer"; import Loader from "./components/Loader"; import BackToTop from "./components/BackToTop"; import MouseCursor from "./components/MouseCursor"; import Script from "next/script"; +import Header from "./components/layout/Header/Header"; +import Footer from "./components/layout/Footer/Footer"; export const metadata: Metadata = { title: "Visaway – Immigration & Visa Consulting HTML Template", @@ -51,12 +46,9 @@ export default function RootLayout({ - {/*
    */} - +
    {children} - - {/*