o2o-negosium-original/landing/app/components/ui/demo-request-modal.tsx
Haewon Kam 2888ff2c28 [feat] landing: 리드 수집 서버리스 함수 + 상담 신청 폼 실전송 연결
랜딩은 ssr:false 정적 빌드라 서버 라우트가 없다. Vercel /api 디렉터리 함수로 받는다.
클라이언트가 같은 오리진(/api/lead)으로 쏘므로 엔드포인트 환경변수도 CORS 도 없다.

api/lead.ts — 리드를 잃지 않는 것이 유일한 책임
  1) 먼저 구조화 로그를 남긴다. 웹훅이 죽어도 Vercel 로그에 리드가 남는다.
  2) LEAD_WEBHOOK_URL 이 있으면 전달(Slack Incoming Webhook·Zapier·자체 API 모두 POST).
     Slack 용 text 와 원본 필드를 함께 실어 수신처를 바꿔도 이 파일을 안 고친다.
  3) 웹훅 실패해도 200 — 1) 에서 리드를 확보했으니 방문자에게 재입력을 시킬 이유가 없다.
     대신 실패는 로그에 크게 남긴다.
  봇 함정(website) 값이 차 있으면 조용히 200. 400 을 주면 어떤 필드가 함정인지 알려주는 셈이다.

contact.tsx — 가짜 성공 제거
  기존엔 setTimeout 1.2초 뒤 성공 화면만 띄우고 아무 데도 보내지 않았다. 화면은
  "접수되었습니다"인데 영업이 받을 리드는 없었다. 이제 같은 함수로 보내고 서버가
  리드를 확보했을 때만 성공을 띄운다. 실패 시 role="alert" 로 안내.

vercel.json — SPA 리라이트가 /api 를 삼키지 않도록 제외.
  "/(.*)" 그대로 두면 /api/lead 요청이 index.html 로 갔다.

데모 요청 모달 카피
  "이름과 이메일만 남겨주시면, 담당자가 일정을 잡아 연락드립니다"
  → "성함과 이메일만 남겨주시면, 사용해보실 수 있는 Demo를 보내드립니다!"
  성공 화면도 같은 약속으로 맞췄다. 폼은 데모를 보낸다는데 성공 화면이 일정을
  잡는다고 하면 방문자가 무엇을 기다려야 하는지 모른다. 라벨도 성함으로 통일.

⚠️ LEAD_WEBHOOK_URL 미설정 시 리드는 Vercel 로그에만 남는다. 로그는 최후의 그물이지
   CRM 이 아니다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 10:48:06 +09:00

229 lines
9.5 KiB
TypeScript

