// admin.jsx — 사용자 행동 로그 분석 대시보드
// localStorage 에 적재된 이벤트를 실시간으로 보여준다.

function AdminPage() {
  const [tick, setTick] = useState(0);
  const [filter, setFilter] = useState('');
  const [eventFilter, setEventFilter] = useState('all');
  const [autoRefresh, setAutoRefresh] = useState(true);

  useEffect(() => {
    document.title = '관리자 — 행동 로그 분석';
    const h = () => setTick(t => t + 1);
    window.addEventListener('urijib:event', h);
    window.addEventListener('urijib:cleared', h);
    let id;
    if (autoRefresh) id = setInterval(() => setTick(t => t + 1), 2000);
    return () => {
      window.removeEventListener('urijib:event', h);
      window.removeEventListener('urijib:cleared', h);
      if (id) clearInterval(id);
    };
  }, [autoRefresh]);

  const all = window.UJTrack.readAll();
  const events = all.filter(e => {
    if (eventFilter !== 'all' && e.event !== eventFilter) return false;
    if (filter) {
      const s = (e.event + ' ' + (e.path || '') + ' ' + JSON.stringify(e.props || {})).toLowerCase();
      if (!s.includes(filter.toLowerCase())) return false;
    }
    return true;
  });

  // Aggregates
  const totalEvents = all.length;
  const uniqueUsers = new Set(all.map(e => e.uid)).size;
  const uniqueSessions = new Set(all.map(e => e.sid)).size;
  const authedUsers = new Set(all.filter(e => e.authed).map(e => e.uid)).size;
  const last24 = all.filter(e => Date.now() - e.ts < 86400000).length;

  // Event types
  const byType = {};
  all.forEach(e => { byType[e.event] = (byType[e.event] || 0) + 1; });
  const topEvents = Object.entries(byType).sort((a, b) => b[1] - a[1]).slice(0, 10);

  // Pages
  const byPage = {};
  all.filter(e => e.event === 'page_view').forEach(e => { byPage[e.path] = (byPage[e.path] || 0) + 1; });
  const topPages = Object.entries(byPage).sort((a, b) => b[1] - a[1]).slice(0, 8);

  // Funnel
  const funnel = computeFunnel(all);

  // Hourly chart
  const hourly = computeHourly(all);

  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: 16,
      }}>
        <a href="#/" data-track="admin_back_home" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <Logo size={26} />
          <span style={{ fontWeight: 700 }}>우리집사기</span>
        </a>
        <span style={{ fontSize: 11, color: T.hot, fontFamily: T.mono, padding: '3px 8px', border: '1px solid ' + T.hot + '60', borderRadius: 3, letterSpacing: 1 }}>ADMIN · ANALYTICS</span>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
          <LiveDot label={'LIVE · ' + (autoRefresh ? '2s' : 'OFF')} />
          <button onClick={() => setAutoRefresh(v => !v)} style={tinyBtn(autoRefresh)}>
            {autoRefresh ? '⏸ 자동새로고침 OFF' : '▶ 자동새로고침 ON'}
          </button>
          <button onClick={() => { window.UJTrack.seed(300); setTick(t => t + 1); }} style={tinyBtn(false)}>
            + 데모 데이터 300건 시드
          </button>
          <button onClick={() => { if (confirm('모든 로그를 삭제할까요?')) { window.UJTrack.clearAll(); setTick(t => t + 1); } }} style={{ ...tinyBtn(false), color: T.down, borderColor: T.down + '60' }}>
            전체 삭제
          </button>
          <button onClick={() => exportCSV(all)} style={tinyBtn(false)}>CSV 다운로드</button>
        </div>
      </header>

      <div style={{ padding: 20 }}>
        <PageHead title="행동 로그 분석" sub={`총 ${totalEvents.toLocaleString()}건 · uri-jib.com 사용자 활동 추적`} />

        {/* KPI Strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 16 }}>
          <Panel pad={14}><KPI label="누적 이벤트" value={totalEvents.toLocaleString()} big /></Panel>
          <Panel pad={14}><KPI label="고유 사용자" value={uniqueUsers.toLocaleString()} big sub="기기 기반 UID" /></Panel>
          <Panel pad={14}><KPI label="가입 사용자" value={authedUsers.toLocaleString()} big sub={`전환율 ${uniqueUsers ? Math.round(authedUsers / uniqueUsers * 100) : 0}%`} /></Panel>
          <Panel pad={14}><KPI label="세션" value={uniqueSessions.toLocaleString()} big /></Panel>
          <Panel pad={14}><KPI label="24h 이벤트" value={last24.toLocaleString()} big /></Panel>
        </div>

        {/* Charts row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 16, marginBottom: 16 }}>
          <Panel title="시간대별 활동" subtitle="최근 7일">
            <HourlyChart data={hourly} />
          </Panel>
          <Panel title="이벤트 종류 TOP 10">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {topEvents.length === 0 && <div style={{ color: T.fgMuted, fontSize: 12 }}>아직 데이터가 없습니다. + 데모 데이터를 시드해보세요.</div>}
              {topEvents.map(([k, v]) => (
                <div key={k}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 3 }}>
                    <span style={{ color: T.fgDim, fontFamily: T.mono }}>{k}</span>
                    <span className="uj-num" style={{ color: T.fg, fontWeight: 600 }}>{v.toLocaleString()}</span>
                  </div>
                  <div style={{ height: 3, background: T.cardLo, borderRadius: 2 }}>
                    <div style={{ height: '100%', width: (v / topEvents[0][1] * 100) + '%', background: T.hot, borderRadius: 2 }} />
                  </div>
                </div>
              ))}
            </div>
          </Panel>
          <Panel title="페이지뷰 TOP 8">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {topPages.length === 0 && <div style={{ color: T.fgMuted, fontSize: 12 }}>—</div>}
              {topPages.map(([k, v]) => (
                <div key={k}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 3 }}>
                    <span style={{ color: T.fgDim, fontFamily: T.mono, maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{k}</span>
                    <span className="uj-num" style={{ color: T.fg, fontWeight: 600 }}>{v}</span>
                  </div>
                  <div style={{ height: 3, background: T.cardLo, borderRadius: 2 }}>
                    <div style={{ height: '100%', width: (v / topPages[0][1] * 100) + '%', background: T.info, borderRadius: 2 }} />
                  </div>
                </div>
              ))}
            </div>
          </Panel>
        </div>

        {/* Funnel */}
        <Panel title="가입 → 활성 사용자 퍼널" style={{ marginBottom: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
            {funnel.map((f, i) => (
              <div key={f.key} style={{ position: 'relative' }}>
                <div style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono, letterSpacing: 1, textTransform: 'uppercase' }}>{f.label}</div>
                <div className="uj-num" style={{ fontSize: 26, fontWeight: 700, color: i === 0 ? T.hot : T.fg, marginTop: 4 }}>{f.value}</div>
                {i > 0 && (
                  <div style={{ fontSize: 10, color: T.fgFaint, fontFamily: T.mono, marginTop: 4 }}>
                    {funnel[0].value ? (f.value / funnel[0].value * 100).toFixed(1) : '0'}% 전환
                  </div>
                )}
                <div style={{ marginTop: 8, height: 6, background: T.cardLo, borderRadius: 3 }}>
                  <div style={{ height: '100%', width: (funnel[0].value ? f.value / funnel[0].value * 100 : 0) + '%',
                    background: i === 0 ? T.hot : i === funnel.length - 1 ? T.up : T.info, borderRadius: 3, transition: 'width .3s' }} />
                </div>
              </div>
            ))}
          </div>
        </Panel>

        {/* Event Stream */}
        <Panel title="이벤트 스트림" subtitle={`${events.length.toLocaleString()}건 표시 중`} action={
          <div style={{ display: 'flex', gap: 8 }}>
            <select value={eventFilter} onChange={(e) => setEventFilter(e.target.value)} style={tinySelect}>
              <option value="all">전체 이벤트</option>
              {Object.keys(byType).sort().map(k => <option key={k} value={k}>{k}</option>)}
            </select>
            <input value={filter} onChange={(e) => setFilter(e.target.value)}
              placeholder="검색 (이벤트·경로·props)"
              style={{ ...tinySelect, width: 220, padding: '6px 10px' }} />
          </div>
        }>
          <div className="uj-scroll" style={{ maxHeight: 520, overflow: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11, fontFamily: T.mono }}>
              <thead style={{ position: 'sticky', top: 0, background: T.card }}>
                <tr style={{ color: T.fgMuted }}>
                  {['시간', '이벤트', '경로', '사용자', '세션', 'Props'].map(h => (
                    <th key={h} style={{ textAlign: 'left', padding: '8px 10px', fontWeight: 500, borderBottom: '1px solid ' + T.line }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {events.slice(-200).reverse().map((e) => (
                  <tr key={e.id} style={{ borderBottom: '1px solid ' + T.line + '60' }}>
                    <td style={{ padding: '6px 10px', color: T.fgMuted, whiteSpace: 'nowrap' }}>{new Date(e.ts).toLocaleString('ko-KR', { hour12: false, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })}</td>
                    <td style={{ padding: '6px 10px', color: eventColor(e.event), fontWeight: 600 }}>{e.event}</td>
                    <td style={{ padding: '6px 10px', color: T.fgDim, maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.path || '/'}</td>
                    <td style={{ padding: '6px 10px', color: T.fgDim }}>
                      {e.authed ? <span style={{ color: T.up }}>●</span> : <span style={{ color: T.fgFaint }}>○</span>}{' '}
                      {e.uid.slice(0, 8)}
                    </td>
                    <td style={{ padding: '6px 10px', color: T.fgFaint }}>{e.sid.slice(0, 8)}</td>
                    <td style={{ padding: '6px 10px', color: T.fgDim, maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {Object.keys(e.props || {}).length ? JSON.stringify(e.props) : ''}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {events.length === 0 && (
              <div style={{ padding: 32, textAlign: 'center', color: T.fgMuted, fontSize: 12 }}>
                매칭되는 이벤트가 없습니다.
              </div>
            )}
          </div>
        </Panel>

        <div style={{ marginTop: 24, padding: 16, background: T.bgAlt, border: '1px solid ' + T.line, borderRadius: 4, fontSize: 12, color: T.fgDim, lineHeight: 1.7 }}>
          <strong style={{ color: T.fg }}>💡 어떻게 작동하나요?</strong><br/>
          모든 페이지뷰·클릭·검색·로그인·가입·필터 변경이 자동으로 적재됩니다.
          현재는 <code style={{ color: T.hot, fontFamily: T.mono }}>localStorage</code> 에 저장되며,
          실제 배포 시 <code style={{ color: T.hot, fontFamily: T.mono }}>tracker.jsx</code> 의 <code style={{ color: T.hot, fontFamily: T.mono }}>mockSend()</code> 만
          <code style={{ color: T.hot, fontFamily: T.mono }}>POST https://api.uri-jib.com/v1/events</code> 로 바꾸면 백엔드(Cloudflare Workers + Supabase)로 전송됩니다.
          8초마다 자동 배치 전송 + 페이지 비활성화 시 즉시 flush.
        </div>
      </div>
    </div>
  );
}

function HourlyChart({ data }) {
  const max = Math.max(...data.map(d => d.count), 1);
  const w = 480, h = 140;
  const bw = w / data.length;
  return (
    <svg width="100%" height={h + 20} viewBox={`0 0 ${w} ${h + 20}`} preserveAspectRatio="none" style={{ display: 'block' }}>
      {data.map((d, i) => {
        const bh = (d.count / max) * h;
        return (
          <g key={i}>
            <rect x={i * bw + 1} y={h - bh} width={bw - 2} height={bh} fill={d.count > 0 ? T.hot : T.line} opacity={d.count > 0 ? 0.85 : 0.3} />
            {i % 24 === 0 && (
              <text x={i * bw} y={h + 14} fontSize="9" fill={T.fgFaint} fontFamily={T.mono}>{d.label}</text>
            )}
          </g>
        );
      })}
    </svg>
  );
}

function computeHourly(events) {
  // last 7 days, per-hour bucket = 168 bars
  const now = Date.now();
  const start = now - 7 * 86400000;
  const buckets = Array.from({ length: 168 }, (_, i) => {
    const t = start + i * 3600000;
    return { t, count: 0, label: (i === 0 || i === 24 || i === 72 || i === 168) ? new Date(t).toLocaleDateString('ko-KR', { month: 'numeric', day: 'numeric' }) : '' };
  });
  events.forEach(e => {
    if (e.ts < start) return;
    const i = Math.floor((e.ts - start) / 3600000);
    if (i >= 0 && i < 168) buckets[i].count++;
  });
  // label every 24h
  for (let i = 0; i < 168; i += 24) {
    buckets[i].label = new Date(buckets[i].t).toLocaleDateString('ko-KR', { month: 'numeric', day: 'numeric' });
  }
  return buckets;
}

function computeFunnel(all) {
  const visited = new Set(all.filter(e => e.event === 'page_view').map(e => e.uid));
  const signupStarted = new Set(all.filter(e => e.event === 'signup_start' || e.event === 'signup_attempt').map(e => e.uid));
  const signedUp = new Set(all.filter(e => e.event === 'signup_complete' || e.event === 'login_success').map(e => e.uid));
  const onboarded = new Set(all.filter(e => e.event === 'onboarding_complete').map(e => e.uid));
  const activated = new Set(all.filter(e => e.event === 'view_apt_detail' || e.event === 'watchlist_add').map(e => e.uid));
  return [
    { key: 'visit', label: '방문', value: visited.size },
    { key: 'signup', label: '가입 시도', value: signupStarted.size },
    { key: 'auth', label: '가입·로그인', value: signedUp.size },
    { key: 'onboard', label: '온보딩 완료', value: onboarded.size },
    { key: 'active', label: '단지 조회·관심', value: activated.size },
  ];
}

function eventColor(name) {
  if (name.includes('login') || name.includes('signup')) return T.up;
  if (name.includes('error') || name.includes('fail')) return T.down;
  if (name === 'page_view') return T.info;
  if (name === 'click') return T.fgDim;
  if (name.includes('search')) return T.ai;
  if (name.includes('watchlist') || name.includes('compare')) return T.hot;
  return T.fg;
}

function exportCSV(events) {
  const headers = ['ts', 'event', 'path', 'uid', 'sid', 'authed', 'props'];
  const rows = events.map(e => [
    new Date(e.ts).toISOString(),
    e.event,
    e.path,
    e.uid,
    e.sid,
    e.authed,
    JSON.stringify(e.props || {}).replace(/"/g, '""'),
  ].map(c => '"' + String(c == null ? '' : c) + '"').join(','));
  const csv = [headers.join(','), ...rows].join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = `urijib-events-${Date.now()}.csv`; a.click();
  URL.revokeObjectURL(url);
  window.UJTrack.track('admin_export_csv', { count: events.length });
}

const tinySelect = {
  padding: '6px 10px', borderRadius: 3,
  background: T.cardLo, color: T.fg, border: '1px solid ' + T.line,
  fontSize: 11, fontFamily: T.mono,
};
function tinyBtn(active) {
  return {
    padding: '6px 12px', borderRadius: 3,
    background: active ? T.hot : T.card, color: active ? T.bg : T.fgDim,
    border: '1px solid ' + (active ? T.hot : T.line),
    fontSize: 11, fontFamily: T.mono, cursor: 'pointer', fontWeight: 600,
  };
}

// ─── Misc routes ────────────────────────────────────────
function LegalPage({ type }) {
  const titles = { terms: '이용약관', privacy: '개인정보 처리방침', disclaimer: '투자 면책 고지' };
  useEffect(() => { document.title = titles[type] + ' — 우리집사기'; }, [type]);
  return (
    <div style={{ minHeight: '100vh', background: T.bg, color: T.fg, fontFamily: T.font }}>
      <header style={{ padding: '20px 24px', borderBottom: '1px solid ' + T.line }}>
        <a href="#/" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <Logo size={24} />
          <span style={{ fontWeight: 600 }}>우리집사기</span>
        </a>
      </header>
      <div style={{ maxWidth: 720, margin: '0 auto', padding: '60px 24px' }}>
        <div style={{ fontSize: 11, fontFamily: T.mono, color: T.hot, letterSpacing: 1.5 }}>LEGAL</div>
        <h1 style={{ fontSize: 32, fontWeight: 800, margin: '8px 0 32px' }}>{titles[type]}</h1>
        <div style={{ fontSize: 14, color: T.fgDim, lineHeight: 1.8 }}>
          {type === 'terms' && <TermsBody />}
          {type === 'privacy' && <PrivacyBody />}
          {type === 'disclaimer' && <DisclaimerBody />}
        </div>
      </div>
    </div>
  );
}

function TermsBody() {
  return <div>
    <p>본 약관은 우리집사기(uri-jib.com)가 제공하는 부동산 정보 서비스 이용에 관한 조건을 규정합니다.</p>
    <h3 style={{ color: T.fg, marginTop: 24 }}>제1조 서비스의 내용</h3>
    <p>본 서비스는 공공데이터(국토교통부 실거래가, 한국은행 ECOS) 및 자체 모델 분석을 통한 정보 제공 서비스이며, 투자 자문이나 권유가 아닙니다.</p>
    <h3 style={{ color: T.fg, marginTop: 24 }}>제2조 회원 가입</h3>
    <p>만 14세 이상이며 본 약관에 동의한 자는 회원으로 가입할 수 있습니다.</p>
    <p style={{ marginTop: 32, fontSize: 12, color: T.fgFaint }}>— 본 문서는 변호사 검토 전 초안입니다. —</p>
  </div>;
}
function PrivacyBody() {
  return <div>
    <p>우리집사기는 「개인정보 보호법」을 준수하며 다음 항목을 수집합니다.</p>
    <h3 style={{ color: T.fg, marginTop: 24 }}>수집 항목</h3>
    <ul style={{ paddingLeft: 20 }}>
      <li>필수: 이메일, 이름, 가입 방식(SSO 제공자)</li>
      <li>자동 수집: 기기 식별자(UID), 페이지 방문 기록, 클릭 이벤트, 검색어, IP 주소, User-Agent</li>
      <li>선택: 관심 지역, 예산, 매수 모드</li>
    </ul>
    <h3 style={{ color: T.fg, marginTop: 24 }}>이용 목적</h3>
    <ul style={{ paddingLeft: 20 }}>
      <li>서비스 제공·맞춤 추천</li>
      <li>서비스 개선을 위한 사용 패턴 분석</li>
      <li>고객 지원</li>
    </ul>
    <h3 style={{ color: T.fg, marginTop: 24 }}>보유 기간</h3>
    <p>회원 탈퇴 시 즉시 파기. 행동 로그는 익명화 후 90일 보관.</p>
    <p style={{ marginTop: 32, fontSize: 12, color: T.fgFaint }}>— 본 문서는 변호사 검토 전 초안입니다. —</p>
  </div>;
}
function DisclaimerBody() {
  return <div>
    <p style={{ padding: 16, background: T.downBg, border: '1px solid ' + T.down + '40', borderRadius: 4 }}>
      <strong style={{ color: T.down }}>⚠ 본 서비스는 투자 자문이나 권유가 아닙니다.</strong> 모든 매수·매도 결정은 본인의 책임 하에 이루어져야 합니다.
    </p>
    <p style={{ marginTop: 16 }}>
      우리집사기가 제공하는 AI 시그널(BUY/WATCH/HOLD)·가격 예측·매수 적기는 과거 데이터와 통계 모델에 기반한 정보 제공이며, 미래 수익을 보장하지 않습니다.
    </p>
    <p>실제 매매 결정 시 공인중개사·세무사·금융기관과 상담하시기 바랍니다.</p>
  </div>;
}

function PricingPage() {
  useEffect(() => { document.title = '요금 — 우리집사기'; }, []);
  return (
    <div style={{ minHeight: '100vh', background: T.bg, color: T.fg, fontFamily: T.font }}>
      <header style={{ padding: '20px 24px', borderBottom: '1px solid ' + T.line }}>
        <a href="#/" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <Logo size={24} />
          <span style={{ fontWeight: 600 }}>우리집사기</span>
        </a>
      </header>
      <div style={{ maxWidth: 960, margin: '0 auto', padding: '80px 24px', textAlign: 'center' }}>
        <div style={{ fontSize: 11, fontFamily: T.mono, color: T.hot, letterSpacing: 1.5 }}>PRICING</div>
        <h1 style={{ fontSize: 40, fontWeight: 800, margin: '12px 0 16px' }}>지금은 전부 무료입니다.</h1>
        <p style={{ fontSize: 16, color: T.fgDim }}>베타 기간 중 기능 제한 없이 사용 가능. 정식 출시 후에도 무료 플랜 유지.</p>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginTop: 48, textAlign: 'left' }}>
          <Panel pad={28}>
            <div style={{ fontFamily: T.mono, fontSize: 11, color: T.hot, letterSpacing: 1.5 }}>FREE</div>
            <div style={{ fontSize: 36, fontWeight: 800, marginTop: 8 }}>₩0</div>
            <div style={{ fontSize: 13, color: T.fgMuted }}>영구 무료</div>
            <ul style={{ marginTop: 24, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13, color: T.fgDim }}>
              <li>✓ AI 매수 시그널 (관심 단지 5개)</li>
              <li>✓ 가격 예측 12개월</li>
              <li>✓ 실시간 뉴스 알림</li>
              <li>✓ 대출·세금 시뮬레이터</li>
            </ul>
            <a href="#/signup" data-track="pricing_free_cta" style={{ ...primaryBtn, marginTop: 24, width: '100%', justifyContent: 'center' }}>시작하기 →</a>
          </Panel>
          <Panel pad={28}>
            <div style={{ fontFamily: T.mono, fontSize: 11, color: T.ai, letterSpacing: 1.5 }}>PRO · COMING SOON</div>
            <div style={{ fontSize: 36, fontWeight: 800, marginTop: 8, color: T.fgMuted }}>₩9,900<span style={{ fontSize: 14 }}>/월</span></div>
            <div style={{ fontSize: 13, color: T.fgMuted }}>정식 출시 후</div>
            <ul style={{ marginTop: 24, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13, color: T.fgDim }}>
              <li>✓ 무제한 관심 단지</li>
              <li>✓ 모델 SHAP 상세 분석</li>
              <li>✓ 백테스트·시나리오</li>
              <li>✓ 우선 고객 지원</li>
            </ul>
          </Panel>
        </div>
      </div>
    </div>
  );
}

function AboutPage() {
  useEffect(() => { document.title = '회사 소개 — 우리집사기'; }, []);
  return (
    <div style={{ minHeight: '100vh', background: T.bg, color: T.fg, fontFamily: T.font }}>
      <header style={{ padding: '20px 24px', borderBottom: '1px solid ' + T.line }}>
        <a href="#/" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <Logo size={24} />
          <span style={{ fontWeight: 600 }}>우리집사기</span>
        </a>
      </header>
      <div style={{ maxWidth: 720, margin: '0 auto', padding: '80px 24px' }}>
        <div style={{ fontSize: 11, fontFamily: T.mono, color: T.hot, letterSpacing: 1.5 }}>ABOUT</div>
        <h1 style={{ fontSize: 40, fontWeight: 800, margin: '12px 0 24px' }}>실거래가 시대의 부동산 의사결정.</h1>
        <p style={{ fontSize: 17, color: T.fgDim, lineHeight: 1.7 }}>
          국토부 실거래가는 모두에게 공개되지만, "지금 사도 되는지" 판단하는 일은 여전히 어렵습니다.
          우리집사기는 공공 데이터와 통계 모델을 결합해 매수 의사결정에 도움이 되는 정보를 제공합니다.
        </p>
        <p style={{ fontSize: 14, color: T.fgMuted, marginTop: 32, fontFamily: T.mono }}>
          © 2026 우리집사기 · uri-jib.com<br/>
          데이터 출처 — 국토교통부 RTMS, 한국은행 ECOS, KB부동산, 한국부동산원, 통계청
        </p>
      </div>
    </div>
  );
}

function NotFound() {
  useEffect(() => { document.title = '404 — 우리집사기'; window.UJTrack.track('not_found', { path: location.hash }); }, []);
  return (
    <div style={{ minHeight: '100vh', background: T.bg, color: T.fg, fontFamily: T.font, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 20 }}>
      <div style={{ fontSize: 96, fontFamily: T.mono, color: T.hot, fontWeight: 800 }}>404</div>
      <div style={{ fontSize: 18 }}>페이지를 찾을 수 없습니다.</div>
      <a href="#/" data-track="404_home" style={primaryBtn}>홈으로 →</a>
    </div>
  );
}

Object.assign(window, { AdminPage, LegalPage, PricingPage, AboutPage, NotFound });
