const MAINTENANCE = {
  scheduled: {
    key: '점검 예정', icon: 'calendar-clock', tone: 'warn', dismissible: true,
    title: '오늘 밤 서버 점검이 있어요',
    note: '점검 시간에는 앱을 이용할 수 없어요. 작성 중인 기록은 미리 저장해 주세요.',
    window: '2026. 8. 26. 02:00 → 04:00', duration: '약 2시간 예정',
    rows: [['점검 시작', '오늘 새벽 2:00'], ['예상 종료', '오늘 새벽 4:00'], ['영향 범위', '앱 전체 · 관리자'], ['알림', '시작 10분 전 푸시']],
    hint: '점검 중에는 기록 작성 · 댓글 · 미션 인증이 모두 중단돼요.',
    cta: '확인했어요', sub: '점검 공지 자세히 보기',
  },
  inprogress: {
    key: '점검 중', icon: 'tools', tone: 'warn', spinner: true,
    title: '더 맛있는 Spoture를 준비하고 있어요',
    note: '지금은 서비스를 이용할 수 없어요. 점검이 끝나면 자동으로 다시 열립니다.',
    window: '2026. 8. 26. 02:00 → 04:00', left: 1420, progress: 41,
    rows: [['점검 시작', '02:00'], ['예상 종료', '04:00'], ['현재 진행', '데이터 이전 중'], ['공지 번호', 'NOTICE-2026-081']],
    hint: '작성 중이던 기록은 임시 저장되어 있어 점검 후 이어서 올릴 수 있어요.',
  },
  extended: {
    key: '점검 연장', icon: 'clock-exclamation', tone: 'warn',
    title: '점검이 40분 연장되었어요',
    note: '예상보다 데이터 이전이 오래 걸리고 있어요. 불편을 드려 죄송합니다.',
    window: '종료 04:00 → 04:40 변경', left: 2280, progress: 78,
    rows: [['최초 예상 종료', '04:00'], ['변경된 종료', '04:40'], ['연장 사유', '데이터 이전 지연'], ['공지 갱신', '03:52']],
    hint: '연장으로 이용하지 못한 시간만큼 진행 중인 미션 기간도 함께 늘어나요.',
  },
  emergency: {
    key: '긴급 점검', icon: 'alert-triangle', tone: 'dark', spinner: true,
    title: '긴급 점검이 진행 중이에요',
    note: '예고 없이 점검에 들어가 죄송해요. 문제를 확인하는 즉시 다시 열겠습니다.',
    window: '2026. 8. 26. 21:14 시작', left: 900,
    rows: [['시작 시각', '21:14'], ['예상 종료', '미정 — 확인 중'], ['영향 범위', '앱 전체'], ['공지 번호', 'URGENT-2026-014']],
    hint: '복구 상황은 공식 채널과 푸시 알림으로 가장 먼저 알려드려요.',
  },
  partial: {
    key: '일부 기능 제한', icon: 'photo-off', tone: 'warn', dismissible: true,
    title: '지금은 사진 업로드만 어려워요',
    note: '이미지 서버만 점검 중이에요. 피드 보기 · 댓글 · 미션 확인은 그대로 이용할 수 있어요.',
    window: '2026. 8. 26. 14:00 → 15:30', left: 3300, progress: 62,
    rows: [['제한 기능', '사진 업로드 · 프로필 사진'], ['정상 기능', '피드 · 댓글 · 미션'], ['예상 종료', '오후 3:30'], ['공지 번호', 'NOTICE-2026-079']],
    hint: '업로드를 시도하면 임시 저장되고, 점검이 끝나면 알림으로 알려드려요.',
    cta: '둘러보기 계속하기', sub: '점검 공지 자세히 보기',
  },
};

