'use client';

import { ReactNode, useState, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Expand, X } from 'lucide-react';

/**
 * ExpandableBlock — wraps a UI block and surfaces a small "expand" icon in its
 * top-right corner. Clicking it opens a lightbox that renders either the same
 * content (replica) or a richer `lightboxContent` passed by the parent.
 *
 * The wrapper keeps the inline block untouched (it just positions an absolute
 * button over it). The expanded view uses a React portal so it sits above
 * everything else, including the map, HUDs and sidebars.
 *
 * Keyboard: Esc closes the lightbox. Click on the backdrop also closes it.
 */

interface ExpandableBlockProps {
  label: string;                  // ARIA + lightbox title
  children: ReactNode;            // inline block content
  lightboxContent?: ReactNode;    // optional richer content for the lightbox
  buttonOffset?: { top?: number; right?: number };
  className?: string;
  contentClassName?: string;      // class applied to the wrapper div
  /** Controlled mode (20-04-2026) — allow external code to open/close
   *  the lightbox via a state prop. Both must be provided together. */
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
}

export function ExpandableBlock({
  label,
  children,
  lightboxContent,
  buttonOffset,
  className,
  contentClassName,
  open: openProp,
  onOpenChange,
}: ExpandableBlockProps) {
  const [openState, setOpenState] = useState(false);
  const controlled = openProp !== undefined;
  const open = controlled ? !!openProp : openState;
  const setOpen = useCallback((v: boolean) => {
    if (!controlled) setOpenState(v);
    onOpenChange?.(v);
  }, [controlled, onOpenChange]);
  const [mounted, setMounted] = useState(false);

  useEffect(() => setMounted(true), []);

  const close = useCallback(() => setOpen(false), [setOpen]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') close();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, close]);

  // Lock body scroll while open
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  return (
    <div className={`relative ${className ?? ''}`}>
      <div className={contentClassName}>{children}</div>

      <button
        type="button"
        onClick={() => setOpen(true)}
        aria-label={`Agrandir : ${label}`}
        title={`Agrandir : ${label}`}
        className="expand-block-btn"
        style={{
          position: 'absolute',
          top: buttonOffset?.top ?? 6,
          right: buttonOffset?.right ?? 6,
        }}
      >
        <Expand size={12} aria-hidden strokeWidth={2.25} />
      </button>

      {open && mounted
        ? createPortal(
            <div
              className="expand-lightbox-backdrop"
              onClick={close}
              role="dialog"
              aria-modal="true"
              aria-label={label}
            >
              <div
                className="expand-lightbox-panel"
                onClick={(e) => e.stopPropagation()}
              >
                <div className="expand-lightbox-header">
                  <span className="expand-lightbox-title">{label}</span>
                  <button
                    type="button"
                    onClick={close}
                    aria-label="Fermer"
                    className="expand-lightbox-close"
                  >
                    <X size={18} aria-hidden strokeWidth={2.25} />
                  </button>
                </div>
                <div className="expand-lightbox-body">
                  {lightboxContent ?? children}
                </div>
              </div>
            </div>,
            document.body,
          )
        : null}
    </div>
  );
}
