// 3. 主催者ダッシュボード — 集計結果の可視化

function ScreenDashboard({ theme }) {
  const s = useStore();
  const ps = s.participants;

  // 集計
  const total = ps.length;
  const byArea = MIE_AREAS.map(a => ({
    ...a,
    count: ps.filter(p => p.area === a.id).length,
  })).sort((a, b) => b.count - a.count);
  const byTheme = ALL_THEMES_FLAT.map(t => ({
    ...t,
    count: ps.filter(p => p.themes?.includes(t.id)).length,
  })).sort((a, b) => b.count - a.count);
  const firstCount = ps.filter(p => p.count === 'first').length;
  const byAge = AGE_RANGES.map(a => ({
    label: a, count: ps.filter(p => p.age === a).length,
  }));

  const maxAreaCount = Math.max(...byArea.map(a => a.count), 1);
  const maxThemeCount = Math.max(...byTheme.map(t => t.count), 1);

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

      {/* ヘッダー */}
      <div style={{
        padding: '14px 20px',
        background: theme.text, color: theme.surface,
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 6, height: 6, borderRadius: '50%', background: theme.accent,
            boxShadow: `0 0 10px ${theme.accent}`,
          }}></div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.5, opacity: 0.7 }}>
            ORGANIZER DASHBOARD
          </div>
        </div>
        <div style={{ fontSize: 18, fontWeight: 800, marginTop: 4, fontFamily: theme.headingFont }}>
          集計結果
        </div>
        <div style={{ fontSize: 11, opacity: 0.55, marginTop: 2 }}>
          更新: 2026.05.13 10:08
        </div>
      </div>

      <div style={{ padding: '16px' }}>
        {/* KPI */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 16 }}>
          <KpiCard theme={theme} label="回答者数" value={total} unit="名"
            sub={`/ 目標 200`} accent />
          <KpiCard theme={theme} label="初参加" value={firstCount} unit="名"
            sub={`${Math.round(firstCount / total * 100)}%`} />
          <KpiCard theme={theme} label="エリア" value={byArea.filter(a => a.count > 0).length} unit="箇所"
            sub="網羅" />
        </div>

        {/* エリア別 */}
        <Card theme={theme} style={{ marginBottom: 16 }}>
          <SectionTitle theme={theme} kicker="AREA">エリア別 参加者</SectionTitle>
          {byArea.filter(a => a.count > 0).slice(0, 8).map(a => (
            <BarRow key={a.id} theme={theme} label={a.label}
              value={a.count} max={maxAreaCount}
              color={a.region === '北勢' ? theme.primary : a.region === '中勢' ? theme.accent :
                a.region === '伊勢志摩' ? theme.success : theme.textMuted} />
          ))}
          {/* 凡例 */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 12, paddingTop: 12,
            borderTop: `1px dashed ${theme.border}` }}>
            {['北勢', '中勢', '伊勢志摩', '伊賀', '東紀州'].map((r, i) => {
              const c = [theme.primary, theme.accent, theme.success, theme.textMuted, theme.textMuted][i];
              return (
                <div key={r} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: theme.textMuted }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: c }}></span>
                  {r}
                </div>
              );
            })}
          </div>
        </Card>

        {/* テーマ別 */}
        <Card theme={theme} style={{ marginBottom: 16 }}>
          <SectionTitle theme={theme} kicker="INTEREST">人気テーマ TOP 10</SectionTitle>
          {byTheme.slice(0, 10).map((t, i) => (
            <div key={t.id} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '8px 0', borderBottom: i < 9 ? `1px solid ${theme.border}` : 'none',
            }}>
              <span style={{
                width: 18, height: 18, borderRadius: 4,
                background: t.color, opacity: 0.85,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 9, color: '#fff', fontWeight: 800,
                fontFeatureSettings: '"tnum"',
              }}>{i + 1}</span>
              <span style={{ flex: 1, fontSize: 13, fontWeight: 600, color: theme.text }}>{t.label}</span>
              <div style={{ flex: '0 0 80px', height: 6, background: theme.chipBg, borderRadius: 99 }}>
                <div style={{
                  width: `${t.count / maxThemeCount * 100}%`,
                  height: '100%', background: t.color, borderRadius: 99, opacity: 0.85,
                }}></div>
              </div>
              <span style={{ fontSize: 12, color: theme.textMuted, minWidth: 30, textAlign: 'right',
                fontFeatureSettings: '"tnum"' }}>{t.count}</span>
            </div>
          ))}
        </Card>

        {/* 年代分布 */}
        <Card theme={theme} style={{ marginBottom: 16 }}>
          <SectionTitle theme={theme} kicker="AGE">年代分布</SectionTitle>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 100,
            paddingBottom: 24, position: 'relative' }}>
            {byAge.map(a => {
              const max = Math.max(...byAge.map(x => x.count), 1);
              const h = a.count / max * 80;
              return (
                <div key={a.label} style={{ flex: 1, textAlign: 'center', position: 'relative', height: '100%' }}>
                  <div style={{ position: 'absolute', bottom: 24, left: 0, right: 0,
                    height: h, background: theme.primary, borderRadius: '4px 4px 0 0',
                    transition: 'height .3s',
                  }}>
                    <div style={{ position: 'absolute', top: -16, left: 0, right: 0, fontSize: 10,
                      fontWeight: 700, color: theme.text }}>{a.count}</div>
                  </div>
                  <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, fontSize: 10,
                    color: theme.textMuted }}>{a.label}</div>
                </div>
              );
            })}
          </div>
        </Card>

        {/* 最近の行動 - ワードクラウド風 */}
        <Card theme={theme}>
          <SectionTitle theme={theme} kicker="ACTIONS">最近やった小さい行動</SectionTitle>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
            {['NISA', '副業開始', 'サブスク解約', '家計簿', 'ウォーキング',
              'ふるさと納税', 'iDeCo', 'ブログ投稿', '読書', 'メルカリ',
              'スクワット', 'AI学習', 'プログラミング'].map((w, i) => {
                const sizes = [13, 11, 17, 12, 15, 11, 14, 12, 16, 13, 11, 14, 12];
                return (
                  <span key={w} style={{
                    fontSize: sizes[i], fontWeight: 700,
                    color: i % 3 === 0 ? theme.primary : i % 3 === 1 ? theme.accent : theme.textMuted,
                    padding: '2px 4px',
                  }}>{w}</span>
                );
              })}
          </div>
        </Card>
      </div>
    </Phone>
  );
}

function KpiCard({ theme, label, value, unit, sub, accent }) {
  return (
    <div style={{
      padding: '12px 10px',
      background: accent ? theme.primary : theme.surface,
      color: accent ? theme.primaryFg : theme.text,
      borderRadius: theme.radius,
      border: accent ? 'none' : `1px solid ${theme.border}`,
    }}>
      <div style={{ fontSize: 10, fontWeight: 700, opacity: accent ? 0.8 : 1,
        color: accent ? theme.primaryFg : theme.textMuted, marginBottom: 4 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 2 }}>
        <span style={{ fontFamily: theme.headingFont, fontSize: 22, fontWeight: 900,
          fontFeatureSettings: '"tnum"' }}>{value}</span>
        <span style={{ fontSize: 11, opacity: 0.7 }}>{unit}</span>
      </div>
      {sub && (
        <div style={{ fontSize: 10, opacity: accent ? 0.7 : 1,
          color: accent ? theme.primaryFg : theme.textSub, marginTop: 2,
          fontFeatureSettings: '"tnum"' }}>{sub}</div>
      )}
    </div>
  );
}

Object.assign(window, { ScreenDashboard });
