import { PostCarousel } from "../../components/PostCarousel.tsx";

import { Handlers, PageProps } from "$fresh/server.ts";
import { Post } from "../../types/index.ts";
import * as hi from "jsr:@preact-icons/hi2";

interface PageData {
  featuredPosts: Post[];
  recentPosts: Post[];
  hotPosts: Post[];
  popularPosts: Post[];
}

export const handler: Handlers<PageData> = {
  async GET(_, ctx) {
    const [featuredResult, recentResult, hotResult, popularResult] =
      await Promise.all([
        fetch(`${Deno.env.get("BASE_URI_API")}/posts/featured`),
        fetch(`${Deno.env.get("BASE_URI_API")}/posts/recent`),
        fetch(`${Deno.env.get("BASE_URI_API")}/posts/hot`),
        fetch(`${Deno.env.get("BASE_URI_API")}/posts/popular`),
      ]);

    // parse all JSON responses concurrently
    const [featuredPosts, recentPosts, hotPosts, popularPosts] =
      await Promise.all([
        featuredResult.json(),
        recentResult.json(),
        hotResult.json(),
        popularResult.json(),
      ]);

    return ctx.render({
      featuredPosts,
      recentPosts,
      hotPosts,
      popularPosts,
    });
  },
};

export default function PostPage({ data }: PageProps<PageData>) {
  const { featuredPosts, recentPosts, hotPosts, popularPosts } = data;

  return (
    <div class="space-y-12 px-10 py-8 bg-[#313244]">
      <h1 class="text-3xl text-white font-bold uppercase text-center">Blog</h1>
      <section>
        <div class="flex items-center gap-2 text-2xl text-white md:justify-start">
          <hi.HiOutlineSparkles />
          <h2 class="text-2xl font-bold text-white text-center lg:text-left">
            Featured Posts
          </h2>
        </div>
        <div className="text-lg font-thin italic text-white mb-4 text-center flex">
          Ignite the impossible
        </div>
        <PostCarousel posts={featuredPosts} />
      </section>
      <section>
        <div class="flex items-center gap-2 text-2xl text-white md:justify-start">
          <hi.HiOutlineClock />
          <h2 class="text-2xl font-bold text-white text-center lg:text-left">
            Recent Posts
          </h2>
        </div>
        <div className="text-lg font-thin italic mb-4 text-white text-center flex">
          Now with 100% fresh perspective
        </div>
        <PostCarousel posts={recentPosts} />
      </section>
      <section>
        <div class="flex items-center gap-2 text-2xl text-white md:justify-start">
          <hi.HiOutlineBolt />
          <h2 class="text-2xl font-bold text-white text-center lg:text-left">
            Popular Posts
          </h2>
        </div>
        <div className="text-lg font-thin italic mb-4 text-white text-center flex">
          Content may cause uncontrollable reading
        </div>
        <PostCarousel posts={popularPosts} />
      </section>
    </div>
  );
}
