// Rôle : regroupe les modales, notifications et viewers rendus au-dessus de l'application.
import React from "react";
import { Icon } from "./Icon.jsx";
import { ImageViewer } from "./ImageViewer.jsx";
import { ConfirmModal, CreateToolboxModal, LinkToolboxModal, NotificationToast } from "./ToolboxModals.jsx";
import { navigate } from "../router/hashRouter.js";
import { uid } from "../features/toolboxes/storage/toolboxStorage.js";

export function InlineNotice({ className = "", iconName = "link", message, tone = "warning" }) {
  if (!message) return null;
  const classes = ["inline-notice", `is-${tone}`, className].filter(Boolean).join(" ");
  return (
    <span className={classes} role="status">
      <Icon name={iconName} />
      <span>{message}</span>
    </span>
  );
}

export function AppOverlays({
  actions,
  confirmModal,
  setConfirmModal,
  createModal,
  setCreateModal,
  linkModalGameId,
  setLinkModalGameId,
  setDrawerGameId,
  storageError,
  setStorageError,
  image,
  setImage,
  notifications,
  dismissNotification,
  toastPosition,
  getGame,
  toolboxes,
  links
}) {
  return (
    <>
      {confirmModal && <ConfirmModal {...confirmModal} onClose={(value) => {
        const onResolve = confirmModal.onResolve;
        setConfirmModal(null);
        onResolve?.(value);
      }} />}
      {createModal && <CreateToolboxModal gameId={createModal.gameId || ""} initialName={getGame(createModal.gameId)?.title || ""} onClose={(name) => {
        const gameId = createModal.gameId || "";
        setCreateModal(null);
        if (!name) return;
        const toolbox = actions.createToolbox(name, gameId);
        if (toolbox && gameId) setDrawerGameId(gameId);
        else if (toolbox) navigate(`/toolbox/${toolbox.id}`);
      }} />}
      {linkModalGameId && <LinkToolboxModal gameId={linkModalGameId} toolboxes={toolboxes} selectedId={links[linkModalGameId] || ""} onClose={(toolboxId) => {
        const gameId = linkModalGameId;
        setLinkModalGameId("");
        if (toolboxId == null) return;
        actions.linkToolboxToGame(gameId, toolboxId);
        setDrawerGameId(gameId);
      }} />}
      {storageError && <ConfirmModal title="Quota local atteint" message={storageError} confirmLabel="Compris" cancelLabel="Fermer" danger onClose={() => setStorageError("")} />}
      {image && <ImageViewer image={image} onClose={() => setImage(null)} createMarkerId={() => uid("marker")} />}
      {notifications.length > 0 && (
        <div className={`notification-toast-stack is-${toastPosition === "left" ? "left" : "right"}`} aria-live="polite" aria-relevant="additions">
          {notifications.map((notification) => (
            <NotificationToast
              key={notification.id}
              id={notification.id}
              message={notification.message}
              onClose={dismissNotification}
            />
          ))}
        </div>
      )}
    </>
  );
}
