// Inspection screens — Group Tabs (4 tabs) + Items
// 4탭: 소방시설 / 피난방화시설 / 화기취급감독 / 기타사항
// 기타사항 탭은 freeform 모드 (이상없음/직접입력 2버튼)

// ──────────────────────────────────────────────
// Reusable: big primary button
// ──────────────────────────────────────────────
function BigYellowButton({ children, onClick, outline, theme }) {
  const t = theme || window.THEME || { brand: '#2563eb', brandInk: '#ffffff' };
  return (
    <button
      onClick={onClick}
      style={{
        width: '100%', minHeight: 56,
        background: outline ? '#fff' : t.brand,
        border: outline ? '1.5px solid #1a1a18' : '1.5px solid transparent',
        borderRadius: 14,
        fontSize: 16, fontWeight: 800, color: outline ? '#1a1a18' : t.brandInk,
        fontFamily: 'inherit', cursor: 'pointer',
        WebkitTapHighlightColor: 'transparent',
        boxShadow: outline ? 'none' : `0 4px 12px ${t.brand}66`,
        letterSpacing: '-0.01em',
        transition: 'transform 160ms, background 360ms, color 360ms',
      }}
      onMouseDown={e => e.currentTarget.style.transform = 'scale(0.98)'}
      onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
    >
      {children}
    </button>
  );
}

