You are a senior-level Next.js, React, TypeScript, and frontend architecture expert.

Task:
Perform a full production-grade audit and optimization of the entire Next.js frontend codebase.

Main goals:

- Reduce CPU usage
- Reduce memory usage
- Reduce unnecessary background processing
- Improve rendering performance
- Reduce bundle size
- Reduce duplicated code
- Simplify architecture
- Improve maintainability
- Convert codebase to clean senior-level production architecture

CRITICAL RULE:
DO NOT break or remove existing working business logic, UI flow, APIs, authentication flow, payment flow, routing flow, Redux flow, or application behavior.

VERY IMPORTANT:

- Preserve existing functionality.
- Preserve existing design/UI behavior.
- Preserve existing API integration flow.
- Preserve existing routing/navigation flow.
- Preserve current response structure and business logic.
- Preserve all working features.
- Do not remove features unless absolutely unnecessary and clearly mentioned.
- Refactor safely without changing app behavior.
- All optimizations must maintain backward compatibility.
- Validate functionality after every optimization/refactor.
- Ensure final app behavior remains identical for users/admins.
- Avoid risky refactors that may break production flow.
- Maintain existing project architecture where necessary while improving code quality.

The application contains:

- Next.js frontend
- React components
- TypeScript
- animations
- auto scrolling
- loops
- timers
- intervals
- reels/video/audio pages
- infinite scroll
- mini players
- API polling
- Redux/Context state management
- dynamic rendering
- loaders/skeletons
- responsive layouts
- reusable UI components

====================================================

1. # CODEBASE CLEANUP + SENIOR LEVEL REFACTORING

Audit entire project structure and refactor code like a senior production-grade engineer.

Requirements:

- Reduce unnecessary lines of code.
- Remove duplicated logic.
- Merge repeated component logic into reusable shared components/hooks/utils.
- Replace copy-paste implementations with reusable architecture.
- Remove dead code and unused files.
- Remove unused imports, variables, functions, states, and dependencies.
- Simplify overly complex logic.
- Improve folder structure and scalability.
- Convert messy code into clean maintainable architecture.
- Follow production-level coding standards.
- Improve readability and maintainability.

Ensure:

- DRY principle
- reusable hooks
- reusable utility functions
- reusable UI components
- centralized constants/configs
- scalable architecture

# ==================================================== 2. REACT RENDER OPTIMIZATION

- Detect unnecessary re-renders.
- Add React.memo where appropriate.
- Use useMemo for expensive calculations.
- Use useCallback for callbacks passed to child components.
- Avoid creating objects/functions inline inside render.
- Prevent parent re-renders from rerendering entire lists/pages.
- Split heavy components into smaller memoized components.

# ==================================================== 3. useEffect + STATE LOOP VALIDATION

- Detect infinite useEffect loops.
- Validate dependency arrays properly.
- Remove repeated setState loops.
- Prevent repeated router.push/navigation loops.
- Ensure APIs are not called repeatedly on every render.
- Prevent multiple state updates inside loops.

# ==================================================== 4. TIMER / INTERVAL / ANIMATION CLEANUP

Find and optimize:

- setInterval
- setTimeout
- requestAnimationFrame
- auto scrolling loops
- marquee animations
- GSAP loops
- framer-motion infinite animations
- Lottie animations
- CSS infinite animations

Requirements:

- Stop animations when component hidden/unmounted.
- Pause animations when tab inactive.
- Cleanup all timers/listeners properly.
- Avoid continuously running background loops.
- Avoid high FPS animation loops.
- Replace JS animations with optimized CSS where possible.
- Prevent multiple intervals running simultaneously.

# ==================================================== 5. AUTO SCROLL / LOOP OPTIMIZATION

Check:

- auto scroll sliders
- infinite horizontal lists
- ticker/marquee
- reels scrolling
- autoplay carousels

Optimize:

- use requestAnimationFrame carefully
- throttle updates
- pause when offscreen
- avoid rerendering entire list during scroll
- avoid DOM calculations every frame
- stop loops when user inactive

# ==================================================== 6. VIDEO / AUDIO / REELS OPTIMIZATION

Check:

- hidden videos still playing
- multiple videos mounted
- autoplay misuse
- unnecessary preloading
- duplicate audio instances
- event listener leaks
- waveform/player rerenders

Optimize:

- render only visible media
- pause hidden media
- lazy load players
- cleanup media listeners
- use IntersectionObserver
- use preload="metadata"
- avoid rendering all reels simultaneously

