// p04a-allpouches.jsx — All pouches index (P04a)
// Mirrors P03 (전체 씨앗) pattern: filter chips + sort + count + grid.
// States: default / empty (no filter match) / offline

function ScreenAllPouches({ state, onNavigate, initialFilter }) {
  const T = window.T;
  const offline = state === 'offline';
  // Preset for the "empty" dev state — picks a lang with zero matches
  const presetLang =
    state === 'empty' ? 'vi' : (initialFilter?.lang || null);

  const [langFilter, setLangFilter] = React.useState(presetLang);
  const [sort, setSort] = React.useState('recent'); // recent | name | seeds
  const [playingPouchId, setPlayingPouchId] = React.useState(null);
  const [playingPouchIdx, setPlayingPouchIdx] = React.useState(0);

  const all = window.MOCK_POUCHES;
  const langs = window.MOCK_LANGS;

  // Auto-advance playing pouch through its seeds; stop after the last.
  const playingPouchTotal = (all.find(p => p.id === playingPouchId)?.seedIds.length) || 0;
  React.useEffect(() => {
    if (!playingPouchId || playingPouchTotal === 0) return;
    const t = setInterval(() => {
      setPlayingPouchIdx(i => {
        if (i + 1 >= playingPouchTotal) {
          setPlayingPouchId(null);
          return 0;
        }
        return i + 1;
      });
    }, 2400);
    return () => clearInterval(t);
  }, [playingPouchId, playingPouchTotal]);

  const filtered = state === 'empty'
    ? []
    : all.filter(p => !langFilter || (p.langCodes || []).includes(langFilter));

  const sorted = React.useMemo(() => {
    const arr = [...filtered];
    if (sort === 'name')   arr.sort((a, b) => a.name.localeCompare(b.name, 'ko'));
    if (sort === 'seeds')  arr.sort((a, b) => b.seedIds.length - a.seedIds.length);
    if (sort === 'recent') arr.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
    return arr;
  }, [filtered, sort]);

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg,
                  display: 'flex', flexDirection: 'column' }}>
      <TopBar title="내 주머니"
        leading={<IconButton icon={<Icons.Back size={22} color={T.ink}/>}
                             onClick={() => onNavigate('back')}/>}
        trailing={
          <IconButton icon={<Icons.Plus size={22} color={offline ? T.ink3 : T.ink}/>}
                      onClick={() => !offline && onNavigate('P08')}
                      disabled={offline}/>
        }/>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ padding: '4px 20px 24px' }}>
          {/* Language filter chips */}
          <div style={{
            display: 'flex', gap: 6, overflowX: 'auto',
            marginBottom: 14, scrollbarWidth: 'none',
          }}>
            <Chip active={!langFilter} onClick={() => setLangFilter(null)}>전체</Chip>
            {langs.map(l => {
              const n = all.filter(p => (p.langCodes || []).includes(l.code)).length;
              if (n === 0) return null; // hide langs with no pouches
              return (
                <Chip key={l.code} active={langFilter === l.code}
                      onClick={() => setLangFilter(langFilter === l.code ? null : l.code)}>
                  {l.label}
                </Chip>
              );
            })}
          </div>

          {/* Count + sort row */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            margin: '0 0 14px',
          }}>
            <div style={{ fontSize: 13.5, color: T.ink2,
                          whiteSpace: 'nowrap', flexShrink: 0 }}>
              {langFilter ? (
                <React.Fragment>
                  <span style={{ color: T.ink3, fontWeight: 500 }}>{all.length}개 중 </span>
                  <b style={{ color: T.accent, fontSize: 15 }}>{sorted.length}개</b>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <b style={{ color: T.ink, fontSize: 15, marginRight: 4 }}>{sorted.length}</b>
                  개의 주머니
                </React.Fragment>
              )}
            </div>
            <div style={{ flex: 1 }}/>
            <Segment
              options={[
                { value: 'recent', label: '최근' },
                { value: 'name',   label: '이름' },
                { value: 'seeds',  label: '씨앗순' },
              ]}
              value={sort}
              onChange={setSort}
            />
          </div>

          {/* Grid / Empty */}
          {sorted.length === 0 ? (
            <EmptyState
              icon={<div style={{ width: 110, height: 75 }}><Hamster count={0} max={10} size={110}/></div>}
              title="조건에 맞는 주머니가 없어요"
              message="다른 언어를 골라보거나 새 주머니를 만들어보세요"
              action={
                <Button kind="primary"
                        icon={<Icons.Plus size={16} color="#FFF"/>}
                        onClick={() => !offline && onNavigate('P08')}
                        disabled={offline}>
                  새 주머니
                </Button>
              }
            />
          ) : (
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10,
            }}>
              {sorted.map(p => (
                <PouchCard key={p.id} pouch={p}
                           playing={playingPouchId === p.id}
                           playIdx={playingPouchId === p.id ? playingPouchIdx : 0}
                           onClick={() => onNavigate('P04', { pouchId: p.id })}
                           onPlay={() => { setPlayingPouchIdx(0); setPlayingPouchId(p.id); }}
                           onStop={() => { setPlayingPouchId(null); setPlayingPouchIdx(0); }}/>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenAllPouches });
