/* global React */
/* eslint-disable */
// ─────────────────────────────────────────────
// 性能ページ (Performance) — 内製スタイル版
//   元リポジトリ cost.html の 5タブ相当データ(window.HOUSE_DATA)を
//   本ビジュアライザーのトークン/コンポーネントで描き直す。
//   - 既存の "性能サマリー(6カード)" もタブ1としてそのまま保持。
// ─────────────────────────────────────────────

const { useState, useMemo } = React;

// ---- 小物 -------------------------------------------------
const Pill = ({ tone = 'muted', children }) => {
  const map = {
    good:    { bg: 'color-mix(in oklch, var(--positive) 14%, transparent)', fg: 'var(--positive)', bd: 'color-mix(in oklch, var(--positive) 28%, transparent)' },
    caution: { bg: 'color-mix(in oklch, var(--warn) 14%, transparent)',     fg: 'var(--warn)',     bd: 'color-mix(in oklch, var(--warn) 28%, transparent)' },
    bad:     { bg: 'color-mix(in oklch, var(--negative) 14%, transparent)', fg: 'var(--negative)', bd: 'color-mix(in oklch, var(--negative) 28%, transparent)' },
    accent:  { bg: 'var(--accent-soft)',                                    fg: 'var(--accent-ink)', bd: 'color-mix(in oklch, var(--accent) 30%, transparent)' },
    muted:   { bg: 'var(--surface-2)',                                      fg: 'var(--ink-3)',    bd: 'var(--line-2)' },
  };
  const c = map[tone] || map.muted;
  return <span className="perf-pill" style={{ background: c.bg, color: c.fg, borderColor: c.bd }}>{children}</span>;
};

const Score5 = ({ value }) => (
  <span className="perf-score5">
    {[1,2,3,4,5].map(i => <span key={i} className={`dot ${i <= value ? 'on' : ''}`}/>)}
  </span>
);

// ---- タブ A: 性能サマリー (既存 6カード) -------------------
const SummaryTab = () => (
  <div className="perf-grid">
    <div className="perf-card perf-card-hero">
      <div className="perf-card-eyebrow">熱損失係数 UA</div>
      <div className="perf-hero-value">
        <span className="serif" style={{ fontSize: 80, lineHeight: 1, fontWeight: 700 }}>0.42</span>
        <span style={{ fontSize: 14, color: 'var(--ink-3)', marginLeft: 8 }}>W/m²K</span>
      </div>
      <div style={{ marginTop: 20 }}>
        <div className="perf-grade-bar">
          <div className="perf-grade-segment" data-active="true">  <span>HEAT20 G3</span><span className="mono">≤0.34</span></div>
          <div className="perf-grade-segment" data-active="current">  <span>HEAT20 G2 ★</span><span className="mono">≤0.46</span></div>
          <div className="perf-grade-segment">                       <span>HEAT20 G1</span><span className="mono">≤0.56</span></div>
          <div className="perf-grade-segment">                       <span>ZEH</span><span className="mono">≤0.60</span></div>
          <div className="perf-grade-segment">                       <span>4等級</span><span className="mono">≤0.87</span></div>
        </div>
      </div>
      <div className="perf-card-foot">本住宅は HEAT20 G2 グレード相当 — 6地域での推奨水準を満たしています</div>
    </div>

    <div className="perf-card">
      <div className="perf-card-eyebrow">気密性能 C値</div>
      <div className="perf-card-value-row">
        <span className="serif" style={{ fontSize: 44, fontWeight: 700, lineHeight: 1 }}>0.5</span>
        <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>cm²/m²</span>
      </div>
      <div className="perf-mini-bar"><div style={{ width: '92%', background: 'var(--positive)' }}/></div>
      <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>業界平均 (2.0) より優秀 · 高気密住宅基準クリア</div>
    </div>

    <div className="perf-card">
      <div className="perf-card-eyebrow">冷房期 日射取得率 ηAC</div>
      <div className="perf-card-value-row">
        <span className="serif" style={{ fontSize: 44, fontWeight: 700, lineHeight: 1 }}>1.6</span>
        <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>—</span>
      </div>
      <div className="perf-mini-bar"><div style={{ width: '78%', background: 'var(--positive)' }}/></div>
      <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>日射遮蔽 良好 · 6地域基準 (2.8以下) 余裕クリア</div>
    </div>

    <div className="perf-card perf-card-sun">
      <div className="perf-card-eyebrow">日照シミュレーション · 冬至</div>
      <div className="perf-sun-grid">
        <div className="perf-sun-face"><div className="perf-sun-label">北面</div>
          <div className="perf-sun-cell" style={{ background: `linear-gradient(180deg, var(--bg-2) 88%, oklch(0.75 0.10 70) 100%)` }}><span className="mono">12%</span></div>
        </div>
        <div className="perf-sun-face"><div className="perf-sun-label">東面</div>
          <div className="perf-sun-cell" style={{ background: `linear-gradient(180deg, var(--bg-2) 36%, oklch(0.72 0.13 75) 100%)` }}><span className="mono">64%</span></div>
        </div>
        <div className="perf-sun-face"><div className="perf-sun-label">南面 ★</div>
          <div className="perf-sun-cell" style={{ background: `linear-gradient(180deg, var(--bg-2) 8%, oklch(0.78 0.16 75) 100%)` }}><span className="mono">92%</span></div>
        </div>
        <div className="perf-sun-face"><div className="perf-sun-label">西面</div>
          <div className="perf-sun-cell" style={{ background: `linear-gradient(180deg, var(--bg-2) 62%, oklch(0.68 0.13 70) 100%)` }}><span className="mono">38%</span></div>
        </div>
      </div>
      <div className="perf-sun-foot">南面の日射取得が良好 · LDK・主寝室は冬季暖房負荷を抑制できる配置</div>
    </div>

    <div className="perf-card">
      <div className="perf-card-eyebrow">一次エネルギー消費</div>
      <div className="perf-card-value-row">
        <span className="serif" style={{ fontSize: 44, fontWeight: 700, lineHeight: 1 }}>71</span>
        <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>GJ/年</span>
      </div>
      <div className="perf-bar-stack">
        <div title="冷房" style={{ width: '20%', background: 'oklch(0.72 0.12 230)' }}><span>冷 14.2</span></div>
        <div title="暖房" style={{ width: '26%', background: 'oklch(0.66 0.13 25)' }}><span>暖 18.6</span></div>
        <div title="給湯" style={{ width: '32%', background: 'oklch(0.62 0.10 80)' }}><span>給湯 22.4</span></div>
        <div title="家電・照明" style={{ width: '22%', background: 'oklch(0.55 0.07 105)' }}><span>家電 15.8</span></div>
      </div>
      <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>ZEH基準比 -28%</div>
    </div>

    <div className="perf-card perf-card-sunpath">
      <div className="perf-card-eyebrow">太陽軌跡 · 冬至/夏至</div>
      {window.HV.SunPathSVG ? <window.HV.SunPathSVG/> : null}
    </div>
  </div>
);

