'use client';

import {MobileNav} from '@astryxdesign/core/MobileNav';
import {useLoyalyAi} from '@/features/loyaly-ai/providers/LoyalyAiProvider';
import {useBreakpoint} from '@/shared/hooks/useBreakpoint';
import {LoyalyAiPanel} from './LoyalyAiPanel';

/**
 * Tablet and mobile presentation.
 *
 * MobileNav rather than Dialog: a Dialog is content-sized (height:
 * fit-content, maxHeight 480px) and ignores top/bottom insets, so it renders
 * as a floating card rather than a full-height surface. MobileNav is the
 * edge-anchored primitive this actually needs, and its native <dialog>
 * brings the focus trap, Escape and backdrop with it.
 *
 * It renders the SAME <LoyalyAiPanel /> as the inline path — crossing the
 * breakpoint changes where the assistant lives, never what it contains or
 * remembers, because all state sits in LoyalyAiProvider above the route tree.
 */
const SHEET = [
  // The composer must clear the home indicator on a notched phone. env() is
  // not expressible as a token and pb-safe is not in core Tailwind, so the
  // inset is an arbitrary property on the one surface that docks to the
  // bottom edge.
  '[&>div]:pb-[env(safe-area-inset-bottom)]',
  /*
   * Hide MobileNav's own header row.
   *
   * MobileNav always renders a close button after its `header` slot. With
   * ChatHeader inside, the sheet showed TWO X buttons stacked — one in
   * MobileNav's empty header row, one in ours — and two rows of chrome above
   * the conversation. ChatHeader is the assistant's header at every width, so
   * the drawer's own row is removed rather than duplicated.
   */
  '[&>div>*:first-child]:hidden',
].join(' ');

/**
 * Full-bleed on a phone.
 *
 * MobileNav's `width` is a MAX-width and it defaults to 320px, so passing
 * `undefined` on mobile — as this did before — left a 320px sheet with 70px of
 * dashboard showing beside it. A conversation is the whole task on a phone;
 * `max-w-none` lets the drawer's own `width: 100vw` fill the screen.
 */
const FULL_BLEED = '[&>div]:max-w-none';

export function LoyalyAiSlideOver() {
  const bp = useBreakpoint();
  const {isSlideOverOpen, setSlideOverOpen} = useLoyalyAi();

  return (
    <MobileNav
      // Explicit, because MobileNav otherwise takes its id from AppShell's
      // mobile context — which every MobileNav in the tree shares, so this and
      // the navigation drawer would both render the same id, and the menu
      // button's aria-controls would resolve to whichever the DOM reached
      // first.
      id="loyaly-ai-slide-over"
      isOpen={isSlideOverOpen}
      onOpenChange={setSlideOverOpen}
      side="end"
      width={420}
      label="Loyaly AI"
      className={bp === 'mobile' ? `${SHEET} ${FULL_BLEED}` : SHEET}
    >
      <LoyalyAiPanel onClose={() => setSlideOverOpen(false)} />
    </MobileNav>
  );
}