import { useEffect, useId, useRef, useState } from "react"
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
import { Check, Loader2, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Typography } from "@/components/ui/typography"
import { EASE_OUT_EXPO } from "@/lib/motion"
import { isEmailLike, submitLead } from "@/lib/lead"
/*
* 데모 요청 모달 — 이름·이메일만 받는 리드 캡처.
*
* 상담 신청(contact.tsx)은 회사명·담당자·연락처·문의내용까지 받는 고관여 폼이다.
* 이건 그 앞단이다. 필드가 늘수록 이탈이 늘기 때문에 두 칸에서 멈춘다 — 영업이
* 첫 연락을 하는 데 필요한 최소가 이름과 이메일이고, 나머지는 통화에서 채운다.
*
* 전체 페이지로 보내지 않고 모달로 띄우는 이유도 같다. 히어로에서 관심이 생긴
* 순간에 그 자리에서 받아야 한다. 스크롤로 내려보내면 그 사이에 식는다.
*/
export function DemoRequestModal({ open, onClose }: { open: boolean; onClose: () => void }) {
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [website, setWebsite] = useState("") // 봇 함정
const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle")
const dialogRef = useRef<HTMLDivElement>(null)
const firstFieldRef = useRef<HTMLInputElement>(null)
const restoreFocusTo = useRef<HTMLElement | null>(null)
const reduce = useReducedMotion()
const titleId = useId()
/* 열릴 때마다 초기화. 남겨두면 성공 화면이 다시 뜨거나 이전 에러가 붙어 나온다. */
useEffect(() => {
if (!open) return
setStatus("idle")
restoreFocusTo.current = document.activeElement as HTMLElement | null
const t = setTimeout(() => firstFieldRef.current?.focus(), 60)
return () => clearTimeout(t)
}, [open])
/* 배경 스크롤 잠금. 모달 뒤에서 페이지가 움직이면 모달이 페이지의 일부처럼 읽힌다. */
useEffect(() => {
if (!open) return
const prev = document.body.style.overflow
document.body.style.overflow = "hidden"
return () => {
document.body.style.overflow = prev
restoreFocusTo.current?.focus?.()
}
}, [open])
/* Esc 로 닫기 + Tab 을 모달 안에 가둔다. 가두지 않으면 뒤 페이지의 링크로 포커스가
빠져나가고, 키보드·스크린리더 사용자는 자기가 어디 있는지 알 수 없게 된다. */
useEffect(() => {
if (!open) return
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
onClose()
return
}
if (e.key !== "Tab") return
const focusables = dialogRef.current?.querySelectorAll<HTMLElement>(
'button:not([disabled]), input:not([disabled]), a[href]',
)
if (!focusables?.length) return
const first = focusables[0]
const last = focusables[focusables.length - 1]
if (e.shiftKey && document.activeElement === first) {
e.preventDefault()
last.focus()
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault()
first.focus()
}
}
document.addEventListener("keydown", onKeyDown)
return () => document.removeEventListener("keydown", onKeyDown)
}, [open, onClose])
const valid = name.trim().length > 0 && isEmailLike(email)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!valid || status === "submitting") return
setStatus("submitting")
const result = await submitLead({ source: "demo-request", name, email, website })
setStatus(result.ok ? "success" : "error")
}
return (
<AnimatePresence>
{open && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-6">
<motion.div
className="absolute inset-0 bg-stage-deep/80 backdrop-blur-sm"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={onClose}
/>
<motion.div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
className="relative w-full max-w-md bg-white rounded-card p-8 sm:p-10 shadow-2xl"
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 16, scale: 0.98 }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.99 }}
transition={{ duration: 0.28, ease: EASE_OUT_EXPO }}
>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="absolute top-4 right-4 p-2 text-ink-muted hover:text-ink transition-colors cursor-pointer"
>
<X className="w-5 h-5" />
</button>
{status === "success" ? (
<div className="text-center py-4">
<div className="w-12 h-12 rounded-full bg-positive-soft text-positive flex items-center justify-center mx-auto mb-5">
<Check className="w-6 h-6" />
</div>
<Typography variant="cardTitle" as="h2" id={titleId} className="mb-3">
</Typography>
{/* 폼에서 "Demo를 보내드립니다"라고 약속했으므로 성공 화면도 같은 약속을 지킨다.
여기서 "일정을 잡아 연락드립니다"로 새면 방문자가 무엇을 기다려야 하는지 모른다. */}
<Typography variant="small">
Demo를 .
</Typography>
</div>
) : (
<>
<Typography variant="cardTitle" as="h2" id={titleId} className="mb-2">
</Typography>
<Typography variant="small" className="mb-8">
, Demo를 !
</Typography>
<form onSubmit={handleSubmit} className="space-y-7">
{/* 봇 함정. 화면에서 감추되 display:none 은 쓰지 않는다 — 일부 봇은
숨겨진 필드를 걸러낸다. 스크린리더에는 aria-hidden + tabIndex 로 숨긴다. */}
<div className="absolute w-px h-px -left-[9999px] overflow-hidden" aria-hidden>
<input
type="text"
name="website"
tabIndex={-1}
autoComplete="off"
value={website}
onChange={(e) => setWebsite(e.target.value)}
/>
</div>
<div>
<label htmlFor="lead-name" className="block text-[13px] font-semibold text-ink-soft mb-2">
</label>
<Input
ref={firstFieldRef}
id="lead-name"
name="name"
type="text"
required
autoComplete="name"
placeholder="예: 홍길동"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={status === "submitting"}
/>
</div>
<div>
<label htmlFor="lead-email" className="block text-[13px] font-semibold text-ink-soft mb-2">
</label>
<Input
id="lead-email"
name="email"
type="email"
required
autoComplete="email"
placeholder="예: hong@company.co.kr"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={status === "submitting"}
/>
</div>
{status === "error" && (
<p role="alert" className="text-[13px] text-ink-soft leading-[1.6] break-keep">
.{" "}
<a href="#contact-section" onClick={onClose} className="text-primary font-semibold underline">
</a>
.
</p>
)}
<Button
type="submit"
variant="primary"
size="lg"
className="w-full"
disabled={!valid || status === "submitting"}
>
{status === "submitting" ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
<span> </span>
</>
) : (
<span> </span>
)}
</Button>
</form>
</>
)}
</motion.div>
</div>
)}
</AnimatePresence>
)
}