// ---- タブ B: 設備選択 -------------------------------------
const EquipmentTab = ({ selection, setSelection }) => {
  const data = window.HOUSE_DATA;
  if (!data) return <div className="perf-empty">HOUSE_DATA 未ロード</div>;
  const { CATS, SCORE_AXES, REASONS } = data;
  const [openCat, setOpenCat] = useState(CATS[0].id);

  return (
    <div className="perf-equip">
      <div className="perf-equip-side">
        {CATS.map(cat => {
          const picked = cat.options.find(o => o.id === selection[cat.id]) || cat.options[0];
          return (
            <button
              key={cat.id}
              className={`perf-equip-cat ${openCat === cat.id ? 'is-open' : ''}`}
              onClick={() => setOpenCat(cat.id)}
            >
              <span className="perf-equip-cat-icon">{cat.icon}</span>
              <span className="perf-equip-cat-text">
                <span className="perf-equip-cat-label">{cat.label}</span>
                <span className="perf-equip-cat-pick">{picked.label}</span>
              </span>
              <Pill tone={picked.p.r === 'good' ? 'good' : 'caution'}>
                {picked.p.r === 'good' ? '採用' : '比較'}
              </Pill>
            </button>
          );
        })}
      </div>
      <div className="perf-equip-detail">
        {CATS.filter(c => c.id === openCat).map(cat => (
          <div key={cat.id}>
            <div className="perf-equip-head">
              <div>
                <div className="t-eyebrow">EQUIPMENT</div>
                <h3 className="serif" style={{ fontSize: 22, fontWeight: 700, marginTop: 4 }}>
                  <span style={{ marginRight: 8 }}>{cat.icon}</span>{cat.label}
                </h3>
              </div>
            </div>
            <div className="perf-equip-opts">
              {cat.options.map(opt => {
                const isPicked = selection[cat.id] === opt.id;
                return (
                  <div key={opt.id} className={`perf-equip-opt ${isPicked ? 'is-picked' : ''}`}>
                    <div className="perf-equip-opt-h">
                      <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', flex: 1 }}>
                        <input
                          type="radio"
                          name={`cat-${cat.id}`}
                          checked={isPicked}
                          onChange={() => setSelection({ ...selection, [cat.id]: opt.id })}
                          style={{ accentColor: 'var(--accent)' }}
                        />
                        <span style={{ fontWeight: 600, fontSize: 14 }}>{opt.label}</span>
                      </label>
                      <Pill tone={opt.p.r === 'good' ? 'good' : 'caution'}>{opt.p.r === 'good' ? '推奨' : '要検討'}</Pill>
                    </div>
                    <div className="perf-equip-opt-meta">
                      <span><span className="t-eyebrow">MAKER</span> {opt.maker}</span>
                      <span><span className="t-eyebrow">初期</span> <strong className="mono">{opt.init}</strong> 万円</span>
                      <span><span className="t-eyebrow">年間</span> <strong className="mono">{opt.annual >= 0 ? opt.annual : `${opt.annual}`}</strong> 万円</span>
                    </div>
                    <div className="perf-equip-opt-scores">
                      {SCORE_AXES.map(ax => (
                        <div key={ax.k} className="perf-axis">
                          <span className="perf-axis-l">{ax.l}</span>
                          <Score5 value={opt.scores[ax.k]}/>
                          <span className="perf-axis-reason">{REASONS[ax.k]?.[opt.id]}</span>
                        </div>
                      ))}
                    </div>
                    <div className="perf-equip-opt-proscons">
                      <div className="perf-pros">
                        <div className="t-eyebrow">PROS</div>
                        <ul>{opt.pros.map((p,i) => <li key={i}>{p}</li>)}</ul>
                      </div>
                      <div className="perf-cons">
                        <div className="t-eyebrow">CONS</div>
                        <ul>{opt.cons.map((p,i) => <li key={i}>{p}</li>)}</ul>
                      </div>
                    </div>
                    <div className={`perf-equip-opt-comment ${opt.p.r}`}>
                      <strong>{opt.p.r === 'good' ? '✓ 採用所見' : '⚠ 比較所見'}：</strong>{opt.p.t}
                    </div>
                    {opt.rec && (
                      <div className="perf-equip-opt-rec">
                        <strong>🛒 おすすめ型番：</strong>{opt.rec}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ---- タブ C: 動線改善 -------------------------------------
// 平面図フロー図: 1F平面 (9,555 × 7,735mm) に動線矢印を重ねる SVG。
// 元リポジトリ (flow-tab.jsx FloorPlanFlow) を本ページのデザイントークンで再構築。
const FloorPlanFlowSVG = () => (
  <svg viewBox="0 0 820 620" style={{ width: '100%', height: 'auto', display: 'block' }}>
    <defs>
      <marker id="flow-arr-pos" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
        <path d="M0,0 L0,6 L8,3 z" fill="var(--positive)"/>
      </marker>
      <marker id="flow-arr-warn" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
        <path d="M0,0 L0,6 L8,3 z" fill="var(--warn)"/>
      </marker>
      <marker id="flow-arr-acc" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
        <path d="M0,0 L0,6 L8,3 z" fill="var(--accent)"/>
      </marker>
      <marker id="flow-arr-neg" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
        <path d="M0,0 L0,6 L8,3 z" fill="var(--negative)"/>
      </marker>
      <pattern id="flow-tatami" patternUnits="userSpaceOnUse" width="20" height="20">
        <rect width="20" height="20" fill="oklch(0.88 0.06 80)"/>
        <line x1="0" y1="0" x2="20" y2="0" stroke="oklch(0.75 0.06 75)" strokeWidth="0.6"/>
        <line x1="0" y1="0" x2="0" y2="20" stroke="oklch(0.75 0.06 75)" strokeWidth="0.6"/>
      </pattern>
    </defs>

    {/* 方位 */}
    <g transform="translate(770, 36)">
      <circle r="20" fill="var(--surface-2)" stroke="var(--line)" strokeWidth="1"/>
      <path d="M0,-13 L4,0 L0,4 L-4,0 z" fill="var(--negative)"/>
      <path d="M0,13 L4,0 L0,-4 L-4,0 z" fill="var(--ink-3)"/>
      <text y="-22" fontSize="9" fill="var(--negative)" textAnchor="middle" fontWeight="700">N</text>
    </g>

    {/* 外部西側 駐車場 */}
    <rect x="10" y="200" width="80" height="280" fill="var(--bg-2)" stroke="var(--line-2)" strokeWidth="1" strokeDasharray="3,2"/>
    <text x="50" y="335" fontSize="11" fontWeight="700" fill="var(--ink-3)" textAnchor="middle">🚗</text>
    <text x="50" y="356" fontSize="10" fontWeight="700" fill="var(--ink-2)" textAnchor="middle">駐車場</text>
    <text x="50" y="370" fontSize="9" fill="var(--ink-3)" textAnchor="middle">カーポート</text>

    {/* 建物外枠 */}
    <rect x="100" y="30" width="700" height="566" fill="none" stroke="var(--ink-3)" strokeWidth="1.5"/>

    {/* ── 北辺: 水回り＋階段＋畳コーナー ── */}
    {/* UB / 脱衣 / 洗面 / WC */}
    {[
      { x:100, w:133, label:'🛁 UB', sub:'浴室' },
      { x:233, w:100, label:'脱衣室', sub:'ドラム式洗乾' },
      { x:333, w:100, label:'洗面', sub:'' },
      { x:433, w:67,  label:'🚽 WC', sub:'' },
    ].map((r,i) => (
      <g key={i}>
        <rect x={r.x} y={30} width={r.w} height={133}
              fill="oklch(0.95 0.02 230)" stroke="oklch(0.78 0.05 230)" strokeWidth="1"/>
        <text x={r.x + r.w/2} y={88} fontSize="11" fontWeight="700" fill="var(--ink)" textAnchor="middle">{r.label}</text>
        {r.sub && <text x={r.x + r.w/2} y={104} fontSize="8.5" fill="var(--ink-3)" textAnchor="middle">{r.sub}</text>}
      </g>
    ))}
    {/* 階段 */}
    <rect x="500" y="30" width="133" height="200" fill="var(--surface-2)" stroke="var(--line)" strokeWidth="1"/>
    <text x="566" y="116" fontSize="11" fontWeight="700" fill="var(--ink)" textAnchor="middle">階段</text>
    <text x="566" y="132" fontSize="9" fill="var(--ink-3)" textAnchor="middle">UP ↑ 2F</text>
    {/* 畳コーナー */}
    <rect x="633" y="30" width="167" height="200" fill="url(#flow-tatami)" stroke="oklch(0.65 0.07 75)" strokeWidth="1"/>
    <text x="716" y="120" fontSize="11" fontWeight="700" fill="oklch(0.30 0.08 75)" textAnchor="middle">畳コーナー</text>
    <text x="716" y="138" fontSize="9" fill="oklch(0.40 0.10 75)" textAnchor="middle">3.1帖</text>

    {/* ── 中段西: 玄関＋ホール ── */}
    <rect x="100" y="163" width="133" height="133" fill="oklch(0.94 0.025 50)" stroke="oklch(0.78 0.05 50)" strokeWidth="1"/>
    <text x="166" y="223" fontSize="11" fontWeight="700" fill="var(--ink)" textAnchor="middle">🚪 玄関</text>
    <text x="166" y="239" fontSize="9" fill="var(--ink-3)" textAnchor="middle">エントランス</text>

    <rect x="233" y="163" width="100" height="67" fill="var(--surface)" stroke="var(--line)" strokeWidth="1"/>
    <text x="283" y="201" fontSize="10" fontWeight="600" fill="var(--ink-2)" textAnchor="middle">ホール</text>

    <rect x="333" y="163" width="167" height="67" fill="var(--surface-2)" stroke="var(--line)" strokeWidth="1"/>
    <text x="416" y="201" fontSize="9" fontWeight="600" fill="var(--ink-3)" textAnchor="middle">階段下収納</text>

    {/* ── LDK 19帖 ── */}
    <rect x="233" y="230" width="567" height="367" fill="oklch(0.96 0.02 80)" stroke="oklch(0.80 0.05 80)" strokeWidth="1"/>
    {/* キッチン */}
    <rect x="343" y="320" width="60" height="200" rx="3" fill="var(--surface)" stroke="var(--ink-3)" strokeWidth="1"/>
    <circle cx="373" cy="350" r="6" fill="var(--bg-2)" stroke="oklch(0.65 0.13 230)" strokeWidth="0.8"/>
    <circle cx="373" cy="380" r="6" fill="var(--bg-2)" stroke="oklch(0.65 0.13 230)" strokeWidth="0.8"/>
    <text x="373" y="433" fontSize="11" textAnchor="middle">🍳</text>
    <text x="373" y="453" fontSize="9" fontWeight="700" fill="var(--ink)" textAnchor="middle">キッチン</text>
    <text x="373" y="466" fontSize="7.5" fill="var(--ink-3)" textAnchor="middle">IH+食洗機</text>
    <text x="373" y="500" fontSize="7.5" fill="var(--ink-3)" textAnchor="middle">アイランド</text>

    <text x="460" y="560" fontSize="10" fontWeight="600" fill="var(--ink-3)" textAnchor="middle">🪑 ダイニング</text>
    <text x="620" y="380" fontSize="12" fontWeight="700" fill="var(--ink)" textAnchor="middle">LDK</text>
    <text x="620" y="396" fontSize="10" fill="oklch(0.45 0.08 80)" textAnchor="middle">19帖</text>
    <text x="620" y="450" fontSize="9" fill="var(--ink-3)" textAnchor="middle">🛋 リビング</text>

    {/* ── 南西: FCL / パントリー ── */}
    <rect x="100" y="297" width="133" height="166" fill="var(--surface-2)" stroke="var(--line)" strokeWidth="1"/>
    <text x="166" y="370" fontSize="10" fontWeight="700" fill="var(--ink)" textAnchor="middle">FCL</text>
    <text x="166" y="385" fontSize="8" fill="var(--ink-3)" textAnchor="middle">ファミリー</text>
    <text x="166" y="397" fontSize="8" fill="var(--ink-3)" textAnchor="middle">クローゼット</text>
    <text x="166" y="416" fontSize="9" fill="var(--accent-ink)" textAnchor="middle">👜 鞄置き</text>

    <rect x="100" y="463" width="133" height="134" fill="var(--surface-2)" stroke="var(--line)" strokeWidth="1"/>
    <text x="166" y="525" fontSize="10" fontWeight="700" fill="var(--ink)" textAnchor="middle">パントリー</text>
    <text x="166" y="540" fontSize="8" fill="var(--ink-3)" textAnchor="middle">食品庫</text>

    {/* 外部南: 物干し */}
    <rect x="500" y="600" width="200" height="14" fill="none" stroke="var(--ink-3)" strokeWidth="1" strokeDasharray="3,2"/>
    <text x="600" y="613" fontSize="9" fill="var(--ink-3)" textAnchor="middle">物干しスペース（屋外南）</text>

    {/* ロボ基地 */}
    <rect x="345" y="240" width="55" height="20" rx="3" fill="color-mix(in oklch, var(--positive) 14%, transparent)" stroke="var(--positive)" strokeWidth="0.8"/>
    <text x="372" y="254" fontSize="8" fontWeight="700" fill="var(--positive)" textAnchor="middle">🤖 ロボ基地</text>

    {/* ─── 動線矢印 ─── */}
    {/* ① ロボット巡回 */}
    <path d="M 400,260 Q 550,280 620,420 Q 550,520 400,500 Q 280,460 320,330"
          stroke="var(--positive)" strokeWidth="1.8" fill="none" strokeDasharray="4,3"
          markerEnd="url(#flow-arr-pos)" opacity="0.7"/>

    {/* ② 入浴後 洗濯 */}
    <path d="M 166,120 Q 200,100 250,80"
          stroke="var(--positive)" strokeWidth="2" fill="none" strokeDasharray="6,3"
          markerEnd="url(#flow-arr-pos)"/>

    {/* ③ 食洗機ON */}
    <path d="M 373,310 L 373,320"
          stroke="var(--positive)" strokeWidth="2.5" fill="none"
          markerEnd="url(#flow-arr-pos)"/>

    {/* ④ 出勤 */}
    <path d="M 100,228 L 88,228"
          stroke="var(--accent)" strokeWidth="2" fill="none"
          markerEnd="url(#flow-arr-acc)"/>

    {/* ⑤ 帰宅 */}
    <path d="M 90,300 Q 95,230 100,228"
          stroke="var(--accent)" strokeWidth="2" fill="none" strokeDasharray="4,3"
          markerEnd="url(#flow-arr-acc)"/>

    {/* ⑥ 帰宅後動線 */}
    <path d="M 233,228 L 333,200 L 343,400"
          stroke="var(--accent)" strokeWidth="1.6" fill="none" strokeDasharray="3,3"
          markerEnd="url(#flow-arr-acc)" opacity="0.7"/>

    {/* ⑦ 買い物搬入(内側) */}
    <path d="M 283,230 Q 220,260 166,297 L 166,463"
          stroke="var(--warn)" strokeWidth="2" fill="none" strokeDasharray="4,3"
          markerEnd="url(#flow-arr-warn)"/>

    {/* ⑧ 買い物搬入(外側) */}
    <path d="M 370,616 L 370,580 Q 280,565 166,530"
          stroke="var(--warn)" strokeWidth="1.8" fill="none" strokeDasharray="3,4"
          markerEnd="url(#flow-arr-warn)" opacity="0.75"/>
    <rect x="354" y="593" width="32" height="6" rx="1" fill="var(--warn)" opacity="0.5"/>

    {/* 帰宅後手洗い: 脱衣室は壁で通れないので 玄関→ホール→(LDK側)→洗面 で入る */}
    <path d="M 180,205 L 283,200 L 360,200 Q 383,196 383,163 L 383,135"
          stroke="oklch(0.62 0.15 290)" strokeWidth="1.8" fill="none" strokeDasharray="3,3" opacity="0.9"/>

    {/* ステップ番号バッジ — 朝からの1日の流れ順 */}
    <g fontFamily="JetBrains Mono, monospace">
      {[
        { n:1, x:348, y:332, c:'var(--positive)', fg:'#fff' },          // 食洗機ON(外出前)
        { n:2, x:372, y:250, c:'var(--positive)', fg:'#fff' },          // 外出時ロボスタート
        { n:3, x:120, y:195, c:'var(--accent)',   fg:'#fff' },          // 外出(玄関→外)
        { n:4, x:222, y:262, c:'var(--warn)',     fg:'#fff' },          // 搬入: ホール→FCL→パントリー
        { n:4, x:372, y:560, c:'var(--warn)',     fg:'#fff' },          // 搬入: キッチン南窓から直接
        { n:5, x:50,  y:270, c:'var(--accent)',   fg:'#fff' },          // 帰宅(駐車場→玄関)
        { n:6, x:312, y:188, c:'oklch(0.62 0.15 290)', fg:'#fff' },     // 帰宅後 手洗い
        { n:7, x:348, y:360, c:'var(--positive)', fg:'#fff' },          // 夕食後 食洗機ON
        { n:8, x:283, y:50,  c:'var(--positive)', fg:'#fff' },          // 入浴後 洗濯スタート
      ].map((s,i) => (
        <g key={i}>
          <circle cx={s.x} cy={s.y} r="10" fill={s.c} stroke="var(--surface)" strokeWidth="1.5"/>
          <text x={s.x} y={s.y} fontSize="10" fontWeight="700" fill={s.fg} textAnchor="middle" dominantBaseline="central">{s.n}</text>
        </g>
      ))}
    </g>
  </svg>
);

// 平面図フロー図カード本体
const FloorPlanFlowCard = () => (
  <div style={{
    background: 'var(--surface)',
    border: '1px solid var(--line)',
    borderRadius: 14,
    padding: 22,
  }}>
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 14, flexWrap: 'wrap', gap: 12 }}>
      <div>
        <div className="t-eyebrow">FLOOR PLAN · 1F</div>
        <h3 className="serif" style={{ fontSize: 18, fontWeight: 700, marginTop: 4 }}>動線オーバーレイ — 設備と移動の重なりを見る</h3>
      </div>
      <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontSize: 11.5 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-2)' }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--positive)' }}/> 自動化タスク
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-2)' }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--warn)' }}/> 手動タスク
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-2)' }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--accent)' }}/> 移動経路
        </span>
        <span className="mono" style={{ color: 'var(--ink-3)', fontSize: 11 }}>9,555 × 7,735 mm</span>
      </div>
    </div>

    <div style={{ background: 'var(--bg)', border: '1px solid var(--line-2)', borderRadius: 10, padding: 12 }}>
      <FloorPlanFlowSVG/>
    </div>

    {/* 凡例 (ステップ) */}
    <div style={{
      marginTop: 14,
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
      gap: '6px 18px',
      fontSize: 11.5,
      color: 'var(--ink-2)',
      lineHeight: 1.7,
    }}>
      <div><span className="mono" style={{ color: 'var(--positive)', fontWeight: 700, marginRight: 6 }}>①</span>食洗機ON（外出前）</div>
      <div><span className="mono" style={{ color: 'var(--positive)', fontWeight: 700, marginRight: 6 }}>②</span>外出時ロボスタート（LDK巡回）</div>
      <div><span className="mono" style={{ color: 'var(--accent)',   fontWeight: 700, marginRight: 6 }}>③</span>外出（玄関→外）</div>
      <div><span className="mono" style={{ color: 'var(--warn)',     fontWeight: 700, marginRight: 6 }}>④</span>搬入: ホール→FCL→パントリー</div>
      <div><span className="mono" style={{ color: 'var(--warn)',     fontWeight: 700, marginRight: 6 }}>④</span>搬入: キッチン南窓から直接</div>
      <div><span className="mono" style={{ color: 'var(--accent)',   fontWeight: 700, marginRight: 6 }}>⑤</span>帰宅（駐車場→玄関）</div>
      <div><span className="mono" style={{ color: 'oklch(0.62 0.15 290)', fontWeight: 700, marginRight: 6 }}>⑥</span>帰宅後 手洗い（玄関→ホール→洗面）</div>
      <div><span className="mono" style={{ color: 'var(--positive)', fontWeight: 700, marginRight: 6 }}>⑦</span>夕食後 食洗機ON</div>
      <div><span className="mono" style={{ color: 'var(--positive)', fontWeight: 700, marginRight: 6 }}>⑧</span>入浴後 洗濯スタート</div>
    </div>

    {/* 日々のメンテナンス（各数分・動線に組み込む） */}
    <div style={{
      marginTop: 14,
      padding: '12px 14px',
      background: 'var(--surface-2)',
      border: '1px solid var(--line-2)',
      borderRadius: 10,
    }}>
      <div className="t-eyebrow" style={{ marginBottom: 8 }}>🧹 日々のメンテナンス（各数分）</div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
        gap: '4px 18px',
        fontSize: 11.5,
        color: 'var(--ink-2)',
        lineHeight: 1.7,
      }}>
        <div>🤖 ロボ掃除機: ダストボックス確認・モップ手入れ・給水（拭き運用時）</div>
        <div>👕 ドラム式: 乾燥フィルターのホコリを毎回除去（つまり防止）</div>
        <div>🍳 IH・キッチン: 調理後に天板をサッと拭く（油はね・吹きこぼれ）</div>
        <div>🧹 ロボ非対応: 部屋の隅・家具の下・階段は手掃除で補完</div>
      </div>
    </div>
  </div>
);

