// p03-allseeds.jsx — All seeds screen (P03)
// States: default / playing / paused / empty (no seeds yet) / filterSheet / offline
// Design unified with P02 home: filter button → modal sheet, + add button,
// player pill that splits into pause + stop when active.

function ScreenAllSeeds({ state, onNavigate, initialFilter, initialFav }) {
  const T = window.T;
  const FilterIcon = window.FilterIcon;
  const RemovableChip = window.RemovableChip;

  // "empty" preset = user has no seeds at all (truly empty collection),
  // not just an unmatched filter — that's what the dev panel button should preview.
  const isEmptyState = state === 'empty';
  const offline = state === 'offline';
  const all = isEmptyState ? [] : window.MOCK_SEEDS;
  const langs = window.MOCK_LANGS;
  const cats = window.MOCK_CATEGORIES;

  const [langFilter, setLangFilter] = React.useState(initialFilter?.lang || null);
  const [catFilter, setCatFilter] = React.useState(initialFilter?.cat || null);
  const [showFilters, setShowFilters] = React.useState(state === 'filterSheet');

  // 곳간(즐겨찾기) 필터 — "나" 탭 곳간에서 진입하면 켜진 채로 시작
  const seedFavs = useSeedFavs();
  const [favOnly, setFavOnly] = React.useState(!!initialFav);

  const [playing, setPlaying] = React.useState(state === 'playing');
  const [playIdx, setPlayIdx] = React.useState(
    state === 'playing' ? 1 :
    state === 'paused'  ? 2 :
    0
  );

  const listScrollRef = React.useRef(null);
  const itemRefs = React.useRef({});

  const filtered = all.filter(s =>
    (!langFilter || s.lang === langFilter) &&
    (!catFilter  || s.categories.includes(catFilter)) &&
    (!favOnly    || seedFavs.isFav(s.id))
  );

  // Auto-advance — same cadence as P02 home (2.4s).
  // On the last item, stop and reset to 0 (button returns to "전체 재생").
  React.useEffect(() => {
    if (!playing || filtered.length === 0) return;
    const t = setInterval(() => {
      setPlayIdx(i => {
        if (i + 1 >= filtered.length) {
          setPlaying(false);
          return 0;
        }
        return i + 1;
      });
    }, 2400);
    return () => clearInterval(t);
  }, [playing, filtered.length]);

  // Clamp playIdx when filter shrinks results
  React.useEffect(() => {
    if (playIdx >= filtered.length) {
      setPlayIdx(0);
      setPlaying(false);
    }
  }, [filtered.length]);

  // Auto-scroll the playing card into view
  React.useEffect(() => {
    if (!playing && playIdx === 0) return;
    const seed = filtered[playIdx];
    if (!seed) return;
    const el = itemRefs.current[seed.id];
    if (el && el.parentElement) {
      const scroller = listScrollRef.current;
      if (!scroller) return;
      const elTop = el.offsetTop;
      const elBottom = elTop + el.offsetHeight;
      const viewTop = scroller.scrollTop;
      const viewBottom = viewTop + scroller.clientHeight;
      if (elTop < viewTop + 80 || elBottom > viewBottom - 40) {
        scroller.scrollTo({ top: elTop - 100, behavior: 'smooth' });
      }
    }
  }, [playing, playIdx]);

  const activeFilters = [
    langFilter && langs.find(l => l.code === langFilter),
    catFilter  && cats.find(c => c.id === catFilter),
  ].filter(Boolean);
  const anyFilter = activeFilters.length > 0 || favOnly;
  const activeCount = activeFilters.length + (favOnly ? 1 : 0);

  const startPlayback = () => {
    if (!filtered.length) return;
    setPlayIdx(0);
    setPlaying(true);
  };
  const stopPlayback = () => { setPlaying(false); setPlayIdx(0); };
  const togglePause  = () => { if (filtered.length) setPlaying(p => !p); };
  const isPaused = !playing && playIdx > 0;

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg,
                  display: 'flex', flexDirection: 'column' }}>
      <TopBar title="내 씨앗"
        offline={offline}
        leading={<IconButton icon={<Icons.Back size={22} color={T.ink}/>}
                             onClick={() => onNavigate('back')}/>}/>

      <div ref={listScrollRef} style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ padding: '4px 20px 28px' }}>

          {/* Count + actions row — mirrors P02 home rhythm */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            margin: '4px 0 12px', minWidth: 0,
          }}>
            <div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                fontSize: 17, fontWeight: 700, color: T.ink,
                letterSpacing: '-0.02em', whiteSpace: 'nowrap',
              }}>
                {favOnly && <Icons.Star size={15} color={T.accent} filled/>}
                {favOnly ? '곳간' : '씨앗'}
              </span>
              {anyFilter ? (
                <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 4, fontSize: 13 }}>
                  <span style={{ color: T.ink3, fontWeight: 500 }}>{all.length}개 중</span>
                  <b style={{ color: T.accent, fontWeight: 800, fontSize: 14 }}>{filtered.length}개</b>
                </span>
              ) : (
                <span style={{ fontSize: 13, color: T.ink3, fontWeight: 500, whiteSpace: 'nowrap' }}>
                  · {all.length}개
                </span>
              )}
            </div>

            <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
              {/* Filter button — hidden when collection is truly empty */}
              {all.length > 0 && (
                <button onClick={() => setShowFilters(true)}
                        aria-label={activeCount > 0 ? `필터 ${activeCount}개 적용됨` : '필터'}
                        style={{
                  position: 'relative',
                  width: 36, height: 36, borderRadius: 12,
                  background: T.surface,
                  border: `0.5px solid ${T.hairline}`,
                  cursor: 'pointer', padding: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'inherit',
                }}>
                  <FilterIcon size={16} color={T.ink}/>
                  {activeCount > 0 && (
                    <span style={{
                      position: 'absolute', top: 7, right: 7,
                      width: 7, height: 7, borderRadius: '50%',
                      background: T.accent,
                      border: `1.5px solid ${T.surface}`,
                    }}/>
                  )}
                </button>
              )}

              {/* Add button — disabled when offline (new seeds need network) */}
              <IconButton
                icon={<Icons.Plus size={20} color={offline ? T.ink3 : T.ink}/>}
                onClick={() => !offline && onNavigate('P06')}
                disabled={offline}
                bg={T.surface}
                style={{ borderRadius: 12, width: 36, height: 36,
                         border: `0.5px solid ${T.hairline}` }}
              />

              {/* Player control — only when there's something to play */}
              {all.length > 0 && ((playing || isPaused) ? (
                <div style={{
                  display: 'inline-flex', alignItems: 'center',
                  height: 36, borderRadius: 12,
                  background: playing ? T.accent : T.surface,
                  border: playing ? 'none' : `0.5px solid ${T.hairline}`,
                  boxShadow: playing ? `0 0 0 6px ${T.accentSoft}` : 'none',
                  transition: 'box-shadow .25s, background .15s',
                  overflow: 'hidden',
                }}>
                  {/* Pause / Resume — preserves playIdx */}
                  <button onClick={togglePause} style={{
                    height: '100%', padding: '0 12px 0 11px',
                    background: 'transparent', border: 'none',
                    color: playing ? '#FFF' : T.ink,
                    fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
                    cursor: 'pointer',
                    display: 'flex', alignItems: 'center', gap: 6,
                    whiteSpace: 'nowrap', letterSpacing: '-0.01em',
                  }}>
                    {playing
                      ? <Icons.Pause size={14} color="#FFF"/>
                      : <Icons.Play size={14} color={T.ink} fillTri/>}
                    {playIdx + 1}/{filtered.length}
                  </button>

                  <div style={{
                    width: 0.5, height: 18, flexShrink: 0,
                    background: playing ? 'rgba(255,255,255,0.25)' : T.hairline,
                  }}/>

                  {/* Stop — full reset */}
                  <button onClick={stopPlayback}
                          aria-label="정지"
                          style={{
                    width: 32, height: '100%',
                    background: 'transparent', border: 'none',
                    cursor: 'pointer', padding: 0,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: 'inherit',
                  }}>
                    <Icons.Stop size={12} color={playing ? '#FFF' : T.ink2}/>
                  </button>
                </div>
              ) : (
                <button onClick={startPlayback}
                        disabled={filtered.length === 0}
                        style={{
                  height: 36, padding: '0 14px', borderRadius: 12,
                  background: T.surface,
                  border: `0.5px solid ${T.hairline}`,
                  color: T.ink,
                  fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
                  cursor: filtered.length ? 'pointer' : 'default',
                  opacity: filtered.length ? 1 : 0.4,
                  display: 'flex', alignItems: 'center', gap: 6,
                  whiteSpace: 'nowrap', letterSpacing: '-0.01em',
                }}>
                  <Icons.Play size={14} color={T.ink} fillTri/>
                  전체 재생
                </button>
              ))}
            </div>
          </div>

          {/* Active filter chips */}
          {anyFilter && (
            <div style={{
              display: 'flex', gap: 6, overflowX: 'auto', alignItems: 'center',
              marginBottom: 12, paddingBottom: 4, scrollbarWidth: 'none',
            }}>
              {favOnly && (
                <RemovableChip
                  label="곳간" icon="★"
                  onRemove={() => setFavOnly(false)}/>
              )}
              {langFilter && (
                <RemovableChip
                  label={langs.find(l => l.code === langFilter)?.label}
                  onRemove={() => setLangFilter(null)}/>
              )}
              {catFilter && (
                <RemovableChip
                  label={cats.find(c => c.id === catFilter)?.label}
                  icon={cats.find(c => c.id === catFilter)?.icon}
                  onRemove={() => setCatFilter(null)}/>
              )}
              <button onClick={() => { setLangFilter(null); setCatFilter(null); setFavOnly(false); }} style={{
                background: 'transparent', border: 'none',
                color: T.ink3, fontSize: 12, fontWeight: 600,
                padding: '0 6px', cursor: 'pointer', flexShrink: 0,
                fontFamily: 'inherit',
              }}>지우기</button>
            </div>
          )}

          {/* Seeds list */}
          {filtered.length === 0 ? (
            anyFilter ? (
              <EmptyState
                icon={<div style={{ width: 110, height: 75 }}><Hamster count={0} max={10} size={110}/></div>}
                title={favOnly && activeFilters.length === 0 ? '곳간이 아직 비어 있어요' : '조건에 맞는 씨앗이 없어요'}
                message={favOnly && activeFilters.length === 0
                  ? '씨앗 상세에서 ★을 누르면 여기 곳간에 모여요'
                  : '다른 언어나 카테고리를 골라보세요'}
                action={<Button kind="soft" size="sm"
                                onClick={() => { setLangFilter(null); setCatFilter(null); setFavOnly(false); }}>
                  필터 초기화
                </Button>}
              />
            ) : (
              <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={() => onNavigate('P06')}>
                  씨앗 담기
                </Button>}
              />
            )
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {filtered.map((s, i) => {
                const isActive = (playing || isPaused) && i === playIdx;
                return (
                  <div key={s.id} ref={el => { if (el) itemRefs.current[s.id] = el; }}>
                    <SeedCard seed={s}
                      playing={playing && i === playIdx}
                      paused={isPaused && i === playIdx}
                      onClick={() => onNavigate('P05', { seedId: s.id })}
                      onPlay={() => { setPlayIdx(i); setPlaying(true); }}
                      style={isActive ? {
                        borderColor: T.accent,
                        boxShadow: `0 0 0 1px ${T.accent}`,
                      } : null}
                    />
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* Filter sheet — reuses P02's FilterSheet for design parity */}
      <BottomSheet open={showFilters} onClose={() => setShowFilters(false)} title="필터">
        <FilterSheet
          langs={langs} cats={cats}
          langFilter={langFilter} catFilter={catFilter}
          setLang={setLangFilter} setCat={setCatFilter}
          favOnly={favOnly} setFavOnly={setFavOnly} showFav
          matchCount={filtered.length}
          onClose={() => setShowFilters(false)}
          onNavigate={onNavigate}
        />
      </BottomSheet>
    </div>
  );
}

Object.assign(window, { ScreenAllSeeds });