# ==================================================== 7. API + NETWORK OPTIMIZATION

- Detect repeated API polling.
- Detect APIs called during render.
- Add debounce for search inputs.
- Add throttle for scroll/network actions.
- Prevent duplicate requests.
- Add caching where possible.
- Optimize websocket reconnect loops.
- Validate polling intervals.

# ==================================================== 8. SCROLL + EVENT LISTENER OPTIMIZATION

Check:

- scroll listeners
- resize listeners
- mousemove listeners
- visibilitychange listeners
- observers

Requirements:

- cleanup listeners properly
- debounce/throttle handlers
- use passive listeners where possible
- avoid attaching listeners repeatedly

# ==================================================== 9. NEXT.JS OPTIMIZATION

Validate:

- dynamic imports for heavy components
- image optimization
- code splitting
- standalone build
- static rendering where possible
- SSR usage
- hydration issues
- large client bundles
- bundle duplication

Optimize:

- use next/dynamic
- use next/image
- reduce client components
- reduce hydration load
- move static content to server/static rendering

# ==================================================== 10. LARGE LIST + DOM OPTIMIZATION

- Detect huge rendered lists.
- Add virtualization where needed.
- Add pagination/lazy loading.
- Avoid rendering hidden DOM elements.
- Avoid unnecessary map rerenders.

# ==================================================== 11. CONTEXT / REDUX OPTIMIZATION

Check:

- global state rerendering whole app
- unstable provider values
- unnecessary selector updates
- huge objects in context

Optimize:

- memoize provider values
- split contexts
- reduce rerender propagation

# ==================================================== 12. MEMORY LEAK DETECTION

Detect:

- leaked intervals
- leaked listeners
- leaked observers
- leaked media instances
- leaked refs
- leaked promises
- leaked subscriptions

Ensure proper cleanup everywhere.

# ==================================================== 13. PRODUCTION PERFORMANCE VALIDATION

Ensure:

- no unnecessary console.logs
- no dev-only code
- no debug loops
- no continuous CPU usage
- no unnecessary rerender chains

Validate:

- smooth scrolling
- low idle CPU
- stable PM2 memory
- no browser lag
- no hidden background processing

# ==================================================== 14. VPS PRODUCTION SAFETY

Ensure app is optimized for:

- low VPS CPU
- low RAM
- multiple Next.js apps running simultaneously
- staging server environments
- PM2 production deployment

Avoid:

- unnecessary SSR
- unnecessary polling
- heavy runtime animations
- excessive client-side rendering

# ==================================================== 15. CODE QUALITY + ARCHITECTURE STANDARDS

Convert codebase into:

- scalable architecture
- reusable structure
- modular codebase
- production-grade standards
- clean senior developer code style

Ensure:

- proper naming conventions
- reusable abstractions
- feature-based structure where needed
- proper separation of concerns
- minimal duplication
- optimized imports
- proper TypeScript typings
- better maintainability

# ==================================================== 16. VALIDATION + SAFETY CHECKS

Before changing any code:

- Understand current functionality completely.
- Verify dependencies between components/modules.
- Avoid breaking shared reusable flows.
- Ensure all optimized code passes TypeScript validation.
- Ensure no routing breakage.
- Ensure no API payload changes.
- Ensure no UI/UX regression.
- Ensure no feature regression.
- Ensure all pages/components still function correctly.

After optimization:

- Validate builds successfully.
- Validate no hydration errors.
- Validate no runtime console errors.
- Validate no broken navigation.
- Validate no broken media playback.
- Validate no broken forms/authentication.
- Validate no broken responsive layouts.

# ==================================================== 17. FINAL OUTPUT REQUIRED

Provide:

- list of detected issues
- optimized code fixes
- refactored reusable solutions
- duplicated logic findings
- files/components needing cleanup
- rendering bottlenecks
- high CPU risk areas
- memory leak risks
- unnecessary background processes
- reusable architecture suggestions
- production optimization summary
- code simplification opportunities
- senior-level refactor recommendations
- list of preserved flows/features
- validation checklist after refactor

Goal:
Make the entire frontend lightweight, maintainable, reusable, scalable, production-safe, and optimized for low CPU usage on VPS environments while preserving all existing functionality and business logic.

# ==================================================== 18. API CENTRALIZATION + DUPLICATE API PREVENTION

Detect APIs that are being called from multiple pages/components repeatedly.

