"use client";

import { X } from "lucide-react";

export function Modal({
  title,
  subtitle,
  onClose,
  children,
  footer,
  wide,
}: {
  title: string;
  subtitle?: string;
  onClose: () => void;
  children: React.ReactNode;
  footer?: React.ReactNode;
  wide?: boolean;
}) {
  return (
    <div
      className="fixed inset-0 z-[60] grid place-items-center bg-black/50 p-4 backdrop-blur-sm animate-fade-in"
      onClick={onClose}
    >
      <div
        role="dialog"
        aria-modal="true"
        aria-label={title}
        onClick={(e) => e.stopPropagation()}
        className={`flex max-h-[90dvh] w-full ${wide ? "max-w-xl" : "max-w-md"} flex-col overflow-hidden rounded-card border border-border bg-elevated shadow-pop animate-slide-up`}
      >
        <div className="flex shrink-0 items-start justify-between gap-3 border-b border-border px-5 py-4">
          <div className="min-w-0">
            <h2 className="truncate text-[16px] font-bold">{title}</h2>
            {subtitle && <p className="mt-0.5 truncate text-[12.5px] text-muted">{subtitle}</p>}
          </div>
          <button onClick={onClose} className="focus-ring -mr-1 grid h-8 w-8 shrink-0 place-items-center rounded-control text-muted hover:bg-hover hover:text-ink" aria-label="Close">
            <X size={18} />
          </button>
        </div>
        <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">{children}</div>
        {footer && <div className="flex shrink-0 justify-end gap-2 border-t border-border px-5 py-3">{footer}</div>}
      </div>
    </div>
  );
}

export function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="mb-3 block">
      <span className="mb-1 block text-[12px] font-semibold text-muted">{label}</span>
      {children}
    </label>
  );
}

export const inputCls =
  "w-full rounded-control border border-border bg-panel px-3 py-2 text-[14px] outline-none focus:border-border-strong placeholder:text-dim";

export function PrimaryBtn({ children, onClick, disabled, type = "button" }: { children: React.ReactNode; onClick?: () => void; disabled?: boolean; type?: "button" | "submit" }) {
  return (
    <button type={type} onClick={onClick} disabled={disabled} className="focus-ring rounded-control bg-accent px-4 py-2 text-[13px] font-semibold text-accent-fg disabled:opacity-40">
      {children}
    </button>
  );
}

export function GhostBtn({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) {
  return (
    <button onClick={onClick} className="focus-ring rounded-control border border-border px-4 py-2 text-[13px] font-semibold hover:bg-hover">
      {children}
    </button>
  );
}
