import { useEffect, useState } from "react";
import { useT } from "../../i18n-context";
import { CheckRoundedIcon } from "../../../shared/icons";
import styles from "./SaveToast.module.scss";

interface SaveToastProps {
  show: boolean;
  timestamp: number;
  onHide: () => void;
}

export function SaveToast({ show, timestamp, onHide }: SaveToastProps) {
  const t = useT();
  const [visible, setVisible] = useState(false);
  const [prevTimestamp, setPrevTimestamp] = useState(timestamp);

  // Adjust state during render (React recommended pattern for derived state)
  if (show && timestamp !== prevTimestamp) {
    setVisible(true);
    setPrevTimestamp(timestamp);
  }
  // When show is cleared externally (e.g. window blur handler), sync visible so
  // the component doesn't stay rendered at opacity:1 forever.
  if (!show && visible) {
    setVisible(false);
  }

  useEffect(() => {
    if (show) {
      const timer = setTimeout(() => {
        setVisible(false);
        setTimeout(onHide, 300);
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [show, timestamp, onHide]);

  useEffect(() => {
    if (show && visible) {
      const failsafe = setTimeout(() => {
        setVisible(false);
        onHide();
      }, 5000);
      return () => clearTimeout(failsafe);
    }
  }, [show, visible, onHide]);

  if (!show && !visible) return null;

  return (
    <div className={`${styles.toast} ${visible ? styles.visible : styles.hidden}`}>
      <CheckRoundedIcon width={13} height={13} />
      {t("ui.settingsSaved")}
    </div>
  );
}
