import { useParams, useNavigate } from "react-router-dom";
import { pluginRegistry } from "../core/plugins/plugin-registry";
import { ToolShell } from "../components/tool/ToolShell";
import { useTheme } from "../app/useTheme";

export function ToolDetailPage() {
  const { toolId } = useParams<{ toolId: string }>();
  const navigate = useNavigate();
  const { dark } = useTheme();

  const plugin = pluginRegistry.find((p) => p.manifest.id === toolId);

  if (!plugin) {
    return (
      <div className="p-8">
        <h2 className="text-xl font-semibold mb-4 text-[var(--p-text)]">Tool not found</h2>
        <button onClick={() => navigate("/tools")} className="text-blue-500 hover:underline">
          Return to directory
        </button>
      </div>
    );
  }

  const handleClose = () => {
    navigate("/tools");
  };

  return (
    <div
      onClick={handleClose}
      role="presentation"
      className="fixed inset-0 z-50 flex items-end justify-center p-0 md:items-center md:p-10 animate-plimi-fade"
      style={{
        background: 'color-mix(in oklab, var(--p-bg) 70%, transparent)',
        backdropFilter: 'blur(8px)',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-label={plugin.manifest.name}
        className="w-full md:w-[min(900px,100%)] h-[92dvh] md:h-auto md:max-h-[calc(100dvh-5rem)] bg-[var(--p-surface)] rounded-t-[20px] md:rounded-[24px] border-[1.5px] border-[var(--p-border)] flex flex-col animate-plimi-slide overflow-hidden"
        style={{
          boxShadow: '0 40px 80px -30px var(--p-shadow-soft)',
        }}
      >
        {/* Grab handle — signals the sheet is dismissable on touch */}
        <div className="md:hidden flex justify-center pt-2.5 pb-1 shrink-0">
          <span className="h-1 w-9 rounded-full bg-[var(--p-border)]" />
        </div>
        <ToolShell plugin={plugin} onClose={handleClose} dark={dark} />
      </div>
    </div>
  );
}
