// Screens2.jsx - V2 점검 화면 디자인 (Refactored to new design)

// 3지 선다형 세그먼트 버튼 폴백 (SelectorStyles.jsx가 없을 경우를 대비한 안전 장치)
function InlineSegmentSelector({ value, onChange }) {
  const STATES = [
    { key: 'O',  label: '양호',   color: '#15803d', icon: 'check' },
    { key: 'X',  label: '불량',   color: '#cc2222', icon: 'x' },
    { key: '/',  label: '해당없음', color: '#5a5a55', icon: 'dash' },
  ];
  const idx = STATES.findIndex(s => s.key === value);
  const active = STATES[idx];

  const getIcon = (kind, color) => {
    if (kind === 'check') return <path d="M5 12.5l5 5 9-10" stroke={color} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>;
    if (kind === 'x') return <path d="M6 6l12 12M18 6L6 18" stroke={color} strokeWidth="2.6" strokeLinecap="round"/>;
    return <path d="M5 12h14" stroke={color} strokeWidth="2.6" strokeLinecap="round"/>;
  };

  return (
    <div style={{
      position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
      background: '#f1efea', borderRadius: 12, padding: 4, height: 52,
      border: '1px solid #e0ddd4',
    }}>
      {idx >= 0 && (
        <div style={{
          position: 'absolute', top: 4, left: `calc(${idx} * (100% - 8px) / 3 + 4px)`,
          width: 'calc((100% - 8px) / 3)', height: 44, background: '#fff',
          border: `2px solid ${active.color}`, borderRadius: 9,
          transition: 'left 260ms cubic-bezier(.5,1.4,.5,1), border-color 180ms',
          boxShadow: `0 2px 8px ${active.color}22, 0 1px 2px rgba(0,0,0,.04)`,
        }} />
      )}
      {STATES.map(s => {
        const selected = s.key === value;
        return (
          <button
            key={s.key}
            onClick={() => onChange(s.key)}
            style={{
              position: 'relative', zIndex: 1, background: 'transparent', border: 'none',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
              color: selected ? s.color : '#5a5a55', fontWeight: selected ? 700 : 500,
              fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit',
              transition: 'color 180ms', WebkitTapHighlightColor: 'transparent',
              letterSpacing: '-0.02em',
            }}
          >
            <span style={{
              transform: selected ? 'scale(1)' : 'scale(0.85)',
              opacity: selected ? 1 : 0.55,
              transition: 'transform 220ms cubic-bezier(.5,1.6,.5,1), opacity 180ms',
              display: 'inline-flex',
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                {getIcon(s.icon, selected ? s.color : '#8a8880')}
              </svg>
            </span>
            {s.label}
          </button>
        );
      })}
    </div>
  );
}

function ItemsScreen({ groupId, categoryId, values, onChange, onAllGood, selectorStyle, theme, groups: propGroups }) {
  const t = theme || window.THEME || { brand: '#2563eb' };
  const groups = propGroups || window.INSPECTION_GROUPS || [];
  const grp = groups.find(g => g.id === groupId);
  const cat = grp && grp.categories.find(c => c.id === categoryId);

  if (!cat) return <div style={{ padding: 20 }}>데이터를 불러올 수 없습니다.</div>;

  // 컴포넌트 스타일 선택 (디자인 시스템 연동)
  const Selector = (window.SelectorSegment && !selectorStyle) ? window.SelectorSegment
                 : selectorStyle === 'cards' && window.SelectorCards ? window.SelectorCards
                 : selectorStyle === 'chips' && window.SelectorChips ? window.SelectorChips
                 : window.SelectorSegment || InlineSegmentSelector;

  const naItems = cat.items.filter(it => values[it.id] === '/');
  const visibleItems = cat.items.filter(it => values[it.id] !== '/');
  const effectiveTotal = cat.items.length - naItems.length; // 해당없음 제외한 실제 점검 대상
  const done = cat.items.filter(it => values[it.id] === 'O' || values[it.id] === 'X').length;
  const total = cat.items.length;
  const badCount = cat.items.filter(it => values[it.id] === 'X').length;
  const progressPct = effectiveTotal ? (done / effectiveTotal) * 100 : 100;
  const isAllOk = effectiveTotal > 0 && done === effectiveTotal && badCount === 0;
  const isAllDone = effectiveTotal === 0 || done === effectiveTotal; // 저장버튼 활성화용

  return (
    <div style={{ padding: '14px 16px 80px' }}>
      {/* Sticky progress summary */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 5,
        background: '#fbf9f3', paddingTop: 4, paddingBottom: 10,
        marginTop: -4, marginLeft: -16, marginRight: -16,
        paddingLeft: 16, paddingRight: 16,
        borderBottom: '1px solid #ece9e0',
      }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10, marginBottom: 6 }}>
          <div style={{
            fontSize: 15, fontWeight: 800, letterSpacing: '-0.01em',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            minWidth: 0, flex: 1,
          }}>
            {cat.name}
          </div>
          <div style={{ fontSize: 12, color: '#8a8880', fontWeight: 700, whiteSpace: 'nowrap', flexShrink: 0 }}>
            {done}/{effectiveTotal}{badCount > 0 ? ` · 불량 ${badCount}` : ''}{naItems.length > 0 ? ` · 해당없음 ${naItems.length}` : ''}
          </div>
        </div>
        <div style={{ height: 4, background: '#ece9e0', borderRadius: 99, overflow: 'hidden' }}>
          <div style={{
            height: '100%', width: `${progressPct}%`,
            background: grp.accent || t.brand,
            borderRadius: 99,
            transition: 'width 420ms cubic-bezier(.4,1.2,.4,1), background 360ms',
          }} />
        </div>

        <button
          onClick={onAllGood}
          style={{
            marginTop: 10, width: '100%', padding: '10px',
            background: isAllOk ? '#15803d' : '#fff',
            border: '1.5px solid #15803d',
            borderRadius: 10, color: isAllOk ? '#fff' : '#15803d',
            fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
            cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            WebkitTapHighlightColor: 'transparent',
          }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <path d="M5 12.5l5 5 9-10" stroke={isAllOk ? '#fff' : '#15803d'} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          {isAllOk ? '일괄 양호 해제' : '전체 양호로 일괄 설정'}
        </button>
      </div>

      <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {visibleItems.map((it, i) => {
          const v = values[it.id];
          const bad = v === 'X';
          const ok = v === 'O';
          const na = v === '/';

          return (
            <div key={it.id} style={{
              background: '#fff',
              // '/' 이거나 미점검(null)일 경우 기본 배경색(#e5e3dc) 적용
              border: `1.5px solid ${bad ? '#cc2222' : ok ? '#c9e7d3' : '#e5e3dc'}`,
              borderRadius: 14, padding: '14px',
              animation: `fadeUp 300ms ${i * 25}ms cubic-bezier(.4,1.2,.4,1) both`,
              transition: 'border-color 260ms',
            }}>
              <div style={{
                display: 'flex', alignItems: 'flex-start', gap: 10,
                marginBottom: 12,
              }}>
                <div style={{
                  flexShrink: 0,
                  width: 22, height: 22, borderRadius: 6,
                  background: '#f1efea',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 800, color: '#5a5a55',
                }}>
                  {i + 1}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontSize: 14, fontWeight: 600, color: '#1a1a18',
                    lineHeight: 1.45, letterSpacing: '-0.01em',
                  }}>
                    {it.text}
                  </div>
                  {it.sub && (
                    <div style={{
                      fontSize: 12, color: '#8a8880', fontWeight: 500,
                      lineHeight: 1.4, marginTop: 4,
                    }}>
                      {it.sub}
                    </div>
                  )}
                </div>
              </div>

              <Selector value={v} onChange={nv => onChange(it.id, nv)} />
            </div>
          );
        })}
      </div>

      {/* 해당없음 항목 복구 섹션 */}
      {naItems.length > 0 && (
        <div style={{ marginTop: 20 }}>
          <div style={{
            fontSize: 12, fontWeight: 700, color: '#8a8880',
            letterSpacing: '-0.01em', marginBottom: 8,
            paddingLeft: 2,
          }}>
            해당없음 처리된 항목 ({naItems.length}개)
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {naItems.map((it, i) => (
              <div key={it.id} style={{
                background: '#f7f6f2',
                border: '1.5px solid #e0ddd4',
                borderRadius: 12, padding: '12px 14px',
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <div style={{
                  flex: 1, fontSize: 13, color: '#8a8880',
                  fontWeight: 500, lineHeight: 1.4,
                  textDecoration: 'line-through',
                }}>
                  {it.text}
                </div>
                <button
                  onClick={() => onChange(it.id, '')}
                  style={{
                    flexShrink: 0,
                    background: '#fff', border: '1.5px solid #ece9e0',
                    borderRadius: 8, padding: '6px 12px',
                    fontSize: 12, fontWeight: 700, color: '#5a5a55',
                    cursor: 'pointer', fontFamily: 'inherit',
                    WebkitTapHighlightColor: 'transparent',
                    display: 'flex', alignItems: 'center', gap: 4,
                  }}
                >
                  ↩ 복구
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.InlineSegmentSelector = InlineSegmentSelector;
window.ItemsScreen = ItemsScreen;