Examples:

- general_setting
- profile
- get_page
- get_type
- get_category
- common dropdown/list APIs
- app config APIs
- shared home APIs

Requirements:

- Prevent duplicate API calls across multiple components/pages.
- Avoid calling same API again if data already exists globally.
- Centralize shared/common APIs into reusable global store/service/provider.
- Implement proper caching strategy for common APIs.
- Use singleton/shared fetch patterns where appropriate.
- Avoid repeated API calls during navigation.
- Avoid repeated API calls on every render/mount.
- Store common API responses globally when possible.
- Reuse already fetched data instead of refetching repeatedly.
- Optimize API lifecycle and dependency flow.
- Reduce unnecessary network usage and backend load.

Validate:

- same API is not triggered multiple times simultaneously
- APIs are not recalled unnecessarily after route changes
- APIs are not repeatedly triggered from layouts/components/hooks

Suggested optimization approaches:

- React Query / SWR caching
- Redux global storage
- Context caching
- custom shared hooks
- memoized API providers
- request deduplication

# ==================================================== 19. USER INACTIVITY OPTIMIZATION

Detect continuous running processes when user is inactive.

Requirements:

- If user inactive for 10 minutes:
  - pause animations
  - pause auto scrolling
  - pause requestAnimationFrame loops
  - pause marquee/ticker loops
  - pause unnecessary intervals/timeouts
  - pause background polling where possible
  - reduce unnecessary rerenders
  - stop hidden background activity

Detect inactivity using:

- mouse movement
- touch events
- keyboard interaction
- visibilitychange
- focus/blur events

When user becomes active again:

- safely resume required processes
- resume animations only where needed
- resume polling only where necessary

Ensure:

- no memory leaks
- no duplicate resume handlers
- no multiple inactivity timers
- no broken UI after resume

Goal:
Prevent unnecessary CPU usage and background processing when staging/demo users leave browser tabs open without interaction for long periods.

# ==================================================== 20. MAJOR CPU KILLER CHECKLIST

Audit and fix the most common code-level issues that can cause high CPU usage on VPS production/staging servers.

## 20.1 Avoid Using SSR Everywhere

Using SSR everywhere is one of the biggest CPU killers in Next.js.

Bad pattern:

```ts
export async function getServerSideProps() {
  const res = await fetch(API);
  const data = await res.json();

  return { props: { data } };
}
This runs:

on every request
for every visitor
on every page refresh
and can create repeated API + database load

This can quickly increase CPU usage when multiple users or multiple Next.js apps are running on the same VPS.

Better solutions:

Static Generation
ISR
Server Component caching
Client-side fetching where suitable

Example:

export async function getStaticProps() {
  return {
    props: {},
    revalidate: 60,
  };
}

For App Router, prefer:

fetch(API_URL, {
  next: { revalidate: 60 },
});

Goal:
Reduce server rendering work and avoid rendering every page on every request.

20.2 Avoid Rendering Heavy Components on Server

Do not SSR heavy browser-only components unnecessarily.

Check components like:

video players
audio players
reels players
charts
maps
editors
animation-heavy sections
large third-party libraries

Bad pattern:

import VideoPlayer from "@/components/VideoPlayer";

If the component uses browser APIs, media processing, animation libraries, or large dependencies, SSR can become expensive.

Better solution:

import dynamic from "next/dynamic";

const VideoPlayer = dynamic(() => import("@/components/VideoPlayer"), {
  ssr: false,
});

Goal:
Lazy load heavy components only in the browser and reduce server CPU usage.

20.3 Add Proper API Caching

Avoid uncached API calls on every page load.

Bad pattern:

await fetch(API_URL);

Better pattern:

await fetch(API_URL, {
  next: { revalidate: 60 },
});

Also consider:

React Query staleTime
SWR cache
Redux shared cache
Redis cache for backend/API layer
request deduplication

Goal:
Avoid repeated API calls, reduce backend load, and reduce VPS CPU usage.

20.4 Image Optimization Strategy for Small VPS

Next.js image optimization can increase CPU usage on small VPS servers, especially with:

many thumbnails
banners
posters
screenshots
user-uploaded images
product images
video covers

For small VPS or staging servers, use:

images: {
  unoptimized: true,
}

Then optimize images using:

Cloudflare
CDN image optimization
compressed WebP/AVIF images
proper image dimensions
lazy loading
external image optimization service

Goal:
Avoid VPS CPU spikes caused by runtime image resizing/optimization.

20.5 Prevent Large Re-render / API Loops

Check all useEffect usage.

Bad pattern:

useEffect(() => {
  fetchData();
});

This runs after every render and can cause:

infinite renders
repeated API calls
CPU spikes
backend/API spam

Correct pattern:

useEffect(() => {
  fetchData();
}, []);

Also validate:

dependency arrays are correct
setState does not trigger repeated effects
router.push is not called repeatedly
API calls are not triggered on every render

Goal:
Prevent render loops and repeated network calls.

20.6 Optimize Real-Time Features

Apps like DTTube, DTPocketFM, DTLive, DTTrends, radio, reels, and streaming platforms may use:

live chat
websocket
notifications
live streaming
polling
real-time counters
presence status

Bad pattern:

setInterval(() => {
  fetchNotifications();
}, 1000);

This is dangerous because it runs for every active user and can overload the server.

Better solutions:

WebSocket
Socket.io rooms
Redis pub/sub
polling every 30–60 seconds
pause polling when tab is hidden
stop polling after user inactivity
cleanup intervals on unmount
avoid duplicate socket connections

Goal:
Reduce continuous background CPU usage and avoid real-time feature overload.
```

