// eslint-disable-next-line @typescript-eslint/no-explicit-any
const API_URL = (process.env as any).NEXT_PUBLIC_WORDPRESS_API_URL as string;

export async function getPosts(): Promise<any[]> {
  const query = `
    {
      posts(first: 10) {
        nodes {
          title
          slug
          date
          excerpt
          featuredImage {
            node {
              sourceUrl
            }
          }
        }
      }
    }
  `;

  const res = await fetch(API_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query }),
    next: { revalidate: 60 },
  } as RequestInit);

  const json: any = await res.json();
  return json.data.posts.nodes;
}

export async function getPost(slug: string): Promise<any> {
  const query = `
    {
      post(id: "${slug}", idType: SLUG) {
        title
        date
        content
        featuredImage {
          node {
            sourceUrl
          }
        }
      }
    }
  `;

  const res = await fetch(API_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query }),
    next: { revalidate: 60 },
  } as RequestInit);

  const json: any = await res.json();
  const post = json.data.post;

  if (!post) return null;

  // Substitui iframes do YouTube por versão responsiva e com lazy loading
  post.content = post.content.replace(
    /<iframe[^>]*src="([^"]*youtube[^"]*)"[^>]*><\/iframe>/gi,
    (match: string, src: string) => {
      // Extrai o ID do vídeo
      const videoId = src.match(/embed\/([^?]+)/)?.[1] ||
                      src.match(/v=([^&]+)/)?.[1];
      if (!videoId) return match;
      return `<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;border-radius:12px;margin:1.5rem 0">
        <iframe
          src="https://www.youtube.com/embed/${videoId}?loading=lazy"
          style="position:absolute;top:0;left:0;width:100%;height:100%;border:0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowfullscreen
          loading="lazy"
        ></iframe>
      </div>`;
    }
  );

  return post;
}
