import type { ComponentChildren } from "preact";

interface OverlayProps {
  children: ComponentChildren;
  onClose: () => void;
  mode?: "overlay" | "slide-in";
  title?: string;
}

/** Modal overlay or right slide-in panel for detail/form screens. */
export function Overlay({ children, onClose, mode = "overlay", title }: OverlayProps) {
  if (mode === "slide-in") {
    return (
      <div class="fixed inset-0 z-40 flex">
        {/* Backdrop */}
        <div class="flex-1" style={{ background: "rgba(0,0,0,0.3)" }} onClick={onClose} />
        {/* Panel */}
        <div
          class="w-full max-w-lg h-full overflow-y-auto"
          style={{ background: "var(--z-bg)", borderLeft: "1px solid var(--z-border)", animation: "slideIn 0.2s ease" }}
        >
          <div class="sticky top-0 z-10 flex items-center justify-between px-5 py-3" style={{ background: "var(--z-surface)", borderBottom: "1px solid var(--z-border)" }}>
            {title && <span class="text-sm font-semibold">{title}</span>}
            <button onClick={onClose} class="w-7 h-7 rounded-md flex items-center justify-center text-sm" style={{ color: "var(--z-muted)" }}>✕</button>
          </div>
          <div class="p-5">{children}</div>
        </div>
        <style>{`@keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }`}</style>
      </div>
    );
  }

  // Overlay / modal (centered)
  return (
    <div class="fixed inset-0 z-40 flex items-center justify-center p-4" onClick={onClose}>
      <div class="absolute inset-0" style={{ background: "rgba(0,0,0,0.5)", backdropFilter: "blur(4px)" }} />
      <div
        class="relative w-full max-w-2xl max-h-[85vh] overflow-y-auto rounded-[var(--z-radius-card)]"
        style={{ background: "var(--z-bg)", border: "var(--z-card-border)", boxShadow: "var(--z-card-shadow)" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div class="sticky top-0 z-10 flex items-center justify-between px-5 py-3" style={{ background: "var(--z-surface)", borderBottom: "1px solid var(--z-border)", borderRadius: "12px 12px 0 0" }}>
          {title && <span class="text-sm font-semibold">{title}</span>}
          <button onClick={onClose} class="w-7 h-7 rounded-md flex items-center justify-center text-sm" style={{ color: "var(--z-muted)" }}>✕</button>
        </div>
        <div class="p-5">{children}</div>
      </div>
    </div>
  );
}