# ==================================================== 23. NEXT.JS RSC + PREFETCH OPTIMIZATION

Audit excessive Next.js App Router `_rsc` requests and route prefetch behavior.

Check for:

- excessive `_rsc` requests
- repeated server component payload fetches
- aggressive route prefetching
- layout rerender loops
- repeated navigation fetches
- dynamic layout rendering
- unnecessary server payload refreshes

Optimize:

- disable unnecessary Link prefetching
- add prefetch={false} for heavy routes/lists
- cache shared server fetches
- add proper revalidate/cache settings
- reduce dynamic rendering
- prevent layout/provider rerender chains
- reduce repeated RSC payload requests
- optimize App Router navigation behavior

Validate:

- layouts are not rerendering unnecessarily
- providers are stable
- server fetches are cached
- route navigation is lightweight
- excessive `_rsc` requests are reduced

Goal:
Reduce unnecessary App Router server requests, lower VPS CPU usage, and optimize Next.js navigation/runtime performance.
========================================================================================================================
==================================================== 22. ADVANCED FRONTEND PERFORMANCE OPTIMIZATION
==============================================

Perform advanced production-grade frontend optimization focused on runtime performance, browser CPU reduction, rendering stability, hydration reduction, memory optimization, and staging VPS efficiency.

====================================================
A. HYDRATION + CLIENT RUNTIME REDUCTION
=======================================

- Reduce unnecessary hydration.
- Minimize browser-side JavaScript execution.
- Avoid full-page hydration where unnecessary.
- Hydrate only interactive islands/components.
- Reduce client-side rendering chains.
- Reduce nested client wrappers/providers.
- Reduce excessive useState/useEffect usage.
- Prefer server-rendered/static content where possible.

Validate:

- no unnecessary hydration
- no unnecessary client rendering
- no large client-side component trees
- no heavy client layouts

====================================================
B. PROVIDER + GLOBAL STATE OPTIMIZATION
=======================================

Audit all:

- Providers
- Contexts
- Redux stores
- Global wrappers

Optimize:

- split heavy providers
- prevent global rerenders
- memoize provider values
- avoid passing unstable objects/functions
- reduce global state dependencies
- avoid unnecessary subscriptions

Prevent:

- full app rerenders
- provider rerender chains
- global rendering bottlenecks

====================================================
C. ANIMATION + GPU/CPU OPTIMIZATION
===================================

Audit all animations:

- framer-motion
- GSAP
- CSS animations
- requestAnimationFrame
- Swiper autoplay
- marquee/ticker
- skeleton shimmer
- transitions

Optimize:

- avoid infinite runtime loops
- pause animations when offscreen
- pause animations on inactive tab
- reduce repaint/reflow cost
- replace JS animations with CSS where possible
- avoid animating large DOM trees
- reduce animation FPS/load
- reduce heavy blur/shadow/backdrop-filter usage

Prevent:

- continuous CPU/GPU usage
- hidden background animation loops
- layout thrashing
- unnecessary repaints

====================================================
D. VIDEO / AUDIO / MEDIA OPTIMIZATION
=====================================

Audit:

- reels
- autoplay videos
- audio players
- mini players
- hidden media
- waveform visualizers

Optimize:

