// 7. デスクトップ版ダッシュボード - 主催者用ワイド画面

function ScreenDashboardDesktop({ 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 repeatCount = ps.filter(p => p.count === 'second').length;
  const byAge = AGE_RANGES.map(a => ({
    label: a, count: ps.filter(p => p.age === a).length,
  }));
  const byRegion = ['北勢', '中勢', '伊勢志摩', '伊賀', '東紀州', '県外'].map(r => ({
    label: r, count: ps.filter(p => MIE_AREAS.find(a => a.id === p.area)?.region === r).length,
  }));

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

  return (
    <div style={{
      width: '100%', height: '100%',
      background: theme.bg, color: theme.text,
      fontFamily: theme.bodyFont, overflow: 'auto',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* ヘッダー */}
      <div style={{
        padding: '20px 32px',
        background: theme.text, color: theme.surface,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <BrandMark theme={theme} size="md" />
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 2, opacity: 0.55 }}>
              ORGANIZER DASHBOARD
            </div>
            <div style={{ fontSize: 22, fontWeight: 800, fontFamily: theme.headingFont, marginTop: 2 }}>
              三重オフ会 集計結果
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10, opacity: 0.55, letterSpacing: 1 }}>EVENT DATE</div>
            <div style={{ fontSize: 13, fontWeight: 700 }}>2026.08.11 (火・祝)</div>
          </div>
          <div style={{ width: 1, height: 32, background: 'rgba(255,255,255,0.15)' }}></div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10, opacity: 0.55, letterSpacing: 1 }}>LAST UPDATE</div>
            <div style={{ fontSize: 13, fontWeight: 700, fontFeatureSettings: '"tnum"' }}>2026.05.13 10:08</div>
          </div>
          <Btn theme={theme} size="sm" style={{ background: theme.accent, color: '#fff', marginLeft: 8 }}>
            CSV 出力
          </Btn>
        </div>
      </div>

      {/* KPIストリップ */}
      <div style={{
        padding: '20px 32px',
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16,
        background: theme.surface, borderBottom: `1px solid ${theme.border}`,
      }}>
        <BigKpi theme={theme} kicker="回答者数" value={total} unit="名" subtitle="目標 200名"
          progress={total / 200} accent />
        <BigKpi theme={theme} kicker="初参加" value={firstCount} unit="名"
          subtitle={`${Math.round(firstCount / total * 100)}% / 重点的にもてなす対象`} />
        <BigKpi theme={theme} kicker="リピーター" value={repeatCount} unit="名"
          subtitle={`${Math.round(repeatCount / total * 100)}% / 場づくりの担い手`} />
        <BigKpi theme={theme} kicker="カバーエリア" value={byArea.filter(a => a.count > 0).length}
          unit="/ 10" subtitle="県内をくまなく" />
      </div>

      {/* メイングリッド */}
      <div style={{
        padding: 24, gap: 16, flex: 1,
        display: 'grid',
        gridTemplateColumns: '1.4fr 1fr 1fr',
        gridTemplateRows: 'auto auto',
      }}>
        {/* エリア分布 (大) */}
        <Card theme={theme} style={{ gridRow: '1 / 3' }}>
          <SectionTitle theme={theme} kicker="AREA">エリア別 参加者分布</SectionTitle>

          {/* 三重マップ風 */}
          <MieMap theme={theme} byRegion={byRegion} />

          <div style={{ marginTop: 16 }}>
            {byArea.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 : a.region === '伊賀' ? '#7b6dbd' :
                  a.region === '東紀州' ? '#c87a3e' : theme.textMuted}
                sublabel={a.count > 0 ? `${a.count}名 · ${a.region}` : '0名'} />
            ))}
          </div>
        </Card>

        {/* テーマTOP10 */}
        <Card theme={theme} style={{ gridColumn: '2 / 4' }}>
          <SectionTitle theme={theme} kicker="INTEREST">人気テーマ TOP10</SectionTitle>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 24px' }}>
            {byTheme.slice(0, 10).map((t, i) => (
              <div key={t.id} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '6px 0', borderBottom: `1px solid ${theme.border}`,
              }}>
                <span style={{
                  width: 22, height: 22, borderRadius: 4,
                  background: t.color, color: '#fff',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10, fontWeight: 800, fontFeatureSettings: '"tnum"',
                }}>{i + 1}</span>
                <span style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{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,
                  }}></div>
                </div>
                <span style={{ fontSize: 12, color: theme.textMuted, minWidth: 28, textAlign: 'right',
                  fontFeatureSettings: '"tnum"' }}>{t.count}</span>
              </div>
            ))}
          </div>
        </Card>

        {/* 年代分布 */}
        <Card theme={theme}>
          <SectionTitle theme={theme} kicker="AGE">年代分布</SectionTitle>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 140,
            paddingBottom: 28, position: 'relative' }}>
            {byAge.map(a => {
              const h = a.count / maxAgeCount * 110;
              return (
                <div key={a.label} style={{ flex: 1, textAlign: 'center', position: 'relative', height: '100%' }}>
                  <div style={{ position: 'absolute', bottom: 28, left: 0, right: 0,
                    height: h, background: theme.primary, borderRadius: '4px 4px 0 0',
                    display: 'flex', flexDirection: 'column', justifyContent: 'flex-start',
                    color: '#fff', fontSize: 11, fontWeight: 700, paddingTop: 4,
                  }}>{a.count > 0 ? a.count : ''}</div>
                  <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, fontSize: 11,
                    color: theme.textMuted }}>{a.label}</div>
                </div>
              );
            })}
          </div>
        </Card>

        {/* 初参加 vs リピーター ドーナツ */}
        <Card theme={theme}>
          <SectionTitle theme={theme} kicker="ATTENDANCE">参加経験</SectionTitle>
          <DonutChart theme={theme}
            slices={[
              { label: '初参加', value: firstCount, color: theme.accent },
              { label: '2回目以降', value: repeatCount, color: theme.primary },
            ]} />
        </Card>

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

        {/* 直近回答 */}
        <Card theme={theme} style={{ gridColumn: '2 / 4' }}>
          <SectionTitle theme={theme} kicker="LATEST">直近の回答 (新着順)</SectionTitle>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {ps.slice(0, 6).map(p => {
              const area = MIE_AREAS.find(a => a.id === p.area);
              return (
                <div key={p.id} style={{
                  display: 'flex', gap: 10, padding: '8px 10px',
                  background: theme.surfaceAlt, borderRadius: theme.radius,
                  alignItems: 'center',
                }}>
                  <Avatar theme={theme} name={p.name} size={32} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 700 }}>
                      {p.name} <span style={{ fontSize: 10, color: theme.textMuted, fontWeight: 400 }}>
                        · {area?.label}
                      </span>
                    </div>
                    <div style={{ fontSize: 10.5, color: theme.textMuted,
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {p.action}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

// 大きいKPIブロック
function BigKpi({ theme, kicker, value, unit, subtitle, progress, accent }) {
  return (
    <div style={{
      padding: 16,
      background: accent ? theme.primary : theme.surfaceAlt,
      color: accent ? theme.primaryFg : theme.text,
      borderRadius: theme.radius,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.5,
        color: accent ? theme.primaryFg : theme.textMuted, marginBottom: 6, opacity: accent ? 0.8 : 1 }}>
        {kicker}
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span style={{ fontFamily: theme.headingFont, fontSize: 34, fontWeight: 900,
          fontFeatureSettings: '"tnum"', lineHeight: 1 }}>{value}</span>
        <span style={{ fontSize: 13, opacity: 0.7 }}>{unit}</span>
      </div>
      <div style={{ fontSize: 10.5, marginTop: 6,
        color: accent ? theme.primaryFg : theme.textMuted, opacity: accent ? 0.75 : 1 }}>{subtitle}</div>
      {progress != null && (
        <div style={{ marginTop: 8, height: 4,
          background: accent ? 'rgba(255,255,255,0.25)' : theme.chipBg, borderRadius: 99 }}>
          <div style={{ width: `${Math.min(100, progress * 100)}%`, height: '100%',
            background: accent ? '#fff' : theme.primary, borderRadius: 99 }}></div>
        </div>
      )}
    </div>
  );
}

// 三重県マップ風 (シンプルな図形)
function MieMap({ theme, byRegion }) {
  const regionMax = Math.max(...byRegion.map(r => r.count), 1);
  // 三重県を上から下に縦長の地域配置
  const regions = [
    { id: '北勢', x: 30, y: 12, w: 90, h: 50 },
    { id: '伊賀', x: 6, y: 60, w: 50, h: 38 },
    { id: '中勢', x: 60, y: 64, w: 70, h: 38 },
    { id: '伊勢志摩', x: 90, y: 104, w: 50, h: 40 },
    { id: '東紀州', x: 60, y: 146, w: 50, h: 60 },
  ];
  return (
    <div style={{
      padding: 16, background: theme.surfaceAlt,
      borderRadius: theme.radius, marginBottom: 12,
      display: 'flex', gap: 16, alignItems: 'center',
    }}>
      <svg width="160" height="220" viewBox="0 0 160 220">
        {regions.map(r => {
          const data = byRegion.find(b => b.label === r.id);
          const intensity = data ? data.count / regionMax : 0;
          return (
            <g key={r.id}>
              <rect x={r.x} y={r.y} width={r.w} height={r.h}
                rx={6}
                fill={theme.primary}
                fillOpacity={0.15 + intensity * 0.7}
                stroke={theme.primary} strokeOpacity={0.4} strokeWidth={1} />
              <text x={r.x + r.w / 2} y={r.y + r.h / 2 - 2}
                textAnchor="middle" fontSize="9" fontWeight="700"
                fill={theme.text} fontFamily={theme.bodyFont}>
                {r.id}
              </text>
              <text x={r.x + r.w / 2} y={r.y + r.h / 2 + 10}
                textAnchor="middle" fontSize="11" fontWeight="900"
                fill={theme.primary} fontFamily={theme.headingFont}>
                {data?.count || 0}
              </text>
            </g>
          );
        })}
      </svg>
      <div style={{ flex: 1, fontSize: 11, color: theme.textMuted, lineHeight: 1.7 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: theme.text, marginBottom: 4 }}>
          三重県カバレッジ
        </div>
        北から南まで{byRegion.filter(r => r.count > 0).length}地域から参加。
        色が濃いほど参加者多数。<br/><br/>
        最多: <strong style={{ color: theme.primary }}>
          {[...byRegion].sort((a, b) => b.count - a.count)[0]?.label}
        </strong>
      </div>
    </div>
  );
}

// ドーナツチャート
function DonutChart({ theme, slices }) {
  const total = slices.reduce((s, x) => s + x.value, 0);
  if (total === 0) return null;
  const C = 100; // center
  const R = 60;
  const RIn = 38;
  let acc = 0;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 8 }}>
      <svg width="160" height="160" viewBox="0 0 200 200">
        {slices.map((sl, i) => {
          const start = acc / total * Math.PI * 2 - Math.PI / 2;
          acc += sl.value;
          const end = acc / total * Math.PI * 2 - Math.PI / 2;
          const x1 = C + R * Math.cos(start);
          const y1 = C + R * Math.sin(start);
          const x2 = C + R * Math.cos(end);
          const y2 = C + R * Math.sin(end);
          const x3 = C + RIn * Math.cos(end);
          const y3 = C + RIn * Math.sin(end);
          const x4 = C + RIn * Math.cos(start);
          const y4 = C + RIn * Math.sin(start);
          const large = end - start > Math.PI ? 1 : 0;
          return (
            <path key={i}
              d={`M${x1} ${y1} A${R} ${R} 0 ${large} 1 ${x2} ${y2} L${x3} ${y3} A${RIn} ${RIn} 0 ${large} 0 ${x4} ${y4} Z`}
              fill={sl.color} />
          );
        })}
        <text x={C} y={C - 4} textAnchor="middle" fontSize="22" fontWeight="900"
          fill={theme.text} fontFamily={theme.headingFont}>
          {total}
        </text>
        <text x={C} y={C + 14} textAnchor="middle" fontSize="10" fill={theme.textMuted}>
          名
        </text>
      </svg>
      <div style={{ flex: 1 }}>
        {slices.map((sl, i) => (
          <div key={i} style={{ marginBottom: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
              <span style={{ width: 10, height: 10, borderRadius: 2, background: sl.color }}></span>
              <span style={{ fontSize: 12, fontWeight: 600 }}>{sl.label}</span>
            </div>
            <div style={{ fontFamily: theme.headingFont, fontSize: 18, fontWeight: 900, color: sl.color,
              fontFeatureSettings: '"tnum"' }}>
              {sl.value}<span style={{ fontSize: 11, color: theme.textMuted, marginLeft: 4 }}>
                ({Math.round(sl.value / total * 100)}%)
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenDashboardDesktop });
