"use client";

import { AdSlot } from "@/components/AdSlot";

import { NewPostsBanner } from "@/components/NewPostsBanner";

import { useSite } from "@/lib/site-context";

import clsx from "clsx";

import { useEffect, useState, useCallback } from "react";
import { Bookmark, Wand2, User, Users, Clock, FileText, Star } from "lucide-react";
import { CreatePostTrigger } from "@/components/CreatePostTrigger";
import { PostCard as DefaultPostCard } from "@/components/PostCard";
import { slot, pageSlot } from "@/lib/theme-registry";
import { PeopleYouMightKnow, ReelsStrip } from "@/components/FeedSuggestions";
import { RightRail } from "@/components/RightRail";
import { useCreatePost } from "@/lib/create-post-context";
import { useAuth } from "@/lib/auth-context";
import { useConnectionWords } from "@/lib/site-context";
import type { Post } from "@/lib/types";

/**
 * The feed tabs.
 *
 * On a friends site "Following" and "Mutuals" are the same set of people
 * -- a connection there is mutual by definition -- so the two collapse
 * into one Friends tab rather than sitting next to each other showing
 * identical results.
 */
const tabsFor = (friendly: boolean): { label: string; feed: string; icon: typeof Wand2 }[] => [
  { label: "For You", feed: "foryou", icon: Wand2 },
  ...(friendly
    ? [{ label: "Friends", feed: "friends", icon: Users }]
    : [
        { label: "Following", feed: "following", icon: User },
        { label: "Mutuals", feed: "friends", icon: Users },
      ]),
  { label: "Posts", feed: "posts", icon: FileText },
  { label: "Favorites", feed: "favorites", icon: Star },
  { label: "Saved", feed: "saved", icon: Bookmark },
];

const EMPTY_MESSAGES: Record<string, string> = {
  following: "Posts from people you follow will show up here.",
  friends: "Posts from mutual follows (you follow each other) will show up here.",
  /** The same tab, worded for a friends site. */
  friendsFriendly: "Posts from your friends will show up here.",
  favorites: "Posts you save will show up here.",
};

function DefaultHome() {
  // A theme's home page, if it brought one. It draws the whole thing —
  // its own composer, tabs and rails — rather than filling a frame with
  // the default site's pieces.
  // A theme brings its own frame and rails, so the page drops its
  // wrapper and its right column rather than drawing a second set.
  const themed = Boolean(slot("Shell", null as never));

  // A theme's card, or the site's own.
  const PostCard = slot("PostCard", DefaultPostCard);

  const { greeting } = useSite();
  const cw = useConnectionWords();
  const tabs = tabsFor(cw.mode === "friend");
  const [posts, setPosts] = useState<Post[]>([]);
  const [tab, setTab] = useState(tabs[0]);
  const [loaded, setLoaded] = useState(false);
  const { postsVersion } = useCreatePost();
  const { user } = useAuth();

  const load = useCallback((feed: string) => {
    setLoaded(false);
    fetch(`/api/posts?feed=${feed}`)
      .then((r) => r.json())
      .then((data) => {
        setPosts(data);
        setLoaded(true);
      });
  }, []);

  useEffect(() => {
    load(tab.feed);
  }, [load, tab, postsVersion]);

  const body = (
    <>
      {greeting && <p className="feed-greeting">{greeting}</p>}

        <div className="feed-tabs sticky top-0 z-30 overflow-x-auto scrollbar-none">
          {tabs.map((t) => (
            <button
              key={t.label}
              onClick={() => setTab(t)}
              className={clsx("feed-tab shrink-0", t.label === tab.label && "on")}
            >
              <t.icon size={14} />
              {t.label}
            </button>
          ))}
        </div>

        <div className="feed-frame w-full border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-black">
        {/* Composer first, then stories — matching the reference order. */}
        <div className="pt-4 pb-3 px-4 border-b border-neutral-100 dark:border-neutral-900">
          <CreatePostTrigger />
        </div>

        <div className="px-4 py-3 border-b border-neutral-100 dark:border-neutral-900">
        </div>
      {/* How many have arrived since this loaded. The feed doesn't move
          on its own — reading something while it jumps is unpleasant. */}
      <NewPostsBanner
        feed={tab.feed}
        newestSeen={posts[0]?.createdAt ?? null}
        onShow={() => load(tab.feed)}
      />


        <div className="mt-2">
          {posts.map((p, i) => (
            <div key={p.id}>
              {i === 3 && <AdSlot />}
              <PostCard
                post={p}
                inSavedList={tab.feed === "saved"}
                onDeleted={(id: string) => setPosts((ps) => ps.filter((post) => post.id !== id))}
                onAuthorBlocked={(authorId: string) =>
                  setPosts((ps) => ps.filter((post) => post.author.id !== authorId))
                }
              />
              {/* Break the feed up with discovery sections rather than an
                  unbroken wall of posts. */}
              {i === 2 && <PeopleYouMightKnow />}
              {i === 5 && <ReelsStrip />}
              {/* On short feeds, still show both by falling back to the end. */}
              {posts.length < 3 && i === posts.length - 1 && (
                <>
                  {posts.length <= 1 && <PeopleYouMightKnow />}
                  <ReelsStrip />
                </>
              )}
            </div>
          ))}
          {loaded && posts.length === 0 && (
            <p className="text-center text-neutral-400 text-sm py-16">
              {!user
                ? "Log in to see this feed."
                : EMPTY_MESSAGES[
                    cw.mode === "friend" && tab.feed === "friends"
                      ? "friendsFriendly"
                      : tab.feed
                  ] || "Nothing here yet."}
            </p>
          )}
        </div>
        </div>
    </>
  );

  // Themed: the theme's Shell has already put the columns in place, so
  // this is just what goes in the middle one.
  if (themed) return body;

  return (
    <div className="flex w-full">
      <main className="app-col shrink-0">{body}</main>
      <RightRail />
    </div>
  );
}

/**
 * The route.
 *
 * A theme may bring its own home page — the golden theme does, because
 * its feed is ordered differently and has its own tabs. Anything without
 * one gets the page above unchanged.
 */
export default function HomeRoute() {
  const Page = pageSlot("/", DefaultHome);
  return <Page />;
}