function Maintenance({ kind, onDismiss }) {
  const { Button } = window.SpotureDesignSystem_f7ad96;
  const s = MAINTENANCE[kind] || MAINTENANCE.inprogress;
  const dark = s.tone === 'dark';
  const up = s.left && s.progress == null;
  const [left, setLeft] = React.useState(s.left || 0);
  const [sheet, setSheet] = React.useState(null);
  const [spin, setSpin] = React.useState(false);
  React.useEffect(() => {
    if (!s.left) return;
    const t = setInterval(() => setLeft(v => (up ? v + 1 : v > 0 ? v - 1 : 0)), 1000);
    return () => clearInterval(t);
  }, [s.left, up]);
  const mm = String(Math.floor(left / 60)).padStart(2, '0');
  const ss = String(left % 60).padStart(2, '0');
  const accent = dark ? '#fff' : 'var(--text-warning)';
  const softBg = dark ? 'rgba(255,255,255,.12)' : 'var(--bg-warning)';
  const line = dark ? 'rgba(255,255,255,.12)' : 'var(--border)';
  const sub = dark ? 'rgba(255,255,255,.62)' : 'var(--text-secondary)';
  const dim = dark ? 'rgba(255,255,255,.5)' : 'var(--text-muted)';
  const fg = dark ? '#fff' : 'var(--text-primary)';
  const refresh = () => { setSpin(true); setTimeout(() => setSpin(false), 1400); };
  return (
    <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', background: dark ? 'var(--bg-ink)' : 'var(--surface-1)' }}>
      <StatusBar light={dark} />
      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: s.cta ? '10px 26px 20px' : '10px 26px 34px', display: 'flex', flexDirection: 'column', gap: 22 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 15, paddingTop: 24 }}>
          <div style={{ position: 'relative', width: 78, height: 78, borderRadius: '50%', background: softBg, display: 'flex', alignItems: s.spinner ? 'flex-end' : 'center', justifyContent: 'center', paddingBottom: s.spinner ? 22 : 0 }}>
            {s.spinner ? (
              <React.Fragment>
                <span style={{ position: 'absolute', bottom: 22, width: 34, height: 18, borderRadius: '0 0 17px 17px', background: accent }}></span>
                <span style={{ position: 'absolute', bottom: 39, width: 46, height: 4, borderRadius: 999, background: accent, opacity: .55 }}></span>
                {[0, .22, .44].map((d, i) => (
                  <span key={i} style={{ position: 'absolute', bottom: 42, left: 22 + i * 12, width: 4, height: 10, borderRadius: 999, background: accent, opacity: .7, animation: 'spsteam 1.3s ease-in-out ' + d + 's infinite' }}></span>
                ))}
              </React.Fragment>
            ) : (
              <i className={'ti ti-' + s.icon} style={{ fontSize: 34, color: accent }}></i>
            )}
          </div>
          <span style={{ font: '700 11px/1 var(--font-family)', letterSpacing: '.08em', color: accent, background: softBg, borderRadius: 999, padding: '8px 12px' }}>{s.key}</span>
          <span style={{ font: 'var(--text-title)', color: fg, textAlign: 'center', letterSpacing: '-.02em', textWrap: 'pretty' }}>{s.title}</span>
          <p style={{ font: 'var(--text-body)', color: sub, textAlign: 'center', margin: 0, lineHeight: 1.65, textWrap: 'pretty' }}>{s.note}</p>
        </div>
        <div style={{ background: dark ? 'rgba(255,255,255,.07)' : 'var(--surface-2)', borderRadius: 'var(--radius-card)', padding: 18, display: 'flex', flexDirection: 'column', gap: 13 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
            <span style={{ font: 'var(--text-caption)', color: sub }}>점검 시간</span>
            <span style={{ font: '600 12.5px/1.4 var(--font-family)', color: fg, textAlign: 'right' }}>{s.window}</span>
          </div>
          {s.left ? (
            <React.Fragment>
              {s.progress != null && <div style={{ height: 7, borderRadius: 999, background: dark ? 'rgba(255,255,255,.14)' : 'var(--border)', overflow: 'hidden' }}><div style={{ width: s.progress + '%', height: '100%', borderRadius: 999, background: accent }}></div></div>}
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{ font: 'var(--text-caption)', color: sub }}>{up ? '경과 시간' : '남은 시간'}</span>
                <span style={{ font: '700 21px/1 var(--font-family)', color: fg, fontVariantNumeric: 'tabular-nums', letterSpacing: '-.01em' }}>{mm}:{ss}</span>
              </div>
            </React.Fragment>
          ) : (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><i className="ti ti-bell" style={{ fontSize: 15, color: accent }}></i><span style={{ font: '600 13px/1 var(--font-family)', color: fg }}>{s.duration}</span></div>
          )}
        </div>
        <div style={{ border: '1px solid ' + line, borderRadius: 'var(--radius-card)', padding: '4px 18px' }}>
          {s.rows.map(r => (
            <div key={r[0]} style={{ display: 'flex', justifyContent: 'space-between', gap: 14, padding: '13px 0', borderBottom: '1px solid ' + line }}>
              <span style={{ font: 'var(--text-caption)', color: sub, flexShrink: 0 }}>{r[0]}</span>
              <span style={{ font: '600 13px/1.4 var(--font-family)', color: fg, textAlign: 'right' }}>{r[1]}</span>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 11, background: dark ? 'rgba(255,255,255,.07)' : 'var(--surface-2)', borderRadius: 'var(--radius-tile)', padding: '15px 16px' }}>
          <i className="ti ti-info-circle" style={{ fontSize: 17, color: dim, flexShrink: 0, marginTop: 1 }}></i>
          <span style={{ font: 'var(--text-small)', color: sub, lineHeight: 1.6, textWrap: 'pretty' }}>{s.hint}</span>
        </div>
      </div>
      {s.cta && (
        <div style={{ padding: '0 26px 30px', display: 'flex', flexDirection: 'column', gap: 9, flexShrink: 0 }}>
          <Button variant="primary" onClick={s.dismissible ? onDismiss : refresh}>
            {spin ? '확인 중…' : s.cta}
          </Button>
          {s.sub && <span onClick={() => setSheet('notice')} style={{ font: '600 13px/1 var(--font-family)', color: dim, textAlign: 'center', padding: '12px 0', cursor: 'pointer' }}>{s.sub}</span>}
        </div>
      )}
      {sheet === 'notice' && <MaintenanceNoticeSheet s={s} onClose={() => setSheet(null)} />}
    </div>
  );
}
window.Maintenance = Maintenance;

