// 5. テーマ別フィルター・グルーピング画面
// AND/OR切替、エリア×テーマ複合フィルター、マッチ度スコアの3パターンを統合した強力版

function ScreenFilter({ theme }) {
  const s = useStore();
  const [selectedThemes, setSelectedThemes] = React.useState(['kasegu', 'blog']);
  const [selectedAreas, setSelectedAreas] = React.useState([]);
  const [mode, setMode] = React.useState('match'); // 'and' | 'or' | 'match'

  const toggleTheme = (id) => {
    setSelectedThemes(t => t.includes(id) ? t.filter(x => x !== id) : [...t, id]);
  };
  const toggleArea = (id) => {
    setSelectedAreas(a => a.includes(id) ? a.filter(x => x !== id) : [...a, id]);
  };

  // フィルタリング & スコアリング
  const scored = s.participants.map(p => {
    const themeMatches = p.themes?.filter(t => selectedThemes.includes(t)).length || 0;
    const areaMatch = selectedAreas.length === 0 || selectedAreas.includes(p.area);
    const totalMatches = themeMatches + (areaMatch && selectedAreas.length > 0 ? 1 : 0);
    const maxPossible = selectedThemes.length + (selectedAreas.length > 0 ? 1 : 0);
    const score = maxPossible > 0 ? totalMatches / maxPossible : 0;
    return { p, themeMatches, areaMatch, score };
  });

  let visible = scored;
  if (mode === 'and') {
    visible = scored.filter(({ p, areaMatch }) =>
      selectedThemes.every(t => p.themes?.includes(t)) && areaMatch);
  } else if (mode === 'or') {
    visible = scored.filter(({ themeMatches, areaMatch }) =>
      (selectedThemes.length === 0 || themeMatches > 0) && areaMatch);
  } else { // match
    visible = scored.filter(({ score }) => score > 0).sort((a, b) => b.score - a.score);
  }

  // テーマグループ毎の人数
  const groupCounts = React.useMemo(() => {
    const counts = {};
    selectedThemes.forEach(tid => {
      counts[tid] = s.participants.filter(p => p.themes?.includes(tid)).length;
    });
    return counts;
  }, [selectedThemes, s.participants]);

  return (
    <Phone theme={theme}>
      <StatusBar theme={theme} />

      {/* ヘッダー */}
      <div style={{ padding: '12px 16px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 800, fontFamily: theme.headingFont }}>
              テーマで仲間を探す
            </div>
            <div style={{ fontSize: 11, color: theme.textMuted, marginTop: 2 }}>
              気になるタグを選んで、同じ興味の人を見つけよう
            </div>
          </div>
        </div>

        {/* モード切替セグメント */}
        <div style={{
          display: 'flex', gap: 0, marginTop: 12,
          background: theme.chipBg, padding: 3, borderRadius: 99,
        }}>
          {[
            { id: 'match', label: 'マッチ度順' },
            { id: 'and', label: 'すべて含む' },
            { id: 'or', label: 'どれかを含む' },
          ].map(m => (
            <button key={m.id} onClick={() => setMode(m.id)}
              style={{
                flex: 1, padding: '7px 4px', border: 'none', cursor: 'pointer',
                borderRadius: 99, fontSize: 11.5, fontWeight: 700,
                background: mode === m.id ? theme.surface : 'transparent',
                color: mode === m.id ? theme.text : theme.textMuted,
                boxShadow: mode === m.id ? `0 1px 3px ${theme.text}10` : 'none',
                fontFamily: theme.bodyFont,
                transition: 'all .15s',
              }}>{m.label}</button>
          ))}
        </div>
      </div>

      {/* タグ選択 - 折りたたみセクション */}
      <div style={{ padding: '14px 16px 8px' }}>
        {Object.entries(INTEREST_THEMES).map(([group, items]) => (
          <div key={group} style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1,
              color: theme.textMuted, marginBottom: 6 }}>
              {group.toUpperCase()}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
              {items.map(t => (
                <Chip key={t.id} theme={theme} color={t.color} size="sm"
                  active={selectedThemes.includes(t.id)}
                  onClick={() => toggleTheme(t.id)}>
                  {t.label}
                </Chip>
              ))}
            </div>
          </div>
        ))}

        {/* エリアフィルタ */}
        <div style={{ marginBottom: 4 }}>
          <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1,
            color: theme.textMuted, marginBottom: 6 }}>
            エリア (近くの人で絞る)
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
            {['北勢', '中勢', '伊勢志摩', '伊賀', '東紀州'].map(r => {
              const areas = MIE_AREAS.filter(a => a.region === r);
              const active = areas.some(a => selectedAreas.includes(a.id));
              return (
                <Chip key={r} theme={theme} size="sm" active={active}
                  onClick={() => {
                    if (active) {
                      setSelectedAreas(sa => sa.filter(a => !areas.some(ar => ar.id === a)));
                    } else {
                      setSelectedAreas(sa => [...sa, ...areas.map(a => a.id)]);
                    }
                  }}>
                  {r}
                </Chip>
              );
            })}
          </div>
        </div>
      </div>

      {/* 選択中サマリー */}
      <div style={{
        margin: '0 16px', padding: '10px 12px',
        background: theme.primary, color: theme.primaryFg,
        borderRadius: theme.radius, marginBottom: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 11, opacity: 0.85 }}>
            {selectedThemes.length}タグ
            {selectedAreas.length > 0 && ` × ${selectedAreas.length}エリア`}
          </div>
          <div style={{ fontSize: 14, fontWeight: 700, fontFeatureSettings: '"tnum"' }}>
            <span style={{ fontFamily: theme.headingFont, fontSize: 22, fontWeight: 900 }}>
              {visible.length}
            </span>名がヒット
          </div>
        </div>
      </div>

      {/* 結果リスト (マッチ度モード) */}
      <div style={{ padding: '0 12px 12px' }}>
        {mode === 'match' && (
          <>
            <div style={{ fontSize: 11, color: theme.textMuted, padding: '0 4px 8px',
              fontWeight: 600 }}>
              マッチ度の高い順
            </div>
            {visible.slice(0, 10).map(({ p, score, themeMatches }) => (
              <MatchRow key={p.id} theme={theme} p={p} score={score} matches={themeMatches}
                selectedThemes={selectedThemes} />
            ))}
          </>
        )}

        {mode !== 'match' && (
          <>
            {/* グループ表示 */}
            {selectedThemes.length > 0 && (
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 11, color: theme.textMuted, padding: '0 4px 8px',
                  fontWeight: 600 }}>
                  選択タグの内訳
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
                  {selectedThemes.map(tid => {
                    const tag = THEME_BY_ID[tid];
                    if (!tag) return null;
                    return (
                      <div key={tid} style={{
                        padding: '10px 12px',
                        borderRadius: theme.radius,
                        background: theme.surface,
                        borderLeft: `4px solid ${tag.color}`,
                        border: `1px solid ${theme.border}`,
                      }}>
                        <div style={{ fontSize: 12, color: theme.textMuted, marginBottom: 2 }}>
                          {tag.label}
                        </div>
                        <div style={{ fontFamily: theme.headingFont, fontSize: 18, fontWeight: 900,
                          color: tag.color, fontFeatureSettings: '"tnum"' }}>
                          {groupCounts[tid]}名
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            <div style={{ fontSize: 11, color: theme.textMuted, padding: '0 4px 8px',
              fontWeight: 600 }}>
              該当する参加者
            </div>
            {visible.slice(0, 8).map(({ p }) => (
              <CompactRow key={p.id} theme={theme} p={p} />
            ))}
          </>
        )}

        {visible.length === 0 && (
          <div style={{ padding: 32, textAlign: 'center', color: theme.textMuted, fontSize: 13 }}>
            条件に合う人がいませんでした<br/>
            タグを減らすか、モードを切り替えてみてください
          </div>
        )}
      </div>
    </Phone>
  );
}

function MatchRow({ theme, p, score, matches, selectedThemes }) {
  const area = MIE_AREAS.find(a => a.id === p.area);
  const pct = Math.round(score * 100);
  return (
    <div style={{
      display: 'flex', gap: 10, padding: '10px 12px', marginBottom: 6,
      background: theme.surface, borderRadius: theme.radius,
      border: `1px solid ${theme.border}`,
      alignItems: 'center',
    }}>
      <Avatar theme={theme} name={p.name} size={36} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span style={{ fontSize: 13.5, fontWeight: 700, color: theme.text }}>{p.name}</span>
          <span style={{ fontSize: 10, color: theme.textMuted }}>{area?.label}</span>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 3, marginTop: 4 }}>
          {p.themes?.filter(t => selectedThemes.includes(t)).map(tid => {
            const tag = THEME_BY_ID[tid];
            return tag ? <Chip key={tid} theme={theme} color={tag.color} size="sm" active>{tag.label}</Chip> : null;
          })}
        </div>
      </div>
      <div style={{
        textAlign: 'center', flexShrink: 0,
        padding: '4px 8px', borderRadius: 8,
        background: pct >= 60 ? theme.primary : theme.chipBg,
        color: pct >= 60 ? theme.primaryFg : theme.text,
      }}>
        <div style={{ fontFamily: theme.headingFont, fontSize: 16, fontWeight: 900,
          fontFeatureSettings: '"tnum"', lineHeight: 1 }}>{pct}<span style={{ fontSize: 10 }}>%</span></div>
        <div style={{ fontSize: 9, opacity: 0.8, marginTop: 2 }}>マッチ</div>
      </div>
    </div>
  );
}

function CompactRow({ theme, p }) {
  const area = MIE_AREAS.find(a => a.id === p.area);
  return (
    <div style={{
      display: 'flex', gap: 8, padding: '8px 10px', marginBottom: 4,
      background: theme.surface, borderRadius: theme.radius,
      border: `1px solid ${theme.border}`, alignItems: 'center',
    }}>
      <Avatar theme={theme} name={p.name} size={26} />
      <span style={{ fontSize: 13, fontWeight: 700, color: theme.text }}>{p.name}</span>
      <span style={{ fontSize: 10, color: theme.textMuted }}>· {area?.label}</span>
      {p.count === 'first' && (
        <span style={{ fontSize: 9, padding: '1px 4px', background: theme.accent,
          color: '#fff', borderRadius: 3, fontWeight: 700, marginLeft: 'auto' }}>初</span>
      )}
    </div>
  );
}

Object.assign(window, { ScreenFilter });
