// status.jsx — 연결 상태 진단 페이지 (#/status)
// 배포 각 단계가 실제로 됐는지 앱에서 바로 확인. 비개발자용 신호등.

function StatusPage() {
  const isMobile = useIsMobile();
  const [checks, setChecks] = useState(null);
  const [running, setRunning] = useState(false);

  useEffect(() => { document.title = '연결 상태 진단 — 우리집사기'; run(); }, []);

  const run = async () => {
    setRunning(true);
    const out = {};

    // 1) 도메인 연결
    const host = location.hostname;
    out.domain = {
      ok: host === 'uri-jib.com' || host === 'www.uri-jib.com',
      pending: host.endsWith('.pages.dev'),
      value: host || '(파일 직접 열림)',
    };

    // 2) HTTPS
    out.https = { ok: location.protocol === 'https:', value: location.protocol };

    // 3) PWA / 서비스워커
    let swReg = false;
    try { swReg = !!(navigator.serviceWorker && (await navigator.serviceWorker.getRegistration())); } catch (e) {}
    out.pwa = { ok: swReg, value: swReg ? '등록됨' : '미등록 (HTTPS+배포 후 작동)', warn: !swReg };

    // 4) 백엔드 주소 감지
    const API = window.UJTrack.API_BASE;
    out.apiBase = { ok: !!API, value: API || '(감지 안 됨 — 데모 모드)', warn: !API };

    // 5) 백엔드 헬스
    if (API) {
      try {
        const r = await fetch(API + '/health', { cache: 'no-store' });
        const d = await r.json();
        out.backend = { ok: !!d.ok, value: d.ok ? '응답 정상' : '오류', raw: d };
        out.d1 = { ok: !!d.hasDB, value: d.hasDB ? 'D1 연결됨' : 'D1 미연결', warn: !d.hasDB };
        out.molit = { ok: !!d.hasMolitKey, value: d.hasMolitKey ? 'RTMS 키 등록됨' : 'RTMS 키 없음', warn: !d.hasMolitKey };
      } catch (e) {
        out.backend = { ok: false, value: '연결 실패 — ' + (e.message || '네트워크 오류') };
        out.d1 = { ok: false, value: '확인 불가' };
        out.molit = { ok: false, value: '확인 불가' };
      }
    } else {
      out.backend = { ok: false, value: '백엔드 미배포 (데모 모드)', warn: true };
      out.d1 = { ok: false, value: '—', skip: true };
      out.molit = { ok: false, value: '—', skip: true };
    }

    // 6) RTMS 실제 데이터 시도 (강남구 지난달)
    if (API && out.molit.ok) {
      try {
        const ym = new Date(); ym.setMonth(ym.getMonth() - 1);
        const ymd = ym.getFullYear() + ('' + (ym.getMonth() + 1)).padStart(2, '0');
        const r = await fetch(API + '/v1/molit/recent?lawd_code=11680&deal_ymd=' + ymd);
        const d = await r.json();
        out.rtmsData = { ok: (d.count || (d.items || []).length) > 0, value: (d.count || (d.items || []).length) + '건 수신 (강남구 ' + ymd + ')' };
      } catch (e) {
        out.rtmsData = { ok: false, value: '조회 실패' };
      }
    } else {
      out.rtmsData = { ok: false, value: '—', skip: true };
    }

    // 7) 로그 적재 (백엔드)
    if (API && out.backend.ok) {
      try {
        const r = await fetch(API + '/v1/events', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ events: [{ id: 'e_diag_' + Date.now(), ts: Date.now(), event: 'diagnostic_ping', path: '/status', uid: window.UJTrack.getUid() }] }),
        });
        const d = await r.json();
        out.logging = { ok: !!d.ok, value: d.ok ? '백엔드 적재 성공' : '적재 실패' };
      } catch (e) {
        out.logging = { ok: false, value: '전송 실패' };
      }
    } else {
      out.logging = { ok: true, value: 'localStorage 적재 중 (' + window.UJTrack.readAll().length + '건)', local: true };
    }

    setChecks(out);
    setRunning(false);
  };

  const items = checks ? [
    { key: 'domain', step: '1', label: 'uri-jib.com 도메인 연결', help: 'Cloudflare Pages → Custom domains' },
    { key: 'https', step: '1', label: 'HTTPS 보안 연결', help: '도메인 연결 시 자동' },
    { key: 'pwa', step: '1', label: 'PWA 앱 설치 가능', help: 'HTTPS 배포 후 작동' },
    { key: 'apiBase', step: '2', label: '백엔드 주소 감지', help: 'uri-jib.com 에서 자동으로 api.uri-jib.com 탐지' },
    { key: 'backend', step: '2', label: '백엔드 Worker 응답', help: 'Worker 배포 + api.uri-jib.com 연결' },
    { key: 'd1', step: '2', label: 'D1 데이터베이스 연결', help: 'Worker Settings → D1 binding (DB)' },
    { key: 'molit', step: '2', label: 'RTMS 키 등록', help: 'Worker Secret → MOLIT_API_KEY' },
    { key: 'rtmsData', step: '2', label: '국토부 실거래가 수신', help: 'data.go.kr 키 승인 후 작동' },
    { key: 'logging', step: '2', label: '행동 로그 적재', help: '백엔드 없으면 localStorage' },
  ] : [];

  const doneCount = items.filter(i => checks[i.key] && checks[i.key].ok).length;

  return (
    <div style={{ minHeight: '100vh', background: T.bg, color: T.fg, fontFamily: T.font }}>
      <header style={{ height: 56, borderBottom: '1px solid ' + T.line, background: T.bgAlt, display: 'flex', alignItems: 'center', padding: '0 20px', gap: 14 }}>
        <a href="#/" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <Logo size={26} /><span style={{ fontWeight: 700 }}>우리집사기</span>
        </a>
        <span style={{ fontSize: 11, color: T.info, fontFamily: T.mono, padding: '3px 8px', border: '1px solid ' + T.info + '60', borderRadius: 3, letterSpacing: 1 }}>STATUS</span>
        <a href="deploy/launch-checklist.html" target="_blank" style={{ marginLeft: 'auto', fontSize: 12, color: T.hot, textDecoration: 'none', fontFamily: T.mono }}>출시 체크리스트 →</a>
      </header>

      <div style={{ maxWidth: 760, margin: '0 auto', padding: isMobile ? 16 : 32 }}>
        <PageHead title="연결 상태 진단" sub="배포 각 단계가 실제로 작동하는지 확인합니다" />

        {checks && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: 18, background: T.card, border: '1px solid ' + T.line, borderRadius: 8, marginBottom: 16 }}>
            <div style={{ position: 'relative' }}>
              <ScoreRing score={Math.round(doneCount / items.length * 100)} size={64} stroke={5} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 18, fontWeight: 700 }}>{doneCount} / {items.length} 단계 완료</div>
              <div style={{ fontSize: 12, color: T.fgDim, marginTop: 2 }}>
                {doneCount === items.length ? '🎉 모든 연결 완료! 실시간 데이터가 흐릅니다.' :
                 doneCount >= 3 ? '도메인은 연결됐어요. 백엔드 단계를 마저 진행하세요.' :
                 '아직 배포 전입니다. 아래 빨간 항목부터 처리하세요.'}
              </div>
            </div>
            <button onClick={run} disabled={running} style={{
              padding: '8px 16px', borderRadius: 5, cursor: running ? 'wait' : 'pointer',
              background: T.hot, color: T.bg, border: 'none', fontSize: 12, fontWeight: 700,
            }}>{running ? '확인 중…' : '↻ 다시 진단'}</button>
          </div>
        )}

        {!checks && <div style={{ padding: 40, textAlign: 'center', color: T.fgMuted }}>진단 중…</div>}

        {checks && [1, 2].map(stepNum => (
          <div key={stepNum} style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 12, fontFamily: T.mono, color: T.fgMuted, letterSpacing: 1, marginBottom: 8 }}>
              {stepNum === 1 ? 'STEP 1 — Cloudflare Pages 배포 + 도메인' : 'STEP 2 — 백엔드 + RTMS 실거래가'}
            </div>
            <div style={{ background: T.card, border: '1px solid ' + T.line, borderRadius: 8, overflow: 'hidden' }}>
              {items.filter(i => i.step === '' + stepNum).map((it, idx, arr) => {
                const r = checks[it.key] || {};
                const color = r.ok ? T.up : r.skip ? T.fgMuted : r.warn ? T.hot : T.down;
                const icon = r.ok ? '●' : r.skip ? '○' : r.warn ? '◐' : '✕';
                return (
                  <div key={it.key} style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
                    borderBottom: idx < arr.length - 1 ? '1px solid ' + T.line : 'none',
                  }}>
                    <span style={{ color, fontSize: 16, width: 18, textAlign: 'center', flexShrink: 0 }}>{icon}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{it.label}</div>
                      <div style={{ fontSize: 11, color: T.fgMuted, marginTop: 1 }}>{it.help}</div>
                    </div>
                    <div style={{ fontSize: 11, color, fontFamily: T.mono, textAlign: 'right', maxWidth: 180, wordBreak: 'break-all' }}>{r.value}</div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}

        <div style={{ marginTop: 24, padding: 16, background: T.bgAlt, border: '1px solid ' + T.line, borderRadius: 8, fontSize: 13, color: T.fgDim, lineHeight: 1.7 }}>
          <strong style={{ color: T.fg }}>다음 할 일</strong><br/>
          • <span style={{ color: T.hot }}>주황(◐)</span> = 배포하면 자동 해결되는 항목<br/>
          • <span style={{ color: T.down }}>빨강(✕)</span> = 본인이 처리해야 하는 항목<br/>
          터미널 없이 하는 법: <a href="deploy/no-terminal-guide.html" target="_blank" style={{ color: T.info }}>복붙 배포 가이드 →</a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StatusPage });
