import { useLocation, useNavigate } from "react-router";
import { Trans } from "@lingui/react/macro";
import { useAuth } from "../hooks/useAuth.ts";
import { type FeedTab, VALID_TABS } from "../config/feedTabs.ts";

export function FeedTabBar() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user } = useAuth();

  const rawTab = new URLSearchParams(location.search).get("tab") ?? "hot";
  const tab: FeedTab = VALID_TABS.has(rawTab) ? (rawTab as FeedTab) : "hot";

  function setTab(t: FeedTab) {
    navigate(`/?tab=${t}`, { replace: true });
  }

  return (
    <div className="feed-sort">
      <button
        type="button"
        className={`feed-sort-btn${tab === "hot" ? " active" : ""}`}
        onClick={() => setTab("hot")}
      >
        <Trans>Hot</Trans>
      </button>
      <button
        type="button"
        className={`feed-sort-btn${tab === "new" ? " active" : ""}`}
        onClick={() => setTab("new")}
      >
        <Trans>New</Trans>
      </button>
      <button
        type="button"
        className={`feed-sort-btn${tab === "journal" ? " active" : ""}`}
        onClick={() => setTab("journal")}
      >
        <Trans>Journal</Trans>
      </button>
      {user && (
        <button
          type="button"
          className={`feed-sort-btn${tab === "followed" ? " active" : ""}`}
          onClick={() => setTab("followed")}
        >
          <Trans>Followed</Trans>
        </button>
      )}
    </div>
  );
}
