first commit

This commit is contained in:
dahyeon committed 2026-08-12 17:28:30 +09:00
1 parent 18d31d5dcf
commit 77a5f5248c
31 files changed
+6637 -30

No files matched your search

+337
View File
@@ -0,0 +1,337 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import type {
AutoReservationState,
ClockCalibrationSettings,
ClockEstimate,
ReservationRequest,
ReservationResult,
TimingTestResult,
} from '../type/reservation'
import { CLOCK_CALIBRATION_DEFAULTS } from '../type/reservation'
const KST_OFFSET_MS = 9 * 60 * 60 * 1_000
const CLOCK_SETTINGS_STORAGE_KEY = 'escape-reserve.clock-calibration.v1'
const LEGACY_CLOCK_SETTINGS_STORAGE_KEY = 'reserve-escape.clock-calibration.v1'
function loadClockSettings(): ClockCalibrationSettings {
try {
const saved = window.localStorage.getItem(CLOCK_SETTINGS_STORAGE_KEY)
?? window.localStorage.getItem(LEGACY_CLOCK_SETTINGS_STORAGE_KEY)
return saved ? { ...CLOCK_CALIBRATION_DEFAULTS, ...JSON.parse(saved) } : { ...CLOCK_CALIBRATION_DEFAULTS }
} catch {
return { ...CLOCK_CALIBRATION_DEFAULTS }
}
}
interface AutomationPanelProps {
request: ReservationRequest | null
captchaToken: string
captchaPastedAtMs: number | null
onTokenConsumed: () => void
onResult: (result: ReservationResult) => void
}
function toKstInput(epochMs: number) {
const value = new Date(epochMs + KST_OFFSET_MS)
return `${value.getUTCFullYear()}-${String(value.getUTCMonth() + 1).padStart(2, '0')}-${String(value.getUTCDate()).padStart(2, '0')}T${String(value.getUTCHours()).padStart(2, '0')}:${String(value.getUTCMinutes()).padStart(2, '0')}:${String(value.getUTCSeconds()).padStart(2, '0')}.${String(value.getUTCMilliseconds()).padStart(3, '0')}`
}
function parseKstInput(value: string) {
const match = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/)
if (!match) return Number.NaN
return Date.UTC(
Number(match[1]), Number(match[2]) - 1, Number(match[3]),
Number(match[4]) - 9, Number(match[5]), Number(match[6] ?? 0),
Number((match[7] ?? '0').padEnd(3, '0')),
)
}
function formatClock(epochMs: number) {
return new Intl.DateTimeFormat('ko-KR', {
timeZone: 'Asia/Seoul',
hour12: false,
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
fractionalSecondDigits: 3,
}).format(epochMs)
}
function formatDuration(milliseconds: number) {
const sign = milliseconds < 0 ? '-' : ''
const absolute = Math.abs(milliseconds)
if (absolute < 1_000) return `${sign}${absolute.toFixed(0)}ms`
const seconds = absolute / 1_000
if (seconds < 60) return `${sign}${seconds.toFixed(3)}초`
return `${sign}${Math.floor(seconds / 60)}분 ${(seconds % 60).toFixed(1)}초`
}
function Metric({ label, value, tone = 'normal' }: { label: string; value: string; tone?: 'normal' | 'good' | 'warn' }) {
return (
<div className="rounded-xl border border-white/8 bg-black/20 px-3 py-2.5">
<p className="text-[9px] uppercase tracking-[0.18em] text-zinc-600">{label}</p>
<p className={`mt-1 font-mono text-xs ${tone === 'good' ? 'text-emerald-300' : tone === 'warn' ? 'text-amber-300' : 'text-zinc-300'}`}>{value}</p>
</div>
)
}
function SampleGraph({ estimate }: { estimate: ClockEstimate }) {
const accepted = estimate.samples.filter((sample) => sample.accepted).slice(-60)
if (accepted.length < 2) return <div className="flex h-28 items-center justify-center text-[10px] text-zinc-700">표본을 수집하는 중입니다.</div>
const width = 600
const height = 112
const maxRtt = Math.max(1, ...accepted.map((sample) => sample.rttMs))
const maxOffsetDelta = Math.max(50, ...accepted.map((sample) => Math.abs(sample.offsetEstimateMs - estimate.offsetMs)))
const points = accepted.map((sample, index) => {
const x = accepted.length === 1 ? 0 : index * width / (accepted.length - 1)
const y = height / 2 - ((sample.offsetEstimateMs - estimate.offsetMs) / maxOffsetDelta) * (height * 0.38)
return `${x.toFixed(1)},${y.toFixed(1)}`
}).join(' ')
return (
<div className="overflow-hidden rounded-xl border border-white/8 bg-black/30 p-2">
<svg viewBox={`0 0 ${width} ${height}`} className="h-28 w-full" role="img" aria-label="최근 서버시간 표본 그래프">
<line x1="0" x2={width} y1={height / 2} y2={height / 2} stroke="rgba(255,255,255,.08)" />
{accepted.map((sample, index) => {
const barWidth = Math.max(2, width / accepted.length - 2)
const barHeight = sample.rttMs / maxRtt * height * 0.35
return <rect key={sample.id} x={index * width / accepted.length} y={height - barHeight} width={barWidth} height={barHeight} fill="rgba(52,211,153,.16)" />
})}
<polyline points={points} fill="none" stroke="rgb(252 211 77)" strokeWidth="2" vectorEffect="non-scaling-stroke" />
</svg>
<div className="flex justify-between px-1 text-[9px] text-zinc-700"><span>노란선: 오프셋 편차</span><span>초록막대: RTT</span></div>
</div>
)
}
export default function AutomationPanel({
request,
captchaToken,
captchaPastedAtMs,
onTokenConsumed,
onResult,
}: AutomationPanelProps) {
const [clock, setClock] = useState<ClockEstimate | null>(null)
const [autoState, setAutoState] = useState<AutoReservationState>({ status: 'idle', tokenStatus: 'empty' })
const [nowMs, setNowMs] = useState(Date.now())
const [targetInput, setTargetInput] = useState(() => toKstInput(Date.now() + 30_000))
const [userOffsetMs, setUserOffsetMs] = useState(0)
const [busy, setBusy] = useState<'monitor' | 'test' | 'arm' | null>(null)
const [error, setError] = useState('')
const [timingTest, setTimingTest] = useState<TimingTestResult | null>(null)
const [settingsOpen, setSettingsOpen] = useState(false)
const [clockSettings, setClockSettings] = useState<ClockCalibrationSettings>(loadClockSettings)
const previousFingerprint = useRef('')
const previousAutoStatus = useRef(autoState.status)
const targetServerTimeMs = parseKstInput(targetInput)
const liveServerTimeMs = clock
? clock.estimatedServerTimeMs + (nowMs - clock.observedAtMs)
: nowMs
const countdownMs = Number.isFinite(targetServerTimeMs) ? targetServerTimeMs - liveServerTimeMs : 0
const tokenAgeMs = captchaPastedAtMs ? nowMs - captchaPastedAtMs : Number.POSITIVE_INFINITY
const tokenAgeAtTargetMs = captchaPastedAtMs && Number.isFinite(targetServerTimeMs)
? targetServerTimeMs - (captchaPastedAtMs + (clock?.offsetMs ?? 0))
: Number.POSITIVE_INFINITY
const tokenReady = captchaToken.trim().length >= 30 && tokenAgeAtTargetMs >= 0 && tokenAgeAtTargetMs <= 90_000
const requestFingerprint = useMemo(() => request ? JSON.stringify({
...request,
captchaToken: request.captchaToken ? `${request.captchaToken.length}:${request.captchaToken.slice(-8)}` : '',
}) : '', [request])
useEffect(() => {
const unsubscribeClock = window.reservationApi.subscribeClock(setClock)
const unsubscribeAuto = window.reservationApi.subscribeAutoState(setAutoState)
void Promise.all([
window.reservationApi.configureClock(clockSettings).then((estimate) => {
setClock(estimate)
setClockSettings(estimate.calibrationSettings)
}),
window.reservationApi.getAutoReservationState().then(setAutoState),
]).catch(() => undefined)
const interval = window.setInterval(() => setNowMs(Date.now()), 50)
return () => {
unsubscribeClock()
unsubscribeAuto()
window.clearInterval(interval)
}
}, [])
useEffect(() => {
if (previousFingerprint.current && previousFingerprint.current !== requestFingerprint && autoState.status === 'armed') {
void window.reservationApi.disarmAutoReservation().then(setAutoState)
}
previousFingerprint.current = requestFingerprint
}, [requestFingerprint, autoState.status])
useEffect(() => {
if (previousAutoStatus.current !== autoState.status) {
if (autoState.status === 'firing') onTokenConsumed()
if ((autoState.status === 'succeeded' || autoState.status === 'failed') && autoState.result) onResult(autoState.result)
previousAutoStatus.current = autoState.status
}
}, [autoState, onResult, onTokenConsumed])
const toggleMonitor = async () => {
setBusy('monitor')
setError('')
try {
setClock(clock?.monitoring
? await window.reservationApi.stopClockMonitor()
: await window.reservationApi.startClockMonitor())
} catch (reason) {
setError(reason instanceof Error ? reason.message : '서버시간 모니터를 전환하지 못했습니다.')
} finally {
setBusy(null)
}
}
const runTimingTest = async () => {
setBusy('test')
setError('')
setTimingTest(null)
try {
const current = clock
? clock.estimatedServerTimeMs + (Date.now() - clock.observedAtMs)
: Date.now()
setTimingTest(await window.reservationApi.runTimingTest({
targetServerTimeMs: current + 3_000,
userOffsetMs,
}))
} catch (reason) {
setError(reason instanceof Error ? reason.message : '시간 테스트에 실패했습니다.')
} finally {
setBusy(null)
}
}
const saveClockSettings = async () => {
setBusy('monitor')
setError('')
try {
const estimate = await window.reservationApi.configureClock(clockSettings)
setClock(estimate)
setClockSettings(estimate.calibrationSettings)
window.localStorage.setItem(CLOCK_SETTINGS_STORAGE_KEY, JSON.stringify(estimate.calibrationSettings))
setSettingsOpen(false)
} catch (reason) {
setError(reason instanceof Error ? reason.message : '시간 보정 설정을 저장하지 못했습니다.')
} finally {
setBusy(null)
}
}
const arm = async () => {
setError('')
if (!request) return setError('예약 정보, 인원, 예약자 정보와 동의를 모두 완료해주세요.')
if (!captchaPastedAtMs || !tokenReady) return setError('목표 시각에 90초 이내인 유효한 캡차 토큰이 필요합니다.')
if (!Number.isFinite(targetServerTimeMs)) return setError('실행 시각을 올바르게 입력해주세요.')
setBusy('arm')
try {
if (!clock?.monitoring) setClock(await window.reservationApi.startClockMonitor())
setAutoState(await window.reservationApi.armAutoReservation({
request,
targetServerTimeMs,
userOffsetMs,
captchaPastedAtMs,
}))
} catch (reason) {
setError(reason instanceof Error ? reason.message : '자동 예약을 무장하지 못했습니다.')
} finally {
setBusy(null)
}
}
const disarm = async () => {
setError('')
try {
setAutoState(await window.reservationApi.disarmAutoReservation())
onTokenConsumed()
} catch (reason) {
setError(reason instanceof Error ? reason.message : '자동 예약을 해제하지 못했습니다.')
}
}
const qualityTone = clock?.quality === 'good' ? 'good' : clock?.quality === 'poor' || clock?.quality === 'unavailable' ? 'warn' : 'normal'
const armed = autoState.status === 'armed' || autoState.status === 'firing'
return (
<section className="panel-card overflow-hidden" aria-label="자동 예약 및 서버시간">
<div className="border-b border-white/8 p-5 sm:p-6">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<p className="text-[10px] font-semibold uppercase tracking-[0.26em] text-amber-300/70">Precision clock</p>
<h2 className="mt-1 text-base font-semibold text-white">관측 서버시간</h2>
<p className="mt-1 text-[10px] leading-4 text-zinc-600">HTTP Date는 초 단위이며 아래 값은 RTT 보정 추정치와 신뢰구간입니다.</p>
</div>
<button onClick={toggleMonitor} disabled={busy === 'monitor' || armed} className={`rounded-full border px-3 py-2 text-[11px] font-semibold transition ${clock?.monitoring ? 'border-emerald-300/25 bg-emerald-300/10 text-emerald-200' : 'border-white/10 text-zinc-400 hover:text-white'} disabled:opacity-40`}>
{busy === 'monitor' ? '측정 중…' : clock?.monitoring ? '모니터 중지' : '모니터 시작'}
</button>
</div>
<p className="mt-5 font-mono text-xl tracking-tight text-white sm:text-2xl" aria-label="관측 서버시간 값">{formatClock(liveServerTimeMs)}</p>
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
<Metric label="offset" value={`${(clock?.offsetMs ?? 0).toFixed(1)}ms`} tone={qualityTone} />
<Metric label="raw offset" value={`${(clock?.rawOffsetMs ?? 0).toFixed(1)}ms`} />
<Metric label="boundary offset" value={clock?.boundaryOffsetMs === undefined ? '—' : `${clock.boundaryOffsetMs.toFixed(1)} ±${(clock.boundaryUncertaintyMs ?? 0).toFixed(1)}ms`} tone={clock?.calibrationReady ? 'good' : 'warn'} />
<Metric label="RTT min / p50" value={`${(clock?.minRttMs ?? 0).toFixed(1)} / ${(clock?.p50RttMs ?? 0).toFixed(1)}ms`} />
<Metric label="RTT p95" value={`${(clock?.p95RttMs ?? 0).toFixed(1)}ms`} />
<Metric label="uncertainty" value={`±${(clock?.uncertaintyMs ?? 0).toFixed(1)}ms`} tone={qualityTone} />
<Metric label="one way" value={`${(clock?.oneWayMs ?? 0).toFixed(1)}ms`} />
<Metric label="sample age" value={clock?.acceptedSamples ? formatDuration(clock.sampleAgeMs + (nowMs - clock.observedAtMs)) : '—'} />
<Metric label="drift" value={`${(clock?.driftPpm ?? 0).toFixed(2)}ppm`} />
<Metric label="remote" value={clock?.remoteIp || '—'} />
<Metric label="boundaries" value={`${clock?.boundaryCount ?? 0} / ${clock?.calibrationSettings.requiredBoundaryCount ?? CLOCK_CALIBRATION_DEFAULTS.requiredBoundaryCount}`} tone={clock?.calibrationReady ? 'good' : 'warn'} />
<Metric label="phase spread" value={clock?.boundarySpreadMs === undefined ? '—' : `${clock.boundarySpreadMs.toFixed(1)}ms`} tone={clock?.calibrationReady ? 'good' : 'warn'} />
<Metric label="recommended" value={`${(clock?.recommendedCorrectionMs ?? 0) >= 0 ? '+' : ''}${(clock?.recommendedCorrectionMs ?? 0).toFixed(1)}ms`} />
<Metric label="calibration" value={clock?.calibrationApplied ? 'applied' : clock?.calibrationReady ? 'ready' : 'learning'} tone={clock?.calibrationApplied ? 'good' : 'warn'} />
</div>
<div className="mt-3"><SampleGraph estimate={clock ?? {
monitoring: false, observedAtMs: nowMs, estimatedServerTimeMs: nowMs, offsetMs: 0, driftPpm: 0,
minRttMs: 0, p50RttMs: 0, p95RttMs: 0, oneWayMs: 0, uncertaintyMs: 0,
sampleAgeMs: 0, acceptedSamples: 0, rawOffsetMs: 0, boundaryCount: 0,
recommendedCorrectionMs: 0, calibrationReady: false, calibrationApplied: false,
calibrationSettings: CLOCK_CALIBRATION_DEFAULTS, remoteIp: '', quality: 'unavailable', samples: [],
}} /></div>
{clock?.warning && <p className="mt-2 text-[10px] leading-4 text-amber-300/70">{clock.warning} 품질이 낮아도 마지막 유효 추정값으로 1회 실행합니다.</p>}
<div className="mt-3 flex justify-end"><button onClick={() => setSettingsOpen((value) => !value)} disabled={armed} className="rounded-full border border-white/10 px-3 py-2 text-[10px] font-semibold text-zinc-400 hover:text-white disabled:opacity-40">정밀 보정 설정</button></div>
{settingsOpen && <div className="mt-3 rounded-xl border border-white/10 bg-black/25 p-4">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{([
['scanWindowMs', '경계 탐색 범위 (ms)', 100, 450],
['probeIntervalMs', '경계 측정 간격 (ms)', 25, 200],
['initialBoundarySpacingSec', '초기 경계 간격 (초)', 1, 10],
['requiredBoundaryCount', '최소 경계 수', 3, 12],
['historySize', '경계 기록 수', 3, 30],
['maxBoundarySpreadMs', '최대 경계 편차 (ms)', 30, 500],
['maxProbeRttMs', '최대 허용 RTT (ms)', 100, 1500],
['maintenanceIntervalSec', '안정화 후 재검증 (초)', 5, 120],
['sampleWindowSize', '표본 보관 수', 60, 600],
] as const).map(([key, label, min, max]) => <label key={key} className="space-y-1"><span className="text-[9px] font-semibold text-zinc-500">{label}</span><input type="number" min={min} max={max} value={clockSettings[key]} onChange={(event) => setClockSettings((current) => ({ ...current, [key]: Number(event.target.value) }))} className="w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 font-mono text-xs text-white outline-none focus:border-amber-300/50" /></label>)}
</div>
<div className="mt-3 flex flex-wrap items-center justify-between gap-3 text-[10px] text-zinc-500"><div className="flex gap-4"><label className="flex items-center gap-2"><input type="checkbox" checked={clockSettings.enabled} onChange={(event) => setClockSettings((current) => ({ ...current, enabled: event.target.checked }))} />초 경계 정밀 측정</label><label className="flex items-center gap-2"><input type="checkbox" checked={clockSettings.autoApply} onChange={(event) => setClockSettings((current) => ({ ...current, autoApply: event.target.checked }))} />검증 후 자동 적용</label></div><div className="flex gap-2"><button onClick={() => setClockSettings({ ...CLOCK_CALIBRATION_DEFAULTS })} className="rounded-lg border border-white/10 px-3 py-2">기본값</button><button onClick={saveClockSettings} disabled={busy !== null} className="rounded-lg bg-amber-300 px-3 py-2 font-bold text-black disabled:opacity-40">설정 적용</button></div></div>
<p className="mt-3 text-[9px] leading-4 text-zinc-600">최소 경계 수와 편차 조건을 모두 통과한 경우에만 추천 보정을 자동 적용합니다. 설정은 앱 메모리에만 유지됩니다.</p>
</div>}
</div>
<div className="border-b border-white/8 p-5 sm:p-6">
<div className="flex items-center justify-between gap-3">
<div><h3 className="text-sm font-semibold text-white">시간 테스트</h3><p className="mt-1 text-[10px] text-zinc-600">3초 뒤 HEAD 요청으로 스케줄러와 도착 오차를 측정합니다.</p></div>
<button onClick={runTimingTest} disabled={busy === 'test' || armed} className="rounded-full border border-white/10 px-3 py-2 text-[11px] font-semibold text-zinc-300 hover:border-white/25 hover:text-white disabled:opacity-40">{busy === 'test' ? '테스트 중…' : '3초 테스트'}</button>
</div>
{timingTest && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4"><Metric label="arrival error" value={`${timingTest.arrivalErrorMs >= 0 ? '+' : ''}${timingTest.arrivalErrorMs.toFixed(1)}ms`} tone={Math.abs(timingTest.arrivalErrorMs) <= timingTest.uncertaintyMs ? 'good' : 'warn'} /><Metric label="timer jitter" value={`${timingTest.schedulerJitterMs >= 0 ? '+' : ''}${timingTest.schedulerJitterMs.toFixed(1)}ms`} /><Metric label="RTT" value={`${timingTest.rttMs.toFixed(1)}ms`} /><Metric label="socket" value={timingTest.reusedSocket ? 'reused' : 'new'} /></div>}
</div>
<div className="p-5 sm:p-6">
<div className="flex items-start justify-between gap-4"><div><h3 className="text-sm font-semibold text-white">단일 요청 자동 예약</h3><p className="mt-1 text-[10px] leading-4 text-zinc-600">목표 서버 도착 시각에 토큰 1개를 소비해 정확히 한 번 제출합니다.</p></div><span className={`rounded-full px-2.5 py-1 text-[9px] font-semibold uppercase tracking-wider ${armed ? 'bg-amber-300/15 text-amber-200' : autoState.status === 'succeeded' ? 'bg-emerald-300/15 text-emerald-200' : autoState.status === 'failed' ? 'bg-red-300/15 text-red-200' : 'bg-white/5 text-zinc-500'}`}>{autoState.status}</span></div>
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_140px]">
<label className="space-y-2"><span className="text-[10px] font-semibold text-zinc-500">실행 시각 (KST, ms)</span><input type="datetime-local" step="0.001" value={targetInput} onChange={(event) => setTargetInput(event.target.value)} disabled={armed} className="w-full rounded-xl border border-white/10 bg-black/25 px-3 py-3 font-mono text-xs text-white outline-none focus:border-amber-300/50 disabled:opacity-50" /></label>
<label className="space-y-2"><span className="text-[10px] font-semibold text-zinc-500">도착 오프셋 (ms)</span><input type="number" min="-5000" max="5000" step="1" value={userOffsetMs} onChange={(event) => setUserOffsetMs(Math.max(-5_000, Math.min(5_000, Number(event.target.value))))} disabled={armed} className="w-full rounded-xl border border-white/10 bg-black/25 px-3 py-3 font-mono text-xs text-white outline-none focus:border-amber-300/50 disabled:opacity-50" /></label>
</div>
<div className="mt-3 grid grid-cols-2 gap-2"><Metric label="countdown" value={formatDuration(countdownMs)} tone={countdownMs > 0 ? 'good' : 'warn'} /><Metric label="token at target" value={Number.isFinite(tokenAgeAtTargetMs) ? formatDuration(tokenAgeAtTargetMs) : '토큰 없음'} tone={tokenReady ? 'good' : 'warn'} /></div>
<div className="mt-3 rounded-xl border border-white/8 bg-black/20 p-3 text-[10px] leading-5 text-zinc-500"><div className="flex justify-between gap-3"><span>토큰</span><span className={tokenReady ? 'text-emerald-300' : 'text-amber-300'}>{captchaToken ? `${captchaToken.slice(0, 6)}••••${captchaToken.slice(-4)} · ${formatDuration(tokenAgeMs)}` : '입력되지 않음'}</span></div>{autoState.snapshot && <><div className="flex justify-between gap-3"><span>고정 스냅샷</span><span className="text-right text-zinc-300">{autoState.snapshot.themeName} · {autoState.snapshot.date} {autoState.snapshot.timeLabel} · {autoState.snapshot.person}명</span></div><div className="flex justify-between gap-3"><span>예정 발송</span><span className="font-mono text-zinc-300">{autoState.timeline?.plannedSendAtMs ? formatClock(autoState.timeline.plannedSendAtMs) : '계산 중'}</span></div></>}</div>
{autoState.timeline?.actualSendAtMs && <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4"><Metric label="actual send" value={formatClock(autoState.timeline.actualSendAtMs).split(' ').at(-1) ?? '—'} /><Metric label="arrival error" value={autoState.timeline.arrivalErrorMs === undefined ? '—' : `${autoState.timeline.arrivalErrorMs >= 0 ? '+' : ''}${autoState.timeline.arrivalErrorMs.toFixed(1)}ms`} /><Metric label="response RTT" value={autoState.timeline.rttMs === undefined ? '—' : `${autoState.timeline.rttMs.toFixed(1)}ms`} /><Metric label="HTTP / socket" value={`${autoState.timeline.httpStatus ?? '—'} / ${autoState.timeline.reusedSocket ? 'reused' : 'new'}`} /></div>}
{(error || autoState.message) && <p role="alert" className={`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${error || autoState.status === 'failed' ? 'border-red-300/15 bg-red-300/5 text-red-200' : 'border-emerald-300/15 bg-emerald-300/5 text-emerald-200'}`}>{error || autoState.message}</p>}
<div className="mt-4 grid grid-cols-2 gap-2">{armed ? <button onClick={disarm} disabled={autoState.status === 'firing'} className="col-span-2 rounded-xl border border-red-300/20 py-3 text-xs font-semibold text-red-200 hover:bg-red-300/8 disabled:opacity-40">자동 예약 해제</button> : <button onClick={arm} disabled={busy === 'arm' || !request || !tokenReady} className="col-span-2 rounded-xl bg-amber-300 py-3 text-xs font-bold text-black hover:bg-amber-200 disabled:cursor-not-allowed disabled:bg-zinc-800 disabled:text-zinc-600">{busy === 'arm' ? '무장 중…' : '자동 예약 무장'}</button>}</div>
</div>
</section>
)
}