// ── Laravel API client (replaces wordpress.ts) ────────────────────────────────
const API = (process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000") + "/api/v1";

export interface Post {
  id:             number;
  ulid:           string;
  slug:           string;
  title:          string;
  excerpt:        string;
  content:        string;
  featured_image: string | null;
  status:         string;
  is_featured:    boolean;
  is_breaking:    boolean;
  views_count:    number;
  reading_time:   number;
  published_at:   string;
  source_url:     string | null;
  source_name:    string | null;
  author:         { id: number; name: string } | null;
  category:       { id: number; name: string; slug: string; color: string; bg_color: string };
  country:        { id: number; name: string; slug: string; flag_emoji: string };
  continent:      { id: number; name: string; slug: string; emoji: string };
  tags:           { id: number; name: string; slug: string }[];
}

export interface PaginatedPosts {
  data:          Post[];
  total:         number;
  per_page:      number;
  current_page:  number;
  last_page:     number;
}

async function apiFetch<T>(path: string, params: Record<string, string | number> = {}): Promise<T> {
  const qs  = new URLSearchParams(Object.fromEntries(Object.entries(params).map(([k,v])=>[k,String(v)]))).toString();
  const url = `${API}${path}${qs ? `?${qs}` : ""}`;
  const res = await fetch(url, { next: { revalidate: 300 } });
  if (!res.ok) throw new Error(`API ${res.status}: ${url}`);
  return res.json();
}

// ── Posts ──────────────────────────────────────────────────────────────────────
export async function getPosts(params: {
  page?: number; perPage?: number;
  continent?: string; country?: string; category?: string;
  search?: string; tag?: string;
} = {}): Promise<PaginatedPosts> {
  const q: Record<string, string | number> = { per_page: params.perPage ?? 12, page: params.page ?? 1 };
  if (params.continent) q.continent = params.continent;
  if (params.country)   q.country   = params.country;
  if (params.category)  q.category  = params.category;
  if (params.search)    q.search    = params.search;
  if (params.tag)       q.tag       = params.tag;
  return apiFetch<PaginatedPosts>("/posts", q);
}

export async function getPostBySlug(slug: string): Promise<Post> {
  return apiFetch<Post>(`/posts/${slug}`);
}

export async function getFeaturedPosts(): Promise<Post[]> {
  return apiFetch<Post[]>("/posts/featured");
}

export async function getBreakingPosts(): Promise<Post[]> {
  return apiFetch<Post[]>("/posts/breaking");
}

export async function getTrendingPosts(): Promise<Post[]> {
  return apiFetch<Post[]>("/posts/trending");
}

export async function getRelatedPosts(slug: string): Promise<Post[]> {
  return apiFetch<Post[]>(`/posts/${slug}/related`);
}

// ── Taxonomy ───────────────────────────────────────────────────────────────────
export async function getContinents() {
  return apiFetch<any[]>("/continents");
}

export async function getContinentPosts(slug: string, page = 1) {
  return apiFetch<PaginatedPosts>(`/continents/${slug}/posts`, { page });
}

export async function getCountryPosts(slug: string, page = 1, category?: string) {
  const q: Record<string,string|number> = { page };
  if (category) q.category = category;
  return apiFetch<PaginatedPosts>(`/countries/${slug}/posts`, q);
}

export async function getCategoryPosts(slug: string, page = 1) {
  return apiFetch<PaginatedPosts>(`/categories/${slug}/posts`, { page });
}

export async function getCategories() {
  return apiFetch<any[]>("/categories");
}

// ── Helpers ────────────────────────────────────────────────────────────────────
export function postUrl(post: Post): string {
  const continent = post.continent?.slug ?? "world";
  const country   = post.country?.slug   ?? "global";
  const category  = post.category?.slug  ?? "news";
  return `/${continent}/${country}/${category}/${post.slug}`;
}

export function getFeaturedImage(post: Post): string {
  const img = post.featured_image ?? "/placeholder.jpg";
  // Next.js image optimisation runs server-side; Node.js can't resolve "localhost"
  // so we swap it for 127.0.0.1 before passing to <Image>.
  return img.replace(/^http:\/\/localhost(:\d+)?/, (_, port) => `http://127.0.0.1${port ?? ""}`);
}

export function stripHtml(html: string): string {
  return html.replace(/<[^>]*>/g, "").replace(/&[^;]+;/g, " ").trim();
}

// Keep legacy names so existing components don't break
export type WPPost = Post;
export const getLatestPosts = (count = 10) => getPosts({ perPage: count }).then(r => r.data);
export const getPostCategories = (post: Post) => post.category ? [post.category] : [];
export const getPostTags = (post: Post) => post.tags ?? [];