function MaintenanceNoticeSheet({ s, onClose }) {
  const { Button } = window.SpotureDesignSystem_f7ad96;
  const log = [
    ['circle-check', '점검 계획 공지', '앱 내 공지 · 푸시 발송 완료'],
    ['circle-dot', '점검 시작', s.window],
    ['tool', '진행 작업', '이미지 서버 교체 · 데이터 이전 · 지표 재계산'],
    ['circle', '점검 종료 후', '자동으로 다시 접속됩니다'],
  ];
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(20,20,20,.44)', display: 'flex', alignItems: 'flex-end', zIndex: 60 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxHeight: '86%', display: 'flex', flexDirection: 'column', background: 'var(--surface-1)', borderRadius: '24px 24px 0 0', padding: '10px 24px 28px', boxShadow: 'var(--shadow-sheet)' }}>
        <div style={{ width: 38, height: 4, borderRadius: 999, background: 'var(--border-strong)', margin: '0 auto 18px', flexShrink: 0 }}></div>
        <span style={{ font: 'var(--text-heading)', display: 'block', marginBottom: 7 }}>점검 공지</span>
        <p style={{ font: 'var(--text-caption)', color: 'var(--text-secondary)', margin: '0 0 16px', lineHeight: 1.6 }}>{s.note}</p>
        <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 16 }}>
          {log.map(r => (
            <div key={r[1]} style={{ display: 'flex', gap: 13, background: 'var(--surface-2)', borderRadius: 'var(--radius-tile)', padding: '15px 16px' }}>
              <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--surface-1)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><i className={'ti ti-' + r[0]} style={{ fontSize: 17, color: 'var(--text-warning)' }}></i></div>
              <div>
                <span style={{ font: 'var(--text-body-strong)', display: 'block', marginBottom: 4 }}>{r[1]}</span>
                <span style={{ font: 'var(--text-small)', color: 'var(--text-secondary)', lineHeight: 1.6, textWrap: 'pretty' }}>{r[2]}</span>
              </div>
            </div>
          ))}
        </div>
        <Button variant="primary" onClick={onClose}>확인</Button>
      </div>
    </div>
  );
}
window.MaintenanceNoticeSheet = MaintenanceNoticeSheet;