- only one active media instance
- pause hidden media
- cleanup listeners properly
- avoid multiple mounted videos
- lazy load media players
- use IntersectionObserver
- use preload="metadata"
- stop hidden autoplay
- destroy unused media instances

====================================================
E. API + NETWORK RUNTIME OPTIMIZATION
=====================================

Audit:

- repeated polling
- duplicated requests
- repeated settings/profile/category calls
- simultaneous API flooding

Optimize:

- centralized API caching
- request deduplication
- React Query/SWR caching
- Redux shared API storage
- cancel old requests
- debounce searches
- throttle scroll/network events
- reduce unnecessary background polling

Prevent:

- same API called from multiple components
- duplicate requests during navigation
- repeated requests after rerender

====================================================
F. LARGE DOM + LIST OPTIMIZATION
================================

Audit:

- large lists
- product grids
- comments
- reels feeds
- long DOM trees

Optimize:

- virtualization
- lazy rendering
- pagination
- incremental rendering
- avoid hidden DOM rendering
- reduce DOM depth

Prevent:

- huge mounted DOM trees
- full list rerenders
- expensive layout calculations

====================================================
G. BROWSER PERFORMANCE OPTIMIZATION
===================================

Optimize:

- reduce scripting time
- reduce paint time
- reduce layout shifts
- reduce memory retention
- reduce garbage collection pressure
- reduce bundle execution cost

Validate:

- no layout thrashing
- no forced synchronous layouts
- no large memory spikes
- no long main-thread blocking

====================================================
H. MOBILE PERFORMANCE OPTIMIZATION
==================================

Ensure:

- smooth scrolling on low-end devices
- low memory usage on mobile
- reduced animation load on mobile
- optimized touch performance
- lightweight rendering on smaller devices

Prevent:

- mobile lag
- scroll stuttering
- excessive GPU usage

====================================================
I. STATIC ASSET + BUNDLE OPTIMIZATION
=====================================

Audit:

- images
- icons
- fonts
- CSS
- JS bundles

Optimize:

- reduce font weights
- remove unused assets
- optimize imports
- enable tree shaking
- reduce bundle duplication
- split large chunks
- lazy load heavy libraries
- optimize next/image usage
- optimize Swiper/framer-motion imports

Prevent:

- oversized JS bundles
- unnecessary chunk loading
- duplicate package inclusion

====================================================
J. BACKGROUND PROCESS OPTIMIZATION
==================================

If user inactive for 10 minutes:

- pause animations
- pause auto scrolling
- pause polling
- pause requestAnimationFrame loops
- reduce background rendering activity

Detect inactivity using:

- mouse movement
- keyboard interaction
- touch interaction
- visibilitychange
- focus/blur events

Resume safely when user active again.

Prevent:

- multiple inactivity timers
- memory leaks
- duplicate resume handlers

====================================================
K. STAGING SERVER + VPS OPTIMIZATION
====================================

Optimize specifically for:

- multiple Next.js apps on same VPS
- PM2 deployment
- limited CPU/RAM environments
- temporary testing/demo staging environments

Reduce:

- idle CPU usage
- unnecessary SSR
- continuous runtime activity
- excessive background tasks
- unnecessary Node.js workload

Ensure:

- stable PM2 memory usage
- low idle resource consumption
- production-safe deployment behavior

====================================================
L. SAFE REFACTORING RULES
=========================

IMPORTANT:
Do NOT break or remove:

- business logic
- API flow
- authentication
- payment flow
- Redux flow
- routing/navigation
- UI/UX behavior
- media playback flow
- existing features

Avoid:

- risky rewrites
- over-optimization
- architecture-breaking changes
- unstable refactors

Prefer:

- incremental safe optimization
- maintainable architecture
- scalable senior-level code structure

====================================================
M. FINAL OUTPUT REQUIRED
========================

Provide:

- detected performance issues
- rendering bottlenecks

- hydration bottlenecks
- animation CPU risks
- media performance issues
- duplicated API issues
- memory leak risks
- oversized bundle findings
- unnecessary runtime processes
- reusable optimization opportunities
- safe refactor suggestions
- production optimization summary
- VPS stability recommendations

Goal:
Create a lightweight, scalable, maintainable, senior-level production frontend optimized for low CPU usage, low memory usage, smooth rendering, stable PM2 deployment, and efficient multi-app VPS environments while preserving all existing functionality.
============================================================================================================================================================================================================================================================
