import React, { useCallback } from 'react';
import { useSetAtom } from 'jotai';
import type { Room } from 'matrix-js-sdk';
import type { BotPreset } from './catalog';
import { BotShellHero } from './BotShellHero';
import { BotWidgetMount } from './BotWidgetMount';
import { botFailedAtomFamily, botShowChatAtomFamily } from './botExperienceState';
import * as css from './BotShell.css';

type BotShellProps = {
  preset: BotPreset;
  room: Room;
};

// Bot-page layout. Owns the hero (host-side, mockup BotsDesktop:660-672) and
// the iframe mount. Standard Cinny `RoomViewHeader` is intentionally absent
// here — BotExperienceHost branches above `<Room>`, picking BotShell when the
// user's `botShowChatAtomFamily(roomId)` is false. The chat fallback path
// uses the regular Room layout via BotChatFallback.
//
// Implicit dependency: BotShellMenu reaches into `useRoomUnread`,
// `useRoomsNotificationPreferencesContext`, and friends — all of which
// expect a `<RoomProvider>` somewhere above. BotExperienceHost wraps both
// branches in `<BotRoomProvider>` (which mounts RoomProvider +
// IsOneOnOneProvider), so this is satisfied today. A future refactor that
// mounts BotShell standalone (e.g. a multi-bot dashboard preview) will
// fail at runtime in obscure ways unless that wrap is preserved. Don't
// move BotShell out of the BotRoomProvider context without rewiring the
// menu.
//
// Failure handling: when BotWidgetMount reports an iframe error, we set the
// per-room failure flag AND flip the show-chat atom — this bounces the user
// to the standard Room view (which lives behind the same atom) and the chat
// fallback overlay surfaces a «Retry widget» button. Clearing both atoms
// re-mounts BotShell with a fresh iframe.
export function BotShell({ preset, room }: BotShellProps) {
  const setFailed = useSetAtom(botFailedAtomFamily(room.roomId));
  const setShowChat = useSetAtom(botShowChatAtomFamily(room.roomId));

  const handleError = useCallback(() => {
    setFailed(true);
    setShowChat(true);
  }, [setFailed, setShowChat]);

  return (
    <div className={css.Shell}>
      <BotShellHero preset={preset} room={room} />
      <div className={css.Frame}>
        <BotWidgetMount preset={preset} room={room} onError={handleError} />
      </div>
    </div>
  );
}