const FlowTab = () => {
  const data = window.HOUSE_DATA;
  if (!data) return null;
  const { MOTIONS } = data;
  const totalSavedMin = MOTIONS.reduce((s, m) => s + m.saved, 0);
  const totalAnnual = MOTIONS.reduce((s, m) => s + m.annual, 0).toFixed(1);

  return (
    <div className="perf-flow">
      {/* ① 平面図フロー図 (元リポジトリの図を本ページデザインで再構成) */}
      <FloorPlanFlowCard/>

      {/* ② 1日あたり/年間 サマリー */}
      <div className="perf-flow-totals">
        <div className="perf-flow-total-card">
          <div className="t-eyebrow">1日あたり短縮</div>
          <div className="perf-flow-total-v">
            <span className="serif" style={{ fontSize: 48, fontWeight: 700, lineHeight: 1 }}>{totalSavedMin}</span>
            <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>分/日</span>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>6つの動線最適化の合計</div>
        </div>
        <div className="perf-flow-total-card">
          <div className="t-eyebrow">年間時間価値</div>
          <div className="perf-flow-total-v">
            <span className="serif" style={{ fontSize: 48, fontWeight: 700, lineHeight: 1 }}>{totalAnnual}</span>
            <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>万円/年</span>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>時給1,500円換算</div>
        </div>
      </div>
      <div className="perf-flow-list">
        {MOTIONS.map(m => (
          <div key={m.id} className="perf-flow-item">
            <div className="perf-flow-item-h">
              <span className="perf-flow-icon">{m.icon}</span>
              <h4 className="serif" style={{ fontSize: 16, fontWeight: 700 }}>{m.zone}</h4>
              <span className="perf-flow-save mono">-{m.saved}分/日</span>
            </div>
            <div className="perf-flow-ba">
              <div className="perf-flow-before">
                <div className="t-eyebrow" style={{ color: 'var(--negative)' }}>BEFORE</div>
                <p>{m.before}</p>
              </div>
              <div className="perf-flow-arrow">→</div>
              <div className="perf-flow-after">
                <div className="t-eyebrow" style={{ color: 'var(--positive)' }}>AFTER</div>
                <p>{m.after}</p>
              </div>
            </div>
            <ul className="perf-flow-tips">
              {m.tips.map((t,i) => <li key={i}>{t}</li>)}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
};

// ---- タブ D: コスト ---------------------------------------
const CostTab = ({ selection }) => {
  const data = window.HOUSE_DATA;
  if (!data) return null;
  const { CATS } = data;
  const rows = CATS.map(cat => {
    const opt = cat.options.find(o => o.id === selection[cat.id]) || cat.options[0];
    return { cat: cat.label, icon: cat.icon, pick: opt.label, init: opt.init, annual: opt.annual };
  });
  const initSum = rows.reduce((s,r) => s + r.init, 0);
  const annualSum = rows.reduce((s,r) => s + r.annual, 0);
  const ten = (initSum + annualSum * 10).toFixed(1);

  return (
    <div className="perf-cost">
      <div className="perf-cost-totals">
        <div className="perf-cost-total">
          <div className="t-eyebrow">初期費用 合計</div>
          <div className="perf-cost-total-v">
            <span className="serif" style={{ fontSize: 44, fontWeight: 700, lineHeight: 1 }}>{initSum}</span>
            <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>万円</span>
          </div>
        </div>
        <div className="perf-cost-total">
          <div className="t-eyebrow">年間費用 合計</div>
          <div className="perf-cost-total-v">
            <span className="serif" style={{ fontSize: 44, fontWeight: 700, lineHeight: 1 }}>{annualSum.toFixed(1)}</span>
            <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>万円/年</span>
          </div>
        </div>
        <div className="perf-cost-total accent">
          <div className="t-eyebrow">10年トータル</div>
          <div className="perf-cost-total-v">
            <span className="serif" style={{ fontSize: 44, fontWeight: 700, lineHeight: 1 }}>{ten}</span>
            <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>万円</span>
          </div>
        </div>
      </div>
      <div className="perf-cost-table">
        <div className="perf-cost-row perf-cost-head">
          <span>カテゴリ</span><span>採用</span>
          <span className="ta-r">初期</span><span className="ta-r">年間</span><span className="ta-r">10年</span>
        </div>
        {rows.map((r,i) => (
          <div key={i} className="perf-cost-row">
            <span><span style={{ marginRight: 6 }}>{r.icon}</span>{r.cat}</span>
            <span style={{ color: 'var(--ink-2)' }}>{r.pick}</span>
            <span className="ta-r mono">{r.init}</span>
            <span className="ta-r mono">{r.annual >= 0 ? r.annual : r.annual}</span>
            <span className="ta-r mono">{(r.init + r.annual * 10).toFixed(1)}</span>
          </div>
        ))}
        <div className="perf-cost-row perf-cost-foot">
          <span>合計</span><span/>
          <span className="ta-r mono">{initSum}</span>
          <span className="ta-r mono">{annualSum.toFixed(1)}</span>
          <span className="ta-r mono">{ten}</span>
        </div>
      </div>
    </div>
  );
};

// ---- タブ E: 設計指針 -------------------------------------
const GuideTab = () => {
  const data = window.HOUSE_DATA;
  if (!data) return null;
  const { OPTIMAL_ASSUMPTIONS, DECISION_RULES, RECOMMENDED_BUILD, COMFORT_SPECS } = data;
  return (
    <div className="perf-guide">
      <section className="perf-guide-section">
        <h3 className="serif" style={{ fontSize: 18, fontWeight: 700, marginBottom: 12 }}>前提条件</h3>
        <ul className="perf-guide-bullets">
          {OPTIMAL_ASSUMPTIONS.map((t,i) => <li key={i}>{t}</li>)}
        </ul>
      </section>
      <section className="perf-guide-section">
        <h3 className="serif" style={{ fontSize: 18, fontWeight: 700, marginBottom: 12 }}>意思決定ルール</h3>
        <div className="perf-guide-rules">
          {DECISION_RULES.map((r,i) => (
            <div key={i} className="perf-guide-rule">
              <div className="perf-guide-rule-num mono">{String(i+1).padStart(2,'0')}</div>
              <div>
                <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4 }}>{r.title}</div>
                <p style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>{r.body}</p>
              </div>
            </div>
          ))}
        </div>
      </section>
      <section className="perf-guide-section">
        <h3 className="serif" style={{ fontSize: 18, fontWeight: 700, marginBottom: 12 }}>推奨構成</h3>
        <div className="perf-guide-recs">
          {RECOMMENDED_BUILD.map((r,i) => (
            <div key={i} className="perf-guide-rec">
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <h4 style={{ fontSize: 13, fontWeight: 700 }}>{r.title}</h4>
                <Pill tone={r.tag === '最優先' ? 'accent' : 'good'}>{r.tag}</Pill>
              </div>
              <div style={{ fontWeight: 600, color: 'var(--accent-ink)', marginBottom: 6 }}>{r.pick}</div>
              <p style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.55, marginBottom: 6 }}>{r.body}</p>
              <p style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.55 }}><strong>準備：</strong>{r.prep}</p>
            </div>
          ))}
        </div>
      </section>
      <section className="perf-guide-section">
        <h3 className="serif" style={{ fontSize: 18, fontWeight: 700, marginBottom: 12 }}>暮らしと収納のポイント</h3>
        <div className="perf-guide-specs">
          {COMFORT_SPECS.map((s,i) => (
            <div key={i} className="perf-guide-spec">
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
                <span style={{ fontSize: 18 }}>{s.icon}</span>
                <h4 style={{ fontSize: 13, fontWeight: 700 }}>{s.title}</h4>
              </div>
              <ul>
                {s.lines.map((l,j) => <li key={j}>{l}</li>)}
              </ul>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
};

// ---- 性能タブ定義 (Layout A サイドバーからも参照) ----
const PERF_TABS = [
  { id: 'summary', label: '性能サマリー', sub: 'UA・C・日照',   icon: '📊' },
  { id: 'equip',   label: '設備選択',    sub: '10カテゴリ',      icon: '⚙️' },
  { id: 'flow',    label: '動線改善',    sub: 'BEFORE / AFTER', icon: '🚶' },
  { id: 'cost',    label: 'コスト',      sub: '初期+10年',      icon: '💰' },
  { id: 'guide',   label: '設計指針',    sub: '前提・ルール',    icon: '🧭' },
];

// ---- メイン: 性能ページ -----------------------------------
// tab / onTabChange を渡すと「外部制御モード」(タブバー非表示)
// 省略するとスタンドアロン(横タブバー付き)
const PerformancePage = ({ theme, tab: tabProp, onTabChange }) => {
  const data = window.HOUSE_DATA;
  const defaultSel = data?.DEFAULT_SELECTION || {};
  const [selection, setSelection] = useState(defaultSel);
  const [tabInternal, setTabInternal] = useState('summary');

  // 外部制御 or 内部状態
  const tab    = tabProp !== undefined ? tabProp : tabInternal;
  const setTab = onTabChange || setTabInternal;
  const isControlled = tabProp !== undefined;

  return (
    <div className="viewport perf-viewport" data-mode="perf">
      {/* スタンドアロン時のみ横タブバー表示 */}
      {!isControlled && (
        <div className="perf-tabbar">
          {PERF_TABS.map(t => (
            <button
              key={t.id}
              className={`perf-tab ${tab === t.id ? 'is-active' : ''}`}
              onClick={() => setTab(t.id)}
            >
              <span className="perf-tab-icon">{t.icon}</span>
              <span className="perf-tab-text">
                <span className="perf-tab-label">{t.label}</span>
                <span className="perf-tab-sub t-eyebrow">{t.sub}</span>
              </span>
            </button>
          ))}
        </div>
      )}
      <div className="perf-scroll">
        {tab === 'summary' && <SummaryTab/>}
        {tab === 'equip'   && <EquipmentTab selection={selection} setSelection={setSelection}/>}
        {tab === 'flow'    && <FlowTab/>}
        {tab === 'cost'    && <CostTab selection={selection}/>}
        {tab === 'guide'   && <GuideTab/>}
      </div>
    </div>
  );
};

window.HV = Object.assign(window.HV || {}, { PerformancePage, PERF_TABS });
