Files
test-project-161/src/components/AutomationPanel.tsx
T
2026-08-13 01:34:54 +09:00

353 lines
25 KiB
TypeScript

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-line-soft bg-canvas px-3 py-2.5">
<p className="text-[9px] uppercase tracking-[0.18em] text-ink-muted">{label}</p>
<p className={`mt-1 font-mono text-xs ${tone === 'good' ? 'text-success' : tone === 'warn' ? 'text-warning' : 'text-ink'}`}>{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-ink-muted">표본을 수집하는 중입니다.</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-line-soft bg-canvas 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(13,11,8,.12)" />
{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(0,180,187,.35)" />
})}
<polyline points={points} fill="none" stroke="var(--color-violet)" strokeWidth="2" vectorEffect="non-scaling-stroke" />
</svg>
<div className="flex justify-between px-1 text-[9px] text-ink-muted"><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 previousCaptchaAt = useRef<number | null>(null)
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 armed = autoState.status === 'armed' || autoState.status === 'firing'
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 (!captchaPastedAtMs || captchaPastedAtMs === previousCaptchaAt.current || armed) return
previousCaptchaAt.current = captchaPastedAtMs
const estimatedServerNow = clock
? clock.estimatedServerTimeMs + (Date.now() - clock.observedAtMs)
: Date.now()
if (!Number.isFinite(targetServerTimeMs) || targetServerTimeMs <= estimatedServerNow + 150) {
setTargetInput(toKstInput(estimatedServerNow + 30_000))
}
}, [armed, captchaPastedAtMs, clock, targetServerTimeMs])
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'
return (
<section className="panel-card overflow-hidden" aria-label="자동 예약 및 서버시간">
<div className="border-b border-line-soft 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-violet">Precision clock</p>
<h2 className="mt-1 text-base font-semibold text-ink">관측 서버시간</h2>
<p className="mt-1 text-[10px] leading-4 text-ink-muted">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-cyan-deep/30 bg-cyan-soft text-cyan-deep' : 'border-line text-ink-muted hover:text-ink'} disabled:opacity-40`}>
{busy === 'monitor' ? '측정 중…' : clock?.monitoring ? '모니터 중지' : '모니터 시작'}
</button>
</div>
<p className={`mt-5 font-mono text-xl tracking-tight sm:text-2xl ${clock?.monitoring ? 'text-cyan-deep' : 'text-ink'}`} 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="transport" value={`${clock?.protocol ?? (clockSettings.transportMode === 'http2' ? 'h2' : 'http/1.1')} · ${clock?.connectionId ?? 'not connected'}`} tone={clock?.protocol === 'h2' ? 'good' : 'normal'} />
<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-warning">{clock.warning} 품질이 낮아도 마지막 유효 추정값으로 1회 실행합니다.</p>}
<div className="mt-3 flex justify-end"><button onClick={() => setSettingsOpen((value) => !value)} disabled={armed} className="rounded-full border border-line px-3 py-2 text-[10px] font-semibold text-ink-muted hover:text-ink disabled:opacity-40">정밀 보정 설정</button></div>
{settingsOpen && <div className="mt-3 rounded-xl border border-line-soft bg-canvas p-4">
<label className="mb-4 block space-y-1"><span className="text-[9px] font-semibold text-ink-muted">전송 모드</span><select value={clockSettings.transportMode} onChange={(event) => setClockSettings((current) => ({ ...current, transportMode: event.target.value as ClockCalibrationSettings['transportMode'] }))} className="w-full rounded-lg border border-line bg-surface px-3 py-2 font-mono text-xs text-ink outline-none focus:border-accent"><option value="http1">HTTP/1.1 keep-alive (기존)</option><option value="http2">HTTP/2 단일 세션</option></select><span className="block text-[9px] leading-4 text-ink-muted">모드 전환 시 RTT 특성이 달라 기존 시간 보정을 초기화하고 다시 수집합니다.</span></label>
<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-ink-muted">{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-line bg-surface px-3 py-2 font-mono text-xs text-ink outline-none focus:border-accent" /></label>)}
</div>
<div className="mt-3 flex flex-wrap items-center justify-between gap-3 text-[10px] text-ink-muted"><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 }))} className="accent-coral" />초 경계 정밀 측정</label><label className="flex items-center gap-2"><input type="checkbox" checked={clockSettings.autoApply} onChange={(event) => setClockSettings((current) => ({ ...current, autoApply: event.target.checked }))} className="accent-coral" />검증 후 자동 적용</label></div><div className="flex gap-2"><button onClick={() => setClockSettings({ ...CLOCK_CALIBRATION_DEFAULTS })} className="rounded-lg border border-line px-3 py-2 text-ink-muted hover:text-ink">기본값</button><button onClick={saveClockSettings} disabled={busy !== null} className="rounded-lg bg-coral px-3 py-2 font-bold text-coral-ink disabled:opacity-40">설정 적용</button></div></div>
<p className="mt-3 text-[9px] leading-4 text-ink-muted">최소 경계 수와 편차 조건을 모두 통과한 경우에만 추천 보정을 자동 적용합니다. 설정은 앱 메모리에만 유지됩니다.</p>
</div>}
</div>
<div className="border-b border-line-soft p-5 sm:p-6">
<div className="flex items-center justify-between gap-3">
<div><h3 className="text-sm font-semibold text-ink">시간 테스트</h3><p className="mt-1 text-[10px] text-ink-muted">3초 뒤 HEAD 요청으로 스케줄러와 도착 오차를 측정합니다.</p></div>
<button onClick={runTimingTest} disabled={busy === 'test' || armed} className="rounded-full border border-line px-3 py-2 text-[11px] font-semibold text-ink-muted hover:border-ink hover:text-ink 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="connection" value={`${timingTest.protocol ?? '—'} ${timingTest.connectionId ?? ''} · ${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-ink">단일 요청 자동 예약</h3><p className="mt-1 text-[10px] leading-4 text-ink-muted">목표 서버 도착 시각에 토큰 1개를 소비해 정확히 한 번 제출합니다.</p></div><span className={`rounded-full px-2.5 py-1 text-[9px] font-semibold uppercase tracking-wider ${armed ? 'bg-gold text-gold-ink' : autoState.status === 'succeeded' ? 'bg-success/10 text-success' : autoState.status === 'failed' ? 'bg-danger/10 text-danger' : 'bg-chrome text-ink-muted'}`}>{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-ink-muted">실행 시각 (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-line bg-surface px-3 py-3 font-mono text-xs text-ink outline-none focus:border-accent disabled:opacity-50" /></label>
<label className="space-y-2"><span className="text-[10px] font-semibold text-ink-muted">도착 오프셋 (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-line bg-surface px-3 py-3 font-mono text-xs text-ink outline-none focus:border-accent 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-line-soft bg-canvas p-3 text-[10px] leading-5 text-ink-muted"><div className="flex justify-between gap-3"><span>토큰</span><span className={tokenReady ? 'font-semibold text-success' : 'font-semibold text-warning'}>{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-ink">{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-ink">{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 / connection" value={`${autoState.timeline.httpStatus ?? '—'} · ${autoState.timeline.protocol ?? '—'} ${autoState.timeline.connectionId ?? ''} · ${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-danger/25 bg-danger/8 text-danger' : 'border-success/25 bg-success/8 text-success'}`}>{error || autoState.message}</p>}
{!armed && (!request || !tokenReady) && <p className="mt-3 text-[10px] leading-4 text-warning">{!request ? '예약자 정보·인원·동의와 CAPTCHA 인증을 완료해주세요.' : tokenAgeAtTargetMs < 0 ? '실행 시각이 이미 지났습니다. 미래 시각으로 변경해주세요.' : 'CAPTCHA 인증 후 90초 이내의 실행 시각을 입력해주세요.'}</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-danger/30 py-3 text-xs font-semibold text-danger hover:bg-danger/8 disabled:opacity-40">자동 예약 해제</button> : <button onClick={arm} disabled={busy === 'arm'} className="col-span-2 rounded-xl bg-coral py-3 text-xs font-bold text-coral-ink hover:bg-coral-strong disabled:cursor-not-allowed disabled:bg-chrome disabled:text-ink-muted">{busy === 'arm' ? '시작 중…' : '자동 예약 시작'}</button>}</div>
</div>
</section>
)
}