"use client";

import { toast } from "sonner";
import { useTranslation } from "react-i18next";

import AccountRow from "@/components/layout/AccountRow";
import { accountLabel } from "@/features/auth/accountLabel";
import { useAuthStore } from "@/store/authStore";
import { useSessionReady } from "@/store/useSessionReady";

/**
 * BE-129 — the other accounts this device still holds, offered on the sign-in
 * screen.
 *
 * This is what makes `endSession()` usable. When a token dies the 401
 * interceptor ends *that* session and deliberately does not promote another,
 * because continuing silently as somebody else would attribute the reader's
 * next action to an account they never chose. The sessions are kept, though —
 * and without this list there would be nothing on screen that knows it, so a
 * reader whose session expired would be asked to type a password while a
 * perfectly good session sat in `localStorage`.
 *
 * Rendered above the form, not instead of it: signing in as someone new is
 * still the common case, and the stored accounts are the shortcut.
 */
export default function StoredAccounts() {
  const { t } = useTranslation();
  const accounts = useAuthStore((state) => state.accounts);
  const switchAccount = useAuthStore((state) => state.switchAccount);
  /* Nothing until the session is known to React: the server renders no
     accounts (they live in `localStorage`), so rendering them on the
     hydration pass is the one thing that would make the two disagree. */
  const sessionReady = useSessionReady();

  if (!sessionReady || accounts.length === 0) return null;

  const onSelect = (id: number, name: string) => {
    switchAccount(id);
    toast.success(t("COMMON.TOAST.ACCOUNT_SWITCHED", { name }));
    /* `assign("/")`, not a reload: the reader is on `/login`, which the guard
       would immediately bounce them off anyway, and home is where a fresh
       sign-in lands. */
    window.location.assign("/");
  };

  return (
    <div className="mx-auto mb-8 w-[90%] max-w-[568px] rounded-2xl border border-[#29246D1A] p-4 2xl:w-[568px] lg:w-[568px]">
      <p className="px-4 pb-2 text-sm font-bold text-secondary-102">
        {t("COMMON.OTHER_ACCOUNTS_ON_DEVICE")}
      </p>
      <ul>
        {accounts.map((account) => (
          <AccountRow
            key={account.id}
            account={account}
            profilePic={account.profile_pic}
            onSelect={() => onSelect(account.id, accountLabel(account))}
          />
        ))}
      </ul>
    </div>
  );
}
