// src\app\(root)\websites\page.tsx

import { Metadata } from 'next';
import WebsitesClient from './WebsitesClient';

export const metadata: Metadata = {
  title: 'All Websites | Guest Post Marketplace',
  description:
    'Browse our collection of premium websites for guest posting. Find the perfect platform to boost your SEO and online presence.',
  openGraph: {
    title: 'All Websites | Guest Post Marketplace',
    description: 'Browse our collection of premium websites for guest posting.',
    type: 'website',
  },
};

export interface searchParams {
  page?: string;
  category?: string;
  minDA?: string;
  minDR?: string;
  minTraffic?: string;
  maxPrice?: string;
  linkType?: string;
  sortBy?: string;
  sortOrder?: string;
  search?: string;
}

interface PageProps {
  searchParams: Promise<searchParams>;
}

// ─── Data fetching ─────────────────────────────────────────────────────────────

// Use NEXT_PUBLIC_APP_URL consistently across all server fetches in the project.
// Falls back to localhost for local dev.
const BASE_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

const EMPTY_WEBSITES_RESPONSE = {
  success: true,
  data: [],
  pagination: {
    current_page: 1,
    per_page: 18,
    total: 0,
    total_pages: 0,
    has_next: false,
    has_prev: false,
  },
  filters: {},
};

async function getWebsitesData(params: searchParams) {
  const qs = new URLSearchParams();
  // Only append defined, non-empty values
  const entries: [string, string | undefined][] = [
    ['page',       params.page],
    ['category',   params.category],
    ['minDA',      params.minDA],
    ['minDR',      params.minDR],
    ['minTraffic', params.minTraffic],
    ['maxPrice',   params.maxPrice],
    ['linkType',   params.linkType],
    ['sortBy',     params.sortBy],
    ['sortOrder',  params.sortOrder],
    ['search',     params.search],
  ];
  entries.forEach(([key, val]) => { if (val) qs.append(key, val); });

  try {
    const response = await fetch(`${BASE_URL}/api/frontend/allwebsites?${qs.toString()}`, {
      next: { revalidate: 60 },
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  } catch (error) {
    console.error('[WebsitesPage] Failed to fetch websites:', error);
    // Return empty state instead of 404-ing the page on transient errors
    return EMPTY_WEBSITES_RESPONSE;
  }
}

async function getCategoriesData(): Promise<unknown[]> {
  try {
    const response = await fetch(`${BASE_URL}/api/frontend/categories`, {
      next: { revalidate: 300 },
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const result = await response.json();
    return result.data || [];
  } catch (error) {
    console.error('[WebsitesPage] Failed to fetch categories:', error);
    return [];
  }
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default async function WebsitesPage({ searchParams }: PageProps) {
  const params = await searchParams;

  // Fetch both in parallel — each has its own error handling above
  const [websitesData, categories] = await Promise.all([
    getWebsitesData(params),
    getCategoriesData(),
  ]);

  return (
    <WebsitesClient
      initialData={websitesData}
      categories={categories}
      searchParams={params}
    />
  );
}