import {useEffect, useState} from 'react'; function nextPicker(lines: string[]) { let remaining: number[] = []; let previous = -1; return () => { if (!remaining.length) remaining = lines.map((_, index) => index); const choices = remaining.filter((index) => index !== previous); const available = choices.length ? choices : remaining; const index = available[Math.floor(Math.random() * available.length)]; remaining = remaining.filter((value) => value !== index); previous = index; return lines[index]; }; } /** * 하늘 문구·기온 문구를 **한 타이머**로 같이 돌린다. * * ★ 왜 하나로 묶나 (대표: "타이틀이랑 소문구 같이 안 나옴, 타이밍 안 맞음") * 전에는 `useWeatherNote` 를 두 번 불러 각자 자기 `setInterval` 을 가졌다. 둘 다 20초 * 간격이라도 첫 타이머가 언제 걸렸는지가 살짝씩 갈려 시간이 지날수록 두 줄이 서로 * 다른 시점에 바뀌었다 — 손님 눈에는 한 카드 안에서 문장 둘이 따로 노는 것으로 보인다. * 타이머 하나가 두 줄을 같이 뽑으면 항상 같은 순간에 같이 바뀐다. * ★ 첫 렌더는 고정해 SSR 과 맞추고, 붙은 뒤 첫 타이머에서 무작위 문구로 전환한다. */ export function useWeatherNotes( skyLines: string[] | undefined, skyFallback: string | undefined, tempLines: string[] | undefined, tempFallback: string | undefined, ): [string | undefined, string | undefined] { const [picked, setPicked] = useState<{sky?: string; temp?: string}>({}); useEffect(() => { if (!skyLines?.length && !tempLines?.length) return; const pickSky = skyLines?.length ? nextPicker(skyLines) : undefined; const pickTemp = tempLines?.length ? nextPicker(tempLines) : undefined; const next = () => setPicked({sky: pickSky?.(), temp: pickTemp?.()}); const first = window.setTimeout(next, 0); const timer = window.setInterval(next, 20_000); return () => { window.clearTimeout(first); window.clearInterval(timer); }; }, [skyLines, tempLines]); return [ picked.sky ?? skyLines?.[0] ?? skyFallback, picked.temp ?? tempLines?.[0] ?? tempFallback, ]; }