"use client";

import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { api } from "@/lib/api";

export function DemoLoginEntry({ google = false }: { google?: boolean }) {
  const router = useRouter();
  const startedRef = useRef(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (startedRef.current) return;
    startedRef.current = true;
    api.demoLogin(google)
      .then(() => {
        router.replace("/");
        router.refresh();
      })
      .catch(() => {
        setError("Demo access is not available right now.");
      });
  }, [google, router]);

  return (
    <main className="grid min-h-screen place-items-center bg-slate-50 p-6 text-slate-900">
      <section className="w-full max-w-sm rounded-xl border border-slate-200 bg-white p-5 text-center shadow-sm">
        <h1 className="text-lg font-black">Opening demo mailbox</h1>
        <p className="mt-2 text-sm font-semibold leading-6 text-slate-500">
          {error || "Preparing the demo session and redirecting to webmail."}
        </p>
        {error ? (
          <button type="button" onClick={() => router.replace("/login")} className="theme-button mt-4 h-10 px-4 text-sm">
            Go to login
          </button>
        ) : null}
      </section>
    </main>
  );
}
