"use client"; import Link from "next/link"; import { useCallback, useEffect, useRef, useState } from "react"; import { usePathname } from "next/navigation"; import { CircleCheck, ImagePlus, MessageCircleWarning, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/input"; import { useT } from "@/components/I18n"; import { cn } from "@/lib/utils"; const MAX_SHOTS = 5; const MAX_BYTES = 5 * 1024 * 1024; const TYPES = ["image/png", "image/jpeg", "image/webp"]; interface Shot { file: File; url: string; } /** * PEP-143: «Сообщить о проблеме» on every page — text plus up to five screenshots (file picker, * drag and drop, paste from the clipboard). The page address, the window size and the page's * last browser errors go along by themselves. */ export function FeedbackButton() { const t = useT(); const path = usePathname(); const dialog = useRef(null); const picker = useRef(null); const [text, setText] = useState(""); const [shots, setShots] = useState([]); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [sent, setSent] = useState(false); const [over, setOver] = useState(false); const add = useCallback( (files: Iterable) => { setError(null); setShots((cur) => { const next = [...cur]; for (const file of files) { if (!TYPES.includes(file.type)) { setError(t("Файл не похож на картинку. Приложите скриншот в формате PNG, JPEG или WebP.")); continue; } if (file.size > MAX_BYTES) { setError(t("Скриншот больше 5 МБ. Приложите файл поменьше.")); continue; } if (next.length >= MAX_SHOTS) { setError(t("Можно приложить не больше {n} скриншотов.", { n: MAX_SHOTS })); break; } next.push({ file, url: URL.createObjectURL(file) }); } return next; }); }, [t], ); const remove = (i: number) => setShots((cur) => { URL.revokeObjectURL(cur[i]!.url); return cur.filter((_, j) => j !== i); }); const reset = () => { shots.forEach((s) => URL.revokeObjectURL(s.url)); setShots([]); setText(""); setError(null); setSent(false); }; const open = () => { if (sent) reset(); dialog.current?.showModal(); }; // Ctrl+V anywhere in the open form: a picture from the clipboard becomes a screenshot. useEffect(() => { const onPaste = (e: ClipboardEvent) => { if (!dialog.current?.open) return; const files = [...(e.clipboardData?.files ?? [])].filter((f) => f.type.startsWith("image/")); if (!files.length) return; e.preventDefault(); add(files); }; window.addEventListener("paste", onPaste); return () => window.removeEventListener("paste", onPaste); }, [add]); const submit = async () => { if (!text.trim() && !shots.length) return setError(t("Напишите, что случилось, или приложите скриншот.")); setBusy(true); setError(null); try { const form = new FormData(); form.set("text", text); const errors = (window as unknown as { __peppaErrors?: unknown[] }).__peppaErrors ?? []; form.set("context", JSON.stringify({ url: location.pathname + location.search, viewport: `${window.innerWidth}x${window.innerHeight}`, errors })); shots.forEach((s) => form.append("shots", s.file, "screenshot")); const res = await fetch("/api/feedback", { method: "POST", body: form }); const body = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string }; if (!res.ok || !body.ok) return setError(body.error ?? t("Не получилось отправить. Проверьте интернет и попробуйте ещё раз.")); setSent(true); } catch { setError(t("Не получилось отправить. Проверьте интернет и попробуйте ещё раз.")); } finally { setBusy(false); } }; return ( <> e.target === dialog.current && dialog.current.close()} className="m-auto w-[520px] max-w-[calc(100vw-1.5rem)] rounded-xl border bg-card p-0 text-foreground backdrop:bg-black/50" >

{t("Сообщить о проблеме")}

{sent ? (

{/* glossary-ignore: «команда» here is the team of people, not a terminal command */} {t("Спасибо, передали команде")}

{t("Мы разберём обращение и напишем вам, когда всё исправим. Статус виден в списке ваших обращений.")}

) : ( <>

{t("Напишите, что случилось, и приложите скриншот. Обращение увидят те, кто делает Peppa FACTORY, — мы разберёмся и ответим вам.")}