// kpi.jsx — 画面4: KPI ダッシュボード (22シートExcel置換)

function KPI({ chartKind = 'line' /* line | bar | area */ }) {

  // ── Channel funnel (horizontal bars) ──────────────────────────
  const Funnel = () => {
    const maxFlow = Math.max(...CHANNEL_FUNNEL.map((c) => c.flow));
    const stages = [
    { k: 'flow', label: '流入' },
    { k: 'visit', label: '見学' },
    { k: 'brief', label: '説明会' },
    { k: 'applied', label: '申込' },
    { k: 'enrolled', label: '入学' }];

    return (
      <div className="card overflow-hidden">
        <div className="px-4 py-2.5 hairline-b flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="w-1 h-4 rounded-full bg-gold" />
            <h3 className="text-[13px] font-semibold">流入チャネル別ファネル</h3>
            <span className="text-[11px] text-mute">過去30日</span>
          </div>
          <div className="flex items-center gap-1 text-[11px]">
            <button className="px-2 py-1 rounded-md bg-ink text-cream">人数</button>
            <button className="px-2 py-1 rounded-md hover:bg-cream2 text-ink2">転換率</button>
          </div>
        </div>
        <div className="px-5 py-4">
          {/* Header row */}
          <div className="grid grid-cols-[120px_1fr_repeat(4,40px)] gap-3 items-center text-[10.5px] text-mute tracking-wide uppercase pb-2 hairline-b">
            <div>チャネル</div>
            <div>流入 → 入学</div>
            {stages.slice(1).map((s) => <div key={s.k} className="text-center">{s.label}</div>)}
          </div>
          {CHANNEL_FUNNEL.map((ch) => {
            const ratio = ch.enrolled / ch.flow;
            const sa = (k) => Math.max(8, ch[k] / maxFlow * 100);
            return (
              <div key={ch.id} className="grid grid-cols-[120px_1fr_repeat(4,40px)] gap-3 items-center py-3 hairline-b last:border-b-0">
                <div>
                  <div className="text-[12px] font-medium">{ch.name}</div>
                  <div className="text-[10.5px] text-mute"><span className="num font-semibold" style={{ color: ratio > 0.18 ? '#7A9F7E' : ratio < 0.12 ? '#C9536A' : '#5D3848' }}>{(ratio * 100).toFixed(1)}%</span> 入学率</div>
                </div>
                <div className="relative h-7 flex items-center">
                  {/* Stacked funnel: 5 nested bars right-shifted, descending width */}
                  <div className="absolute inset-y-0 left-0 right-0 flex items-center">
                    {stages.map((s, i) =>
                    <div key={s.k} className="absolute h-full top-0 flex items-center px-2 text-[10px] num font-semibold text-white"
                    style={{
                      left: 0,
                      width: `${sa(s.k)}%`,
                      background: i === 0 ? '#5D3848' : i === 1 ? '#7A4A60' : i === 2 ? '#B5728C' : i === 3 ? '#D89AAA' : '#EBC0CB',
                      borderRadius: 4,
                      zIndex: 5 - i,
                      paddingRight: 4
                    }}>
                        <span className="ml-auto">{ch[s.k]}</span>
                      </div>
                    )}
                  </div>
                </div>
                {stages.slice(1).map((s) => {
                  const prev = stages[stages.findIndex((x) => x.k === s.k) - 1].k;
                  const conv = ch[s.k] / ch[prev];
                  return (
                    <div key={s.k} className={`text-center num text-[11px] font-medium ${conv > 0.6 ? 'text-okgreen' : conv < 0.4 ? 'text-alert' : 'text-ink2'}`}>
                      {(conv * 100).toFixed(0)}%
                    </div>);

                })}
              </div>);

          })}
        </div>
        <div className="px-5 py-3 hairline-t bg-cream2/30 flex items-center justify-between text-[11px] text-ink2">
          <span><b className="text-ink">紹介</b> が最高転換 (47.6%入学率) — 紹介報酬制度の Phase 2 着手で更に伸長見込</span>
          <span className="text-mute">合計流入 <span className="num font-semibold text-ink">427名</span></span>
        </div>
      </div>);

  };

  // ── Sales chart (line / bar / area) ───────────────────────────
  const SalesChart = () => {
    const w = 640,h = 240,pad = { l: 36, r: 16, t: 16, b: 28 };
    const cw = w - pad.l - pad.r,ch = h - pad.t - pad.b;
    const months = MONTHLY_SALES;
    const schools = [
    { id: 'umeda', name: '梅田福島', color: '#B5728C' },
    { id: 'kyobashi', name: '京橋', color: '#D89AAA' },
    { id: 'shinsai', name: '心斎橋', color: '#C9A98C' },
    { id: 'namba', name: '難波', color: '#9A8EAA' },
    { id: 'kobe', name: '神戸', color: '#7A9F7E' },
    { id: 'shinjuku', name: '新宿', color: '#D6A172' }];

    const max = 2200;
    const xAt = (i) => pad.l + i / (months.length - 1) * cw;
    const yAt = (v) => pad.t + ch - v / max * ch;
    const total = months.reduce((sum, m) => sum + schools.reduce((s, sc) => s + m[sc.id], 0), 0);
    const totalLast = schools.reduce((s, sc) => s + months[months.length - 1][sc.id], 0);
    const totalPrev = schools.reduce((s, sc) => s + months[months.length - 2][sc.id], 0);
    const growthPct = ((totalLast - totalPrev) / totalPrev * 100).toFixed(1);

    return (
      <div className="card overflow-hidden">
        <div className="px-4 py-2.5 hairline-b flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="w-1 h-4 rounded-full bg-gold" />
            <h3 className="text-[13px] font-semibold">校舎別売上推移</h3>
            <span className="text-[11px] text-mute">過去6ヶ月（万円）</span>
          </div>
          <div className="flex items-center gap-3">
            <div className="text-right">
              <div className="num text-[16px] font-semibold leading-tight">¥{(totalLast * 10).toLocaleString()}<span className="text-[10px] text-mute font-medium">万</span></div>
              <div className="text-[10.5px] text-okgreen">5月 +{growthPct}% vs 前月</div>
            </div>
          </div>
        </div>
        <div className="px-3 py-3">
          <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="w-full" preserveAspectRatio="xMidYMid meet">
            {/* grid */}
            {[0, 500, 1000, 1500, 2000].map((v) =>
            <g key={v}>
                <line x1={pad.l} x2={w - pad.r} y1={yAt(v)} y2={yAt(v)} stroke="#F0E8E0" strokeDasharray="2 3" />
                <text x={pad.l - 6} y={yAt(v) + 3} textAnchor="end" className="axis-tick">{v}</text>
              </g>
            )}
            {/* x labels */}
            {months.map((m, i) =>
            <text key={i} x={xAt(i)} y={h - 10} textAnchor="middle" className="axis-tick">{m.month.slice(5)}</text>
            )}

            {chartKind === 'bar' && (() => {
              const bw = cw / months.length / (schools.length + 1);
              return months.map((m, i) =>
              <g key={i}>
                  {schools.map((sc, j) => {
                  const x = xAt(i) - schools.length * bw / 2 + j * bw;
                  const y = yAt(m[sc.id]);
                  return <rect key={sc.id} x={x} y={y} width={bw - 1} height={pad.t + ch - y} fill={sc.color} opacity="0.9" />;
                })}
                </g>
              );
            })()}

            {chartKind !== 'bar' && schools.map((sc) => {
              const pts = months.map((m, i) => `${xAt(i)},${yAt(m[sc.id])}`).join(' ');
              if (chartKind === 'area') {
                const areaPath = `M ${xAt(0)},${yAt(0)} L ${pts.split(' ').join(' L ')} L ${xAt(months.length - 1)},${yAt(0)} Z`;
                return (
                  <g key={sc.id}>
                    <path d={areaPath} fill={sc.color} fillOpacity="0.18" />
                    <polyline points={pts} fill="none" stroke={sc.color} strokeWidth="2" />
                    {months.map((m, i) => <circle key={i} cx={xAt(i)} cy={yAt(m[sc.id])} r="3" fill="#fff" stroke={sc.color} strokeWidth="2" />)}
                  </g>);

              }
              return (
                <g key={sc.id}>
                  <polyline points={pts} fill="none" stroke={sc.color} strokeWidth="2.2" />
                  {months.map((m, i) => <circle key={i} cx={xAt(i)} cy={yAt(m[sc.id])} r="3" fill="#fff" stroke={sc.color} strokeWidth="2" />)}
                </g>);

            })}

            {/* highlight latest umeda */}
            <text x={xAt(months.length - 1) + 6} y={yAt(months[months.length - 1].umeda) + 4} className="num" fontSize="10" fill="#B5728C" fontWeight="600">梅田 2,080</text>
          </svg>

          <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 pt-1">
            {schools.map((sc) =>
            <div key={sc.id} className="flex items-center gap-1.5 text-[11px]">
                <span style={{ width: 10, height: 10, background: sc.color, borderRadius: 2 }} />
                <span className="text-ink2">{sc.name}</span>
                <span className="num text-mute">{months[months.length - 1][sc.id]}</span>
              </div>
            )}
          </div>
        </div>
      </div>);

  };

  // ── Course mix (donut) ────────────────────────────────────────
  const Donut = () => {
    const total = COURSE_MIX.reduce((s, c) => s + c.students, 0);
    const r = 64,sw = 22,cx = 90,cy = 90;
    const circumference = 2 * Math.PI * r;
    let offset = 0;
    return (
      <div className="card overflow-hidden">
        <div className="px-4 py-2.5 hairline-b flex items-center gap-2">
          <span className="w-1 h-4 rounded-full bg-gold" />
          <h3 className="text-[13px] font-semibold">コース別構成</h3>
          <span className="text-[11px] text-mute ml-auto">在籍 {total}名</span>
        </div>
        <div className="p-4 flex items-center gap-4">
          <svg width="180" height="180" viewBox="0 0 180 180">
            <circle cx={cx} cy={cy} r={r} fill="none" stroke="#F4EEE8" strokeWidth={sw} />
            {COURSE_MIX.map((c, i) => {
              const dash = c.share * circumference;
              const seg =
              <circle key={i} cx={cx} cy={cy} r={r} fill="none"
              stroke={c.color} strokeWidth={sw}
              strokeDasharray={`${dash} ${circumference - dash}`}
              strokeDashoffset={-offset}
              transform={`rotate(-90 ${cx} ${cy})`} />;

              offset += dash;
              return seg;
            })}
            <text x={cx} y={cy - 4} textAnchor="middle" className="num" fontSize="22" fontWeight="600" fill="#5D3848">{total}</text>
            <text x={cx} y={cy + 12} textAnchor="middle" fontSize="9" fill="#A89098">在籍合計</text>
          </svg>
          <div className="flex-1 flex flex-col gap-1.5">
            {COURSE_MIX.map((c) =>
            <div key={c.id} className="flex items-center gap-2 text-[12px]">
                <span style={{ width: 8, height: 8, borderRadius: 2, background: c.color }} />
                <span className="flex-1 truncate">{c.name}</span>
                <span className="num text-mute w-12 text-right">{(c.share * 100).toFixed(0)}%</span>
                <span className="num text-ink2 w-12 text-right">{c.students}名</span>
              </div>
            )}
            <div className="pt-2 mt-1 hairline-t text-[10.5px] text-mute">
              平均単価 <span className="num font-semibold text-ink">¥327,800</span> · LTV <span className="num font-semibold text-ink">¥4.2億 / 年</span>
            </div>
          </div>
        </div>
      </div>);

  };

  // ── Rescue simulation hero ────────────────────────────────────
  const RescueHero = () =>
  <div className="card-lg overflow-hidden col-span-12" style={{ background: 'linear-gradient(135deg,#FCF2F4 0%,#F0CFD8 100%)' }}>
      <div className="px-6 py-5 flex items-center gap-8">
        <div className="flex-1">
          <div className="text-[10.5px] tracking-[0.18em] uppercase text-gold2 font-semibold mb-1">取りこぼし救済シミュレーション</div>
          <div className="text-[15px] text-ink2 mb-1">3 日未連絡アラートの稼働で、月平均</div>
          <div className="flex items-baseline gap-2 mb-1">
            <span className="num text-[44px] font-semibold leading-none text-ink">3 件</span>
            <span className="text-[14px] text-mute">救済</span>
            <span className="text-[14px] text-mute mx-1">→</span>
            <span className="num text-[44px] font-semibold leading-none" style={{ color: '#B5728C' }}>+¥855,000</span>
            <span className="text-[14px] text-mute">/ 月</span>
          </div>
          <div className="text-[11.5px] text-ink2 leading-relaxed mt-1.5 max-w-2xl">
            過去90日で「説明会後3日以上未連絡」かつ離脱したケース：<span className="num font-semibold">月平均9名</span>。うち平均単価<span className="num font-semibold">¥285,000</span>を母数に、過去類似ケースの再アプローチ成功率<span className="num font-semibold">33%</span>を適用。
          </div>
        </div>
        <div className="flex flex-col gap-2 shrink-0">
          <div className="text-center">
            <div className="text-[10.5px] text-mute mb-1">年換算</div>
            <div className="num text-[26px] font-semibold text-ink">+¥10.26M</div>
          </div>
          <button className="px-4 py-2 rounded-md bg-ink text-cream text-[12px] font-medium hover:bg-ink2">アラート設定を確認</button>
        </div>
      </div>
    </div>;


  // ── Time savings tile ─────────────────────────────────────────
  const TimeSavings = () =>
  <div className="card-lg overflow-hidden col-span-4" style={{ background: 'linear-gradient(160deg,#5D3848 0%,#3F2434 100%)', color: '#FCF7F6' }}>
      <div className="px-5 py-5">
        <div className="text-[10.5px] tracking-[0.18em] uppercase text-gold mb-2">作業時間削減</div>
        <div className="flex items-baseline gap-2 mb-1.5">
          <span className="num text-[40px] font-semibold leading-none">10–20</span>
          <span className="text-[14px] text-gold">時間 / 月</span>
        </div>
        <div className="text-[12px] text-cream/80 leading-relaxed">
          22 シート手集計の自動化で、デモ副社長の作業時間が削減。<span className="text-gold font-medium"></span>
        </div>
        <div className="mt-3 grid grid-cols-3 gap-2">
          {[
        { l: 'Excel手集計', v: '0h' },
        { l: 'コピペ', v: '0h' },
        { l: '転記ミス', v: '0件' }].
        map((s, i) =>
        <div key={i} className="px-2 py-2 rounded-md" style={{ background: 'rgba(255,255,255,0.06)' }}>
              <div className="num text-[16px] font-semibold text-cream">{s.v}</div>
              <div className="text-[10px] text-gold/80">{s.l}</div>
            </div>
        )}
        </div>
      </div>
    </div>;


  return (
    <div className="px-7 py-6 nice-scroll overflow-y-auto" style={{ height: 'calc(100vh - 56px)' }}>
      {/* Header */}
      <div className="flex items-end justify-between mb-5">
        <div>
          <div className="text-[11px] text-mute mb-1 tracking-wide">2026年5月 · 全校舎ビュー</div>
          <h1 className="text-[22px] font-semibold text-ink">KPI レポート</h1>
          <p className="text-[12.5px] text-ink2 mt-1">22 シート Excel の手集計から解放。<span className="font-medium text-ink">自動更新 · エクスポート可能</span>。</p>
        </div>
        <div className="flex items-center gap-2">
          <button className="text-[12px] px-3 py-1.5 rounded-md border border-line hover:bg-cream2 flex items-center gap-1.5 whitespace-nowrap">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="M7 10l5 5 5-5" /><path d="M12 15V3" /></svg>
            Excel出力
          </button>
          <button className="text-[12px] px-3 py-1.5 rounded-md border border-line hover:bg-cream2 flex items-center gap-1.5 whitespace-nowrap">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></svg>
            PDF出力
          </button>
          <button className="text-[12px] px-3 py-1.5 rounded-md bg-ink text-cream hover:bg-ink2 flex items-center gap-1.5 whitespace-nowrap">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 12h16M4 6h16M4 18h10" /></svg>
            経理シートへ送信
          </button>
        </div>
      </div>

      {/* Quick stats */}
      <div className="grid grid-cols-12 gap-3 mb-3">
        <div className="col-span-3"><StatTile label="今月売上見込" value="¥73.8" suffix="M" delta="+9.1%" sub="vs 前月" /></div>
        <div className="col-span-3"><StatTile label="新規入学" value="16" suffix="名" delta="+3" sub="前月比" /></div>
        <div className="col-span-3"><StatTile label="平均CVR" value="9.3" suffix="%" tone="ok" delta="+0.8pt" sub="流入→入学" /></div>
        <div className="col-span-3"><StatTile label="LTV" value="¥327K" tone="default" sub="平均単価 (在籍330名)" /></div>
      </div>

      {/* Rescue hero */}
      <div className="grid grid-cols-12 gap-3 mb-3">
        <RescueHero />
      </div>

      {/* Charts */}
      <div className="grid grid-cols-12 gap-3 mb-3">
        <div className="col-span-8"><SalesChart /></div>
        <div className="col-span-4"><Donut /></div>
      </div>

      {/* Funnel + time-savings */}
      <div className="grid grid-cols-12 gap-3">
        <div className="col-span-8"><Funnel /></div>
        <TimeSavings />
      </div>
    </div>);

}

window.KPI = KPI;