"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

type Props = {
  className?: string;
  label?: string;
};

/** Starts Pro Checkout (€5/mo) or applies a dev mock upgrade. */
export function UpgradeProButton({
  className = "text-accent hover:underline",
  label = "Upgrade to Pro",
}: Props) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleUpgrade() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/account/subscribe", { method: "POST" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Upgrade failed");
      if (data.mocked) {
        router.refresh();
        return;
      }
      if (!data.url) throw new Error("No checkout URL returned");
      window.location.href = data.url;
    } catch (err) {
      setError(err instanceof Error ? err.message : "Upgrade failed");
      setLoading(false);
    }
  }

  return (
    <span className="inline">
      <button
        type="button"
        onClick={handleUpgrade}
        disabled={loading}
        className={className}
      >
        {loading ? "Starting…" : label}
      </button>
      {error && <span className="ml-2 text-sm text-red-400">{error}</span>}
    </span>
  );
}