// ──────────────────────────────────────────────
// Home — 대시보드
// ──────────────────────────────────────────────
function HomeScreen({ onStart, onHistory, stats, theme, onPhotoYear, onPhotoMonth, onPhotoToken }) {
  const t = theme || window.THEME || { brand: '#2563eb' };
  const now = new Date();
  
  // 1. 실제 전달받은 요약 데이터 (없을 경우 미점검 상태로 초기화)
  const summaryData = stats?.summary || [
    { label: '소방시설', sub: '미점검', color: '#8a8880' },
    { label: '피난방화시설', sub: '미점검', color: '#8a8880' },
    { label: '화기취급감독', sub: '미점검', color: '#8a8880' },
    { label: '기타사항', sub: '미점검', color: '#8a8880' },
  ];

  // 2. 실제 전달받은 최근 알림 이력
  const alarmsData = stats?.alarms || [];

  return (
    <div style={{ padding: '18px 16px 20px' }}>
      <div style={{ fontSize: 13, color: '#5a5a55', fontWeight: 600, marginBottom: 6 }}>
        {now.getFullYear()}년 {now.getMonth() + 1}월
      </div>
      <div style={{ fontSize: 15, fontWeight: 800, color: '#1a1a18', marginBottom: 12 }}>
        이번달 업무수행기록 현황
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {summaryData.map((s, i) => (
          <div key={i} style={{
            background: '#fff', border: '1px solid #e5e3dc',
            borderRadius: 12, padding: '12px 14px',
            animation: `fadeUp 360ms ${i * 70}ms cubic-bezier(.4,1.2,.4,1) both`,
          }}>
            <div style={{ fontSize: 11.5, color: '#8a8880', fontWeight: 500, marginBottom: 4 }}>
              {s.label}
            </div>
            <div style={{ fontSize: 15, fontWeight: 800, color: s.color || '#15803d', letterSpacing: '-0.01em' }}>
              {s.sub}
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 20, marginBottom: 10, fontSize: 15, fontWeight: 800 }}>
        최근 소리톡 알림
      </div>
      <div style={{
        background: '#fff', border: '1px solid #e5e3dc', borderRadius: 12,
        overflow: 'hidden',
      }}>
        {alarmsData.length === 0 ? (
          <div style={{ padding: '24px 16px', textAlign: 'center', color: '#8a8880', fontSize: 13, fontWeight: 500 }}>
            최근 발생한 알림이 없습니다.
          </div>
        ) : (
          alarmsData.map((a, i) => {
            const isAlarm = a.type === 'ALARM' || a.type === 'alarm';
            const statusColor = isAlarm ? '#cc2222' : '#15803d';
            
            return (
              <div key={i} style={{
                padding: '12px 14px',
                borderTop: i ? '1px solid #ece9e0' : 'none',
                display: 'flex', alignItems: 'center',
              }}>
                <div style={{ flex: 1 }}>
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 6,
                    fontSize: 13, fontWeight: 700, color: statusColor,
                  }}>
                    <span style={{
                      width: 8, height: 8, borderRadius: '50%',
                      background: statusColor,
                      boxShadow: isAlarm
                        ? '0 0 0 3px rgba(204,34,34,.18)'
                        : '0 0 0 3px rgba(21,128,61,.18)',
                    }} />
                    {isAlarm ? '경보' : '복구'}
                  </div>
                  <div style={{ fontSize: 11.5, color: '#8a8880', marginTop: 2 }}>
                    {a.time}
                  </div>
                </div>
                <div style={{ fontSize: 13, color: '#5a5a55', fontWeight: 600 }}>
                  {a.v ? `${a.v}V` : ''}
                </div>
              </div>
            );
          })
        )}
      </div>

      <div style={{ marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <BigYellowButton onClick={onStart} theme={theme}>점검 기록하기</BigYellowButton>
        <BigYellowButton onClick={onHistory} outline theme={theme}>월간 기록 보기</BigYellowButton>
      </div>

      {/* 안전점검 사진기록 */}
      <PhotoRecord year={onPhotoYear} month={onPhotoMonth} token={onPhotoToken} />
    </div>
  );
}

function PhotoRecord({ year, month, token }) {
  const [photos, setPhotos] = React.useState([]);
  const [uploading, setUploading] = React.useState(false);
  const [viewPhoto, setViewPhoto] = React.useState(null);
  const fileRef = React.useRef();
  const MAX = 5;

  const loadPhotos = () => {
    if (!year || !month || !token) return;
    fetch(`/api/monthly/${year}/${month}/photos`, {
      headers: { 'Authorization': `Bearer ${token}` }
    }).then(r => r.json()).then(data => {
      if (Array.isArray(data)) setPhotos(data);
    }).catch(() => {});
  };

  React.useEffect(() => { loadPhotos(); }, [year, month]);

  const handleFile = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    if (photos.length >= MAX) { alert('최대 5장까지 업로드 가능합니다.'); return; }
    setUploading(true);
    const form = new FormData();
    form.append('photo', file);
    try {
      const res = await fetch(`/api/monthly/${year}/${month}/photos`, {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body: form
      });
      const data = await res.json();
      const photo = data.photo || data;
      if (photo.id) {
        setPhotos(prev => [...prev, { ...photo, url: photo.url || `/uploads/photos/${photo.filename}` }]);
      }
    } catch(e) {}
    setUploading(false);
    e.target.value = '';
  };

  const handleDelete = async (id) => {
    try {
      await fetch(`/api/monthly/${year}/${month}/photos/${id}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${token}` }
      });
      setPhotos(prev => prev.filter(p => p.id !== id));
    } catch(e) {}
  };

  return (
    <div style={{ marginTop: 16, background: '#fff', border: '1px solid #ece9e0', borderRadius: 14, padding: '14px 16px' }}>
      <div style={{ fontSize: 14, fontWeight: 800, color: '#1a1a18', marginBottom: 10 }}>
        안전점검 사진기록
        <span style={{ fontSize: 11, color: '#8a8880', fontWeight: 500, marginLeft: 6 }}>{photos.length}/{MAX}장</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 10 }}>
        {viewPhoto && (
          <div onClick={() => setViewPhoto(null)} style={{
            position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
            background: 'rgba(0,0,0,0.92)', zIndex: 9999,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          }}>
            <img src={viewPhoto.url} alt="" style={{ maxWidth: '100%', maxHeight: '80vh', objectFit: 'contain' }} />
            <div style={{ display: 'flex', gap: 12, marginTop: 16 }}>
              <a href={viewPhoto.url} download style={{
                background: '#fff', borderRadius: 8, padding: '8px 18px',
                fontSize: 13, fontWeight: 700, color: '#1a1a18', textDecoration: 'none',
              }}>다운로드</a>
              <button onClick={e => { e.stopPropagation(); handleDelete(viewPhoto.id); setViewPhoto(null); }} style={{
                background: '#cc2222', border: 'none', borderRadius: 8, padding: '8px 18px',
                fontSize: 13, fontWeight: 700, color: '#fff', cursor: 'pointer', fontFamily: 'inherit',
              }}>삭제</button>
            </div>
            <div style={{ color: '#fff', fontSize: 12, marginTop: 10, opacity: 0.6 }}>탭하여 닫기</div>
          </div>
        )}
        {photos.map(p => (
          <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, background: '#fbf9f3', border: '1px solid #ece9e0', borderRadius: 10, padding: '8px 10px' }}>
            <img src={p.url} alt="" onClick={() => setViewPhoto(p)} style={{ width: 56, height: 56, borderRadius: 8, objectFit: 'cover', flexShrink: 0, cursor: 'pointer' }} />
            <div style={{ flex: 1, fontSize: 12, color: '#5a5a55' }}>{p.description || p.taken_at || ''}</div>
            <button onClick={() => handleDelete(p.id)} style={{
              background: '#fff', border: '1px solid #cc2222', borderRadius: 8,
              padding: '5px 10px', fontSize: 11, fontWeight: 700, color: '#cc2222',
              fontFamily: 'inherit', cursor: 'pointer', flexShrink: 0,
            }}>삭제</button>
          </div>
        ))}
        {photos.length === 0 && (
          <div style={{ textAlign: 'center', padding: '16px 0', color: '#8a8880', fontSize: 13 }}>
            등록된 사진이 없습니다
          </div>
        )}
      </div>
      <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleFile} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <button disabled={photos.length >= MAX || uploading} onClick={() => { fileRef.current.removeAttribute('capture'); fileRef.current.click(); }}
          style={{ padding: '10px', background: '#fff', border: '1.5px solid #d4d1c7', borderRadius: 10, fontSize: 12.5, fontWeight: 700, color: photos.length >= MAX ? '#d4d1c7' : '#1a1a18', fontFamily: 'inherit', cursor: photos.length >= MAX ? 'not-allowed' : 'pointer' }}>
          앨범에서 선택
        </button>
        <button disabled={photos.length >= MAX || uploading} onClick={() => { fileRef.current.setAttribute('capture', 'environment'); fileRef.current.click(); }}
          style={{ padding: '10px', background: photos.length >= MAX ? '#d4d1c7' : '#1a1a18', border: 'none', borderRadius: 10, fontSize: 12.5, fontWeight: 700, color: '#fff', fontFamily: 'inherit', cursor: photos.length >= MAX ? 'not-allowed' : 'pointer' }}>
          {uploading ? '업로드 중...' : '카메라 촬영'}
        </button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────
