// p04-collection.jsx — Collection detail screen
// States: default / playing / empty (no seeds) / nameEdit

function ScreenCollection({ state, onNavigate, pouchId }) {
  const T = window.T;
  const pouch = window.MOCK_POUCHES.find(p => p.id === (pouchId || 'p01')) || window.MOCK_POUCHES[0];
  const seeds = state === 'empty' ? [] : pouch.seedIds.map(id => window.MOCK_SEEDS.find(s => s.id === id)).filter(Boolean);
  const [playing, setPlaying] = React.useState(state === 'playing');
  const [playIdx, setPlayIdx] = React.useState(state === 'playing' ? 0 : -1);
  const [editingName, setEditingName] = React.useState(state === 'nameEdit');
  const [name, setName] = React.useState(pouch.name);
  const [showMenu, setShowMenu] = React.useState(false);
  const [color, setColor] = React.useState(pouch.color);
  const [showColorSheet, setShowColorSheet] = React.useState(false);
  const [showDeleteAlert, setShowDeleteAlert] = React.useState(false);
  const col = T[color];
  const POUCH_COLORS = ['pouchA', 'pouchB', 'pouchC', 'pouchD', 'pouchE', 'pouchF'];

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg,
                  display: 'flex', flexDirection: 'column' }}>
      <TopBar
        leading={<IconButton icon={<Icons.Back size={22} color={T.ink}/>}
                             onClick={() => onNavigate('back')}/>}
        trailing={<IconButton icon={<Icons.More size={22} color={T.ink}/>}
                             onClick={() => setShowMenu(true)}/>}
      />

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {/* Header banner */}
        <div style={{
          margin: '4px 20px 20px',
          borderRadius: 18,
          background: `linear-gradient(135deg, ${col} 0%, ${col}CC 100%)`,
          padding: '22px 20px 20px',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', right: -20, bottom: -30,
            width: 140, height: 140, borderRadius: 70,
            background: 'rgba(255,255,255,0.18)',
          }}/>
          <div style={{ position: 'relative', zIndex: 1 }}>
            <div style={{
              fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.7)',
              letterSpacing: '0.1em', textTransform: 'uppercase',
              marginBottom: 6,
            }}>👜 주머니</div>

            {editingName ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <input value={name} onChange={e => setName(e.target.value)} autoFocus
                       style={{
                         flex: 1, background: 'rgba(255,255,255,0.95)',
                         border: 'none', borderRadius: 10,
                         padding: '10px 12px', fontSize: 20, fontWeight: 700,
                         color: T.ink, letterSpacing: '-0.02em',
                         fontFamily: 'inherit', outline: 'none',
                       }}/>
                <button onClick={() => setEditingName(false)} style={{
                  background: '#FFF', border: 'none',
                  padding: '8px 12px', borderRadius: 10,
                  fontSize: 13, fontWeight: 700, color: T.ink,
                  fontFamily: 'inherit', cursor: 'pointer',
                }}>완료</button>
              </div>
            ) : (
              <div onClick={() => setEditingName(true)} style={{
                fontSize: 26, fontWeight: 800, color: '#FFF',
                letterSpacing: '-0.03em', lineHeight: 1.1,
                cursor: 'pointer',
              }}>{name}</div>
            )}

            <div style={{
              marginTop: 12, display: 'flex', alignItems: 'center', gap: 14,
              fontSize: 12.5, color: 'rgba(255,255,255,0.85)', fontWeight: 500,
              flexWrap: 'wrap',
            }}>
              <span style={{ whiteSpace: 'nowrap' }}>{pouch.langCodes.map(c => window.MOCK_LANGS.find(l => l.code === c)?.label).join(', ')}</span>
              <span style={{ whiteSpace: 'nowrap' }}>· 씨앗 {seeds.length}개</span>
              <span style={{ whiteSpace: 'nowrap' }}>· {pouch.createdAt.replace(/-/g, '.')}</span>
            </div>
          </div>
        </div>

        <div style={{ padding: '0 20px 28px' }}>
          {/* Play button */}
          {seeds.length > 0 && (
            <button onClick={() => { setPlaying(p => !p); setPlayIdx(playing ? -1 : 0); }} style={{
              width: '100%', height: 52, borderRadius: 14,
              background: playing ? T.accent : T.ink,
              color: playing ? '#FFF' : T.onInk, border: 'none',
              fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
              letterSpacing: '-0.01em',
              cursor: 'pointer', marginBottom: 14,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              whiteSpace: 'nowrap',
            }}>
              {playing
                ? <React.Fragment><Icons.Stop size={16} color="#FFF"/> 정지 · {playIdx + 1}/{seeds.length}</React.Fragment>
                : <React.Fragment><Icons.Play size={16} color={T.onInk} fillTri/> 전체 재생</React.Fragment>}
            </button>
          )}

          {/* Seeds list */}
          {seeds.length === 0 ? (
            <EmptyState
              icon={<div style={{ width: 110, height: 75 }}><Hamster count={0} max={10} size={110}/></div>}
              title="이 주머니에 씨앗이 없어요"
              message="씨앗을 담아 시작해보세요"
              action={<Button kind="primary" onClick={() => onNavigate('P06')}
                              icon={<Icons.Plus size={16} color="#FFF"/>}>
                씨앗 담기
              </Button>}
            />
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {seeds.map((s, i) => (
                <SeedCard key={s.id} seed={s}
                  playing={playing && i === playIdx}
                  onClick={() => onNavigate('P05', { seedId: s.id })}
                  onPlay={() => {
                    if (playing && playIdx === i) { setPlaying(false); setPlayIdx(-1); }
                    else { setPlaying(true); setPlayIdx(i); }
                  }}
                  style={playing && i === playIdx ? {
                    borderColor: T.accent, boxShadow: `0 0 0 1px ${T.accent}`,
                  } : null}
                />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Action menu */}
      <BottomSheet open={showMenu} onClose={() => setShowMenu(false)}>
        <div style={{ padding: '8px 12px 28px' }}>
          <ListRow label="이름 편집"
                   leading={<Icons.Edit size={20} color={T.ink2}/>}
                   trailing={<Icons.ChevronR size={18} color={T.ink3}/>}
                   onClick={() => { setShowMenu(false); setEditingName(true); }}/>
          <ListRow label="색상 변경"
                   leading={<div style={{ width: 20, height: 20, borderRadius: 10,
                                          background: col }}/>}
                   trailing={<Icons.ChevronR size={18} color={T.ink3}/>}
                   onClick={() => { setShowMenu(false); setShowColorSheet(true); }}/>
          <ListRow label="주머니 삭제" danger
                   leading={<Icons.Trash size={20} color={T.danger}/>}
                   trailing={<Icons.ChevronR size={18} color={T.danger}/>}
                   onClick={() => { setShowMenu(false); setShowDeleteAlert(true); }}
                   last/>
        </div>
      </BottomSheet>

      {/* Color picker sheet */}
      <BottomSheet open={showColorSheet} onClose={() => setShowColorSheet(false)} title="색상 변경">
        <div style={{ padding: '6px 20px 28px' }}>
          <div style={{ fontSize: 12.5, color: T.ink2, padding: '2px 0 16px' }}>
            주머니를 대표하는 색을 골라주세요
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {POUCH_COLORS.map(c => {
              const on = color === c;
              return (
                <button key={c} onClick={() => { setColor(c); setShowColorSheet(false); }}
                        aria-label={c} style={{
                  height: 64, borderRadius: 16,
                  background: T[c], cursor: 'pointer',
                  border: on ? `3px solid ${T.ink}` : `0.5px solid ${T.hairline}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  padding: 0, fontFamily: 'inherit',
                }}>
                  {on && <Icons.Check size={22} color={T.onInk}/>}
                </button>
              );
            })}
          </div>
        </div>
      </BottomSheet>

      <AlertModal
        open={showDeleteAlert}
        title="이 주머니를 삭제할까요?"
        message="주머니는 사라지지만 담긴 씨앗은 그대로 남아요."
        confirmLabel="삭제"
        danger
        onConfirm={() => { setShowDeleteAlert(false); onNavigate('back'); }}
        onCancel={() => setShowDeleteAlert(false)}
      />
    </div>
  );
}

Object.assign(window, { ScreenCollection });
