import React, { ReactNode } from "react";
import { createPortal } from "react-dom";

interface OffcanvasProps {
  isOpen: boolean;
  onClose: () => void;
  width?: number; // px only for drawer-style control
  header?: ReactNode;
  footer?: ReactNode;
  children: ReactNode;
}

const Offcanvas: React.FC<OffcanvasProps> = ({
  isOpen,
  onClose,
  width = 420,
  header,
  footer,
  children,
}) => {
  return createPortal(
    <>
      {/* BACKDROP */}
      <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          background: "#3b2f2859",
          opacity: isOpen ? 1 : 0,
          visibility: isOpen ? "visible" : "hidden",
          transition: "opacity .25s ease",
          zIndex: 9998,
          pointerEvents: isOpen ? "auto" : "none",
        }}
      />

      {/* DRAWER */}
      <div
        style={{
          position: "fixed",
          top: 16,
          right: 16,
          height: "calc(100% - 32px)",
          width,
          background: "#fff",
          borderRadius: 16,
          boxShadow: "0 20px 60px -10px rgba(122,46,29,0.25)",
          zIndex: 9999,
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
          transform: isOpen ? "translateX(0)" : `translateX(${width + 40}px)`,
          transition: "transform 0.3s ease",
          pointerEvents: isOpen ? "auto" : "none",
        }}
      >
        {/* HEADER */}
        {header && (
          <div
            style={{
              padding: "18px 20px",
              flexShrink: 0,
              background: "#fff",
            }}
          >
            {header}
          </div>
        )}
        <div
          style={{
            flex: 1,
            overflowY: "auto",
            padding: 15,
          }}
        >
          {children}
        </div>

        {/* FOOTER */}
        {footer && (
          <div
            style={{
              padding: 16,
              borderTop: "1px solid #eee",
              flexShrink: 0,
              background: "#fff",
            }}
          >
            {footer}
          </div>
        )}
      </div>
    </>,
    document.body
  );
};

export default Offcanvas;