import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { ShieldAlert, X } from "lucide-react";
import { getTokenStoreMode, TokenStoreMode } from "../../services/authService";

// Per-session dismissal flag. Kept in sessionStorage so the banner
// returns on the next app launch if the fallback condition still
// holds — this matches the acceptance criteria from issue #81.
const DISMISS_KEY = "tokenStoreFallbackBannerDismissed";

export default function TokenStoreFallbackBanner() {
  const { t } = useTranslation();
  const [mode, setMode] = useState<TokenStoreMode | null>(null);
  const [dismissed, setDismissed] = useState<boolean>(() => {
    try {
      return sessionStorage.getItem(DISMISS_KEY) === "1";
    } catch {
      return false;
    }
  });

  useEffect(() => {
    let cancelled = false;
    getTokenStoreMode()
      .then((m) => {
        if (!cancelled) setMode(m);
      })
      .catch(() => {
        if (!cancelled) setMode(null);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  if (mode !== "file" || dismissed) return null;

  const dismiss = () => {
    try {
      sessionStorage.setItem(DISMISS_KEY, "1");
    } catch {
      // Ignore storage errors — the banner will simply hide for the
      // remainder of this render cycle via state.
    }
    setDismissed(true);
  };

  return (
    <div className="flex items-start gap-3 rounded-xl border border-amber-500/40 bg-amber-500/10 p-4">
      <ShieldAlert size={20} className="mt-0.5 shrink-0 text-amber-500" />
      <div className="flex-1 space-y-1 text-sm">
        <p className="font-semibold text-[var(--foreground)]">
          {t("account.tokenStore.fallback.title")}
        </p>
        <p className="text-[var(--muted-foreground)]">
          {t("account.tokenStore.fallback.description")}
        </p>
      </div>
      <button
        type="button"
        onClick={dismiss}
        aria-label={t("common.close")}
        className="shrink-0 text-[var(--muted-foreground)] hover:text-[var(--foreground)] transition-colors"
      >
        <X size={16} />
      </button>
    </div>
  );
}