// GroupTabsScreen — 4탭 + 설비군 리스트 (혹은 기타사항 분기)
// ──────────────────────────────────────────────
function GroupTabsScreen({ activeGroup, onGroupChange, values, etcMode, etcText, onEtcMode, onEtcText, onPickCategory, onAllGoodCategory, onSaveMemo, theme, groups: propGroups }) {
  const t = theme || window.THEME || { brand: '#2563eb' };
  const groups = propGroups || window.INSPECTION_GROUPS || [];
  const cur = groups.find(g => g.id === activeGroup) || groups[0];

  if (!cur) return null;

  // 💡 기타사항일 경우 무조건 EtcScreen으로 빠지도록 안전장치 추가
  const isFree = cur.isFreeform || cur.id === 'g4' || cur.short === '기타사항';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* 4-tab segmented control */}
      <div style={{
        padding: '12px 16px 8px',
        borderBottom: '1px solid #ece9e0',
        background: '#fff',
      }}>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
          background: '#f1efea', borderRadius: 11,
          padding: 4, position: 'relative',
        }}>
          {/* indicator */}
          {(() => {
            const idx = groups.findIndex(g => g.id === cur.id);
            return (
              <div style={{
                position: 'absolute',
                top: 4, left: `calc(${idx} * (100% - 8px) / 4 + 4px)`,
                width: 'calc((100% - 8px) / 4)', height: 'calc(100% - 8px)',
                background: '#fff',
                borderRadius: 8,
                boxShadow: '0 1px 3px rgba(0,0,0,.06), 0 1px 1px rgba(0,0,0,.04)',
                transition: 'left 280ms cubic-bezier(.5,1.4,.5,1)',
                border: `1.5px solid ${cur.accent}`,
              }} />
            );
          })()}
          {groups.map(g => {
            const on = g.id === cur.id;
            return (
              <button
                key={g.id}
                onClick={() => onGroupChange(g.id)}
                style={{
                  position: 'relative', zIndex: 1,
                  background: 'transparent', border: 'none',
                  padding: '10px 4px',
                  fontSize: 12, fontWeight: on ? 700 : 600,
                  color: on ? g.accent : '#5a5a55',
                  fontFamily: 'inherit', cursor: 'pointer',
                  letterSpacing: '-0.02em',
                  transition: 'color 200ms',
                  WebkitTapHighlightColor: 'transparent',
                  whiteSpace: 'nowrap',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
                }}
              >
                <span className="category-icon" style={{ fontSize: 14 }}>{g.icon}</span>
                <span>{g.short}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* body */}
      <div style={{ flex: 1, overflow: 'auto' }}>
        {isFree
          ? <EtcScreen group={cur} mode={etcMode} text={etcText} onMode={onEtcMode} onText={onEtcText} onSaveMemo={onSaveMemo} onAllGoodCategory={onAllGoodCategory} theme={t} />
          : <CategoryListScreen group={cur} values={values} onPick={onPickCategory} onAllGoodCategory={onAllGoodCategory} onSaveMemo={onSaveMemo} theme={t} />
        }
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────
// CategoryListScreen — 설비군 리스트 (한 그룹)
// ──────────────────────────────────────────────
function CategoryListScreen({ group, values, onPick, onAllGoodCategory, onSaveMemo, theme }) {
  const t = theme || window.THEME || { brand: '#2563eb' };
  const [mode, setMode] = React.useState(null);
  const [memoText, setMemoText] = React.useState('');

  let totalItems = 0;
  let okItems = 0;
  if (group && group.categories) {
    group.categories.forEach(c => {
      c.items.forEach(it => {
        if (values[it.id] === '/') return;
        totalItems++;
        if (values[it.id] === 'O') okItems++;
      });
    });
  }
  const isAllOk = totalItems > 0 && okItems === totalItems;

  return (
    <div style={{ padding: '14px 16px 24px' }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        marginBottom: 12,
      }}>
        <div style={{ fontSize: 14, fontWeight: 800, letterSpacing: '-0.02em' }}>
          설비군 <span style={{ color: '#8a8880', fontWeight: 600 }}>· {group.categories.length}개</span>
        </div>
        <div style={{
          fontSize: 11, color: '#8a8880', fontWeight: 600,
        }}>
          탭하여 점검 시작
        </div>
      </div>

      {/* 전체 이상없음 / 직접 입력 2버튼 이식 영역 */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
        <button
          onClick={() => {
            if (onAllGoodCategory) onAllGoodCategory(group.id);
          }}
          style={{
            background: isAllOk ? '#15803d' : '#fff',
            border: `2px solid ${isAllOk ? '#15803d' : '#bfe1ca'}`,
            borderRadius: 14, padding: '16px 12px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
            cursor: 'pointer', fontFamily: 'inherit', transition: 'all 220ms',
            boxShadow: isAllOk ? '0 8px 18px rgba(21,128,61,.25)' : '0 1px 2px rgba(0,0,0,.04)',
            WebkitTapHighlightColor: 'transparent',
          }}
        >
          <div style={{ width: 36, height: 36, borderRadius: '50%', background: isAllOk ? 'rgba(255,255,255,.18)' : '#e8f5ed', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M5 12.5l5 5 9-10" stroke={isAllOk ? '#fff' : '#15803d'} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          <div style={{ fontSize: 14, fontWeight: 800, color: isAllOk ? '#fff' : '#15803d' }}>
            {isAllOk ? '일괄 양호 해제' : '전체 이상없음'}
          </div>
        </button>

        <button
          onClick={() => setMode(mode === 'write' ? null : 'write')}
          style={{
            background: mode === 'write' ? '#1a1a18' : '#fff',
            border: `2px solid ${mode === 'write' ? '#1a1a18' : '#d4d1c7'}`,
            borderRadius: 14, padding: '16px 12px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
            cursor: 'pointer', fontFamily: 'inherit', transition: 'all 220ms',
            boxShadow: mode === 'write' ? '0 8px 18px rgba(0,0,0,.18)' : '0 1px 2px rgba(0,0,0,.04)',
            WebkitTapHighlightColor: 'transparent',
          }}
        >
          <div style={{ width: 36, height: 36, borderRadius: '50%', background: mode === 'write' ? 'rgba(255,255,255,.14)' : '#f1efea', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M14 4l6 6-10 10H4v-6l10-10z" stroke={mode === 'write' ? '#fff' : '#1a1a18'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          <div style={{ fontSize: 14, fontWeight: 800, color: mode === 'write' ? '#fff' : '#1a1a18' }}>
            직접 입력
          </div>
        </button>
      </div>

      {/* 직접 입력 (메모) 확장 영역 */}
      <div style={{ maxHeight: mode === 'write' ? 320 : 0, overflow: 'hidden', transition: 'max-height 380ms', marginBottom: mode === 'write' ? 16 : 0, opacity: mode === 'write' ? 1 : 0 }}>
        <div style={{ background: '#fff', border: '1px solid #ece9e0', borderRadius: 14, padding: 14 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: '#5a5a55', marginBottom: 8 }}>
            {group.name} 특이사항
          </div>
          <textarea
            value={memoText} onChange={e => setMemoText(e.target.value)}
            placeholder="발견된 사항을 자유롭게 기록하세요." rows={4}
            style={{ width: '100%', resize: 'vertical', padding: '10px 12px', border: '1px solid #e5e3dc', borderRadius: 10, fontSize: 13.5, fontFamily: 'inherit', background: '#fbf9f3', outline: 'none', boxSizing: 'border-box' }}
          />
          <button
            onClick={async () => {
              if (!memoText.trim()) return alert('내용을 입력하세요.');
              if (onSaveMemo) await onSaveMemo(group.id, memoText);
              setMode(null);
              setMemoText('');
            }}
            style={{ marginTop: 8, width: '100%', padding: '12px', background: t.brand, color: '#fff', border: 'none', borderRadius: 10, fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
          >저장하기</button>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {group.categories.map((c, i) => {
          const total = c.items.length;
          let done = 0, bad = 0, na = 0;
          for (const it of c.items) {
            const v = values[it.id];
            // 진짜 양호('O') 또는 진짜 불량('X')일 때만 진행 카운트에 포함
            if (v === 'O' || v === 'X') done++;
            if (v === 'X') bad++;
            if (v === '/') na++;
          }
          const effectiveTotal = total - na;
          const complete = effectiveTotal >= 0 && done >= effectiveTotal && (done > 0 || na > 0);
          const started = done > 0 || na > 0;
          const statusColor =
            !started ? '#8a8880'
            : bad ? '#cc2222'
            : complete ? '#15803d'
            : group.accent;
          const statusLabel =
            !started ? '미점검'
            : bad ? `불량 ${bad}건`
            : complete ? '완료'
            : `진행 중`;

          return (
            <button
              key={c.id}
              onClick={() => onPick(group.id, c.id)}
              style={{
                background: '#fff',
                border: `1.5px solid ${
                  bad ? '#f4b4b4'
                  : complete ? '#bfe1ca'
                  : started ? group.accent + '55'
                  : '#e5e3dc'}`,
                borderRadius: 14,
                padding: '14px 16px',
                display: 'flex', alignItems: 'center', gap: 12,
                cursor: 'pointer',
                fontFamily: 'inherit', textAlign: 'left',
                animation: `fadeUp 300ms ${i * 30}ms cubic-bezier(.4,1.2,.4,1) both`,
                WebkitTapHighlightColor: 'transparent',
                transition: 'transform 160ms, border-color 260ms',
              }}
              onMouseDown={e => (e.currentTarget.style.transform = 'scale(0.99)')}
              onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
              onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
            >
              {/* status dot */}
              <div style={{
                width: 8, height: 8, borderRadius: '50%',
                background: statusColor,
                boxShadow: `0 0 0 3px ${statusColor}22`,
                flexShrink: 0,
              }} />

              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontSize: 14.5, fontWeight: 700, color: '#1a1a18',
                  letterSpacing: '-0.01em',
                  marginBottom: 3,
                  lineHeight: 1.3,
                }}>
                  {c.name}
                </div>
                <div style={{
                  fontSize: 12, color: '#8a8880', fontWeight: 500,
                  display: 'flex', alignItems: 'center', gap: 6,
                }}>
                  <span>{total}항목</span>
                  <span style={{ color: '#d4d1c7' }}>·</span>
                  <span style={{ color: statusColor, fontWeight: 700 }}>
                    {statusLabel}
                  </span>
                </div>
              </div>

              {/* progress badge or chevron */}
              {started ? (
                <div style={{
                  fontSize: 11, fontWeight: 800,
                  color: statusColor,
                  background: statusColor + '11',
                  padding: '4px 9px', borderRadius: 99,
                  flexShrink: 0,
                }}>
                  {done}/{effectiveTotal}
                </div>
              ) : (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}>
                  <path d="M9 6l6 6-6 6" stroke="#8a8880" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────
// EtcScreen — 기타사항 (이상없음 / 직접 입력)
// ──────────────────────────────────────────────
function EtcScreen({ group, mode, text, onMode, onText, onSaveMemo, onAllGoodCategory, theme }) {
  const t = theme || window.THEME || { brand: '#2563eb' };
  return (
    <div style={{ padding: '20px 16px 24px' }}>
      <div style={{
        background: '#fff', border: '1px solid #ece9e0',
        borderRadius: 14, padding: '16px',
        marginBottom: 14,
      }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: '#1a1a18', marginBottom: 4, letterSpacing: '-0.01em' }}>
          {group.icon} 기타 점검 사항
        </div>
        <div style={{ fontSize: 12, color: '#8a8880', fontWeight: 500, lineHeight: 1.5 }}>
          위 3개 분류에 해당하지 않는 사항을 기록합니다.
          이상이 없으면 [이상없음]을 누르고, 별도 이슈가 있으면 [직접 입력]에 작성하세요.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {/* 이상없음 */}
        <button
          onClick={() => {
            const nextMode = mode === 'O' ? null : 'O';
            onMode(nextMode);
            if (onAllGoodCategory) onAllGoodCategory(group.id);
          }}
          style={{
            background: mode === 'O' ? '#15803d' : '#fff',
            border: `2px solid ${mode === 'O' ? '#15803d' : '#bfe1ca'}`,
            borderRadius: 14, padding: '22px 12px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
            cursor: 'pointer', fontFamily: 'inherit',
            transition: 'all 220ms cubic-bezier(.4,1.2,.4,1)',
            transform: mode === 'O' ? 'translateY(-2px)' : 'translateY(0)',
            boxShadow: mode === 'O' ? '0 8px 18px rgba(21,128,61,.25)' : '0 1px 2px rgba(0,0,0,.04)',
            WebkitTapHighlightColor: 'transparent',
          }}
        >
          <div style={{
            width: 44, height: 44, borderRadius: '50%',
            background: mode === 'O' ? 'rgba(255,255,255,.18)' : '#e8f5ed',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <path d="M5 12.5l5 5 9-10" stroke={mode === 'O' ? '#fff' : '#15803d'} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div style={{
            fontSize: 15, fontWeight: 800, letterSpacing: '-0.01em',
            color: mode === 'O' ? '#fff' : '#15803d',
          }}>이상없음</div>
        </button>

        {/* 직접 입력 */}
        <button
          onClick={() => onMode('write')}
          style={{
            background: mode === 'write' ? '#1a1a18' : '#fff',
            border: `2px solid ${mode === 'write' ? '#1a1a18' : '#d4d1c7'}`,
            borderRadius: 14, padding: '22px 12px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
            cursor: 'pointer', fontFamily: 'inherit',
            transition: 'all 220ms cubic-bezier(.4,1.2,.4,1)',
            transform: mode === 'write' ? 'translateY(-2px)' : 'translateY(0)',
            boxShadow: mode === 'write' ? '0 8px 18px rgba(0,0,0,.18)' : '0 1px 2px rgba(0,0,0,.04)',
            WebkitTapHighlightColor: 'transparent',
          }}
        >
          <div style={{
            width: 44, height: 44, borderRadius: '50%',
            background: mode === 'write' ? 'rgba(255,255,255,.14)' : '#f1efea',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <path d="M14 4l6 6-10 10H4v-6l10-10z" stroke={mode === 'write' ? '#fff' : '#1a1a18'} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div style={{
            fontSize: 15, fontWeight: 800, letterSpacing: '-0.01em',
            color: mode === 'write' ? '#fff' : '#1a1a18',
          }}>직접 입력</div>
        </button>
      </div>

      {/* 직접 입력 모드 — textarea 펼침 */}
      <div style={{
        maxHeight: mode === 'write' ? 320 : 0,
        overflow: 'hidden',
        transition: 'max-height 380ms cubic-bezier(.4,1.2,.4,1), margin-top 380ms, opacity 280ms',
        marginTop: mode === 'write' ? 12 : 0,
        opacity: mode === 'write' ? 1 : 0,
      }}>
        <div style={{
          background: '#fff', border: '1px solid #ece9e0',
          borderRadius: 14, padding: 14,
        }}>
          <div style={{
            fontSize: 12, fontWeight: 700, color: '#5a5a55',
            marginBottom: 8,
          }}>
            특이사항
          </div>
          <textarea
            value={text || ''}
            onChange={e => onText(e.target.value)}
            placeholder="발견된 사항을 자유롭게 기록하세요. 예) 지하 1층 분전반 주변 정리 필요, 옥상 해치 잠금장치 교체 검토 등"
            rows={6}
            style={{
              width: '100%', resize: 'vertical', minHeight: 120,
              padding: '10px 12px',
              border: '1px solid #e5e3dc', borderRadius: 10,
              fontSize: 13.5, fontFamily: 'inherit',
              background: '#fbf9f3', color: '#1a1a18',
              outline: 'none', boxSizing: 'border-box',
              lineHeight: 1.55,
            }}
          />
        <button
          onClick={async () => {
            if (!text.trim()) return alert('내용을 입력하세요.');
            if (onSaveMemo) await onSaveMemo(group.id, text);
            onMode(null);
            onText('');
          }}
          style={{ marginTop: 8, width: '100%', padding: '12px', background: t.brand, color: '#fff', border: 'none', borderRadius: 10, fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
        >저장하기</button>

          <div style={{
            marginTop: 8, fontSize: 11, color: '#8a8880', fontWeight: 500,
            textAlign: 'right',
          }}>
            {(text || '').length}자 · 자동 저장됨
          </div>
        </div>
      </div>

      {/* 이상없음 확인 */}
      {mode === 'O' && (
        <div style={{
          marginTop: 12,
          background: '#e8f5ed',
          border: '1px solid #bfe1ca',
          borderRadius: 12, padding: '12px 14px',
          fontSize: 12.5, color: '#15803d', fontWeight: 600,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="10" stroke="#15803d" strokeWidth="2"/>
            <path d="M8 12.5l3 3 5-7" stroke="#15803d" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          이상없음으로 기록되었습니다.
        </div>
      )}
    </div>
  );
}

window.BigYellowButton = BigYellowButton;
window.HomeScreen = HomeScreen;
window.GroupTabsScreen = GroupTabsScreen;
window.CategoryListScreen = CategoryListScreen;
window.EtcScreen = EtcScreen;
