"use client"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import { useLive } from "@/lib/live"; import { Button } from "@/components/ui/button"; import { pairingLinkAction } from "@/app/(app)/actions"; import { useT } from "@/components/I18n"; /** * PEP-100: opens the user's bot (with the pairing code) in a new tab / the Telegram app and keeps * Peppa open — a plain redirect used to take the page away mid-steps. While the user presses * Start, the live channel tells the page, and it re-renders so the step turns done. */ export function OpenBotButton({ label, variant = "default", size = "sm" }: { label: string; variant?: "default" | "ghost" | "outline"; size?: "sm" | "xs" }) { const t = useT(); const router = useRouter(); const [waiting, setWaiting] = useState(false); const [error, setError] = useState(null); const [link, setLink] = useState(null); useEffect(() => { if (!waiting) return; const stop = setTimeout(() => setWaiting(false), 3 * 60_000); return () => clearTimeout(stop); }, [waiting]); // PEP-225: the binding (`me`) changes when the user presses Start in the bot — re-render then. useLive(waiting ? "me" : null, (e) => { if (e.type === "change") router.refresh(); }); async function open() { setError(null); // Opened synchronously in the click, so the browser doesn't block it as a popup. const tab = window.open("about:blank", "_blank"); const r = await pairingLinkAction(); if (!r.url) { tab?.close(); setError(r.error ? t.text(r.error) : t("Не получилось открыть бота")); return; } // Popups blocked: never take Peppa away — show a link that opens in a new tab instead. if (tab) tab.location.href = r.url; else setLink(r.url); setWaiting(true); } return ( {link && ( {t("Браузер не открыл новую вкладку — нажмите здесь, чтобы открыть бота")} )} {waiting && {t("Нажмите Start в Telegram и вернитесь сюда — шаг отметится сам.")}} {error && {error}} ); }