"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import "./NewTrailButton.css";
import { createDraft } from "@/data/drafts/actions";
import { useAuthAction } from "@/auth/useAuthAction";

interface NewTrailButtonProps {
  text?: string;
}

export function NewTrailButton({ text = "+ new trail" }: NewTrailButtonProps) {
  const router = useRouter();
  const requireAuth = useAuthAction();
  const [isPending, startTransition] = useTransition();

  const handleClick = () => {
    requireAuth();
    startTransition(async () => {
      const rkey = await createDraft();
      router.push(`/drafts/${rkey}`);
    });
  };

  return (
    <button onClick={handleClick} className="NewTrailButton" disabled={isPending}>
      {isPending ? "creating..." : text}
    </button>
  );
}
