/* global React, HV */
/* eslint-disable */

// ─────────────────────────────────────────────
// 住宅最適設計ビジュアライザー — 3つのレイアウト案
// パネル内容は mode (外観 / 内装 / 性能) で切替
// ─────────────────────────────────────────────

const { useState, useEffect } = React;
const {
  Icon, Swatch, Section, Metric, Viewport, ModeSwitch, TopBar, StatusBar, HouseSVG, FloorPlanSVG,
  WALL_COLORS, ROOF_COLORS, SOFFIT_COLORS, FRAME_COLORS, DOOR_STYLES, CARPORT_OPTS, DECK_COLORS, LAWN_COLORS,
  projectMeta,
} = window.HV;

// ══════════════════════════════════════════════
// パネル本体: モードに応じた内容
// ══════════════════════════════════════════════
const WALL_TOGGLE_LABEL = '別色を使う';

// ── 折りたたみセクション + on/off トグル付き(壁) ──
const WallSection = ({ title, count, spec, setSpec, toggleKey, valueKey, defaultOpen }) => {
  const enabled = spec[toggleKey];
  return (
    <Section icon="paint" title={title} count={enabled ? count : null} defaultOpen={defaultOpen}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '2px 0 6px' }}>
        <label className="toggle">
          <input
            type="checkbox"
            checked={enabled}
            onChange={e => setSpec({ ...spec, [toggleKey]: e.target.checked })}
          />
          <span className="toggle-track"><span className="toggle-thumb"/></span>
          <span style={{ fontSize: 12, color: 'var(--ink-2)', fontWeight: 500 }}>{WALL_TOGGLE_LABEL}</span>
        </label>
        {!enabled && <span style={{ fontSize: 11, color: 'var(--ink-3)', marginLeft: 'auto' }}>(北側と同色)</span>}
      </div>
      {enabled && (
        <div className="swatch-grid">
          {WALL_COLORS.map(c => (
            <Swatch key={c.id} option={c} selected={spec[valueKey] === c.id} onClick={() => setSpec({ ...spec, [valueKey]: c.id })}/>
          ))}
        </div>
      )}
    </Section>
  );
};

const FinishesPanel = ({ spec, setSpec }) => (
  <div className="finishes-panel">
    <Section icon="paint" title="外壁 — 北側・玄関周り" count={WALL_COLORS.length}>
      <div className="swatch-grid">
        {WALL_COLORS.map(c => (
          <Swatch key={c.id} option={c} selected={spec.wall === c.id} onClick={() => setSpec({ ...spec, wall: c.id })}/>
        ))}
      </div>
    </Section>
    <WallSection title="外壁 — 南側／西壁(パントリー側)" count={WALL_COLORS.length}
                 spec={spec} setSpec={setSpec} toggleKey="wallSouthEnabled" valueKey="wallSouth"
                 defaultOpen={false}/>
    <WallSection title="外壁 — 玄関ポーチ突出部" count={WALL_COLORS.length}
                 spec={spec} setSpec={setSpec} toggleKey="wallPorchEnabled" valueKey="wallPorch"
                 defaultOpen={false}/>
    <WallSection title="外壁 — 段差横壁(本体↔ポーチ間)" count={WALL_COLORS.length}
                 spec={spec} setSpec={setSpec} toggleKey="wallStepEnabled" valueKey="wallStep"
                 defaultOpen={false}/>
    <Section icon="door" title="玄関ドアスタイル" defaultOpen={false}>
      <div className="swatch-grid is-list">
        {DOOR_STYLES.map(c => (
          <Swatch key={c.id} option={c} selected={spec.doorStyle === c.id} onClick={() => setSpec({ ...spec, doorStyle: c.id })}/>
        ))}
      </div>
    </Section>
    <Section icon="roof" title="屋根材" count={ROOF_COLORS.length}>
      <div className="swatch-grid">
        {ROOF_COLORS.map(c => (
          <Swatch key={c.id} option={c} selected={spec.roof === c.id} onClick={() => setSpec({ ...spec, roof: c.id })}/>
        ))}
      </div>
    </Section>
    <Section icon="paint" title="軒天" count={SOFFIT_COLORS.length} defaultOpen={false}>
      <div className="swatch-grid">
        {SOFFIT_COLORS.map(c => (
          <Swatch key={c.id} option={c} selected={spec.soffit === c.id} onClick={() => setSpec({ ...spec, soffit: c.id })}/>
        ))}
      </div>
    </Section>
    <Section icon="window" title="窓枠の色" defaultOpen={false}>
      <div className="swatch-grid">
        {FRAME_COLORS.map(c => (
          <Swatch key={c.id} option={c} selected={spec.frame === c.id} onClick={() => setSpec({ ...spec, frame: c.id })}/>
        ))}
      </div>
    </Section>
    <Section icon="tree" title="外構 — カーポート" defaultOpen={false}>
      <div className="swatch-grid is-list">
        {CARPORT_OPTS.map(c => (
          <Swatch
            key={c.id}
            option={{ ...c, hex: c.id === 'aluminum' ? '#d8e0e4' : c.id === 'wood' ? '#8a6038' : '#e8e2d6' }}
            selected={spec.carport === c.id}
            onClick={() => setSpec({ ...spec, carport: c.id })}
          />
        ))}
      </div>
    </Section>
    <Section icon="tree" title="外構 — ウッドデッキ" defaultOpen={false}>
      <div className="swatch-grid">
        {DECK_COLORS.map(c => (
          <Swatch key={c.id} option={c} selected={spec.deck === c.id} onClick={() => setSpec({ ...spec, deck: c.id })}/>
        ))}
      </div>
    </Section>
    <Section icon="tree" title="外構 — 庭面" defaultOpen={false}>
      <div className="swatch-grid">
        {LAWN_COLORS.map(c => (
          <Swatch key={c.id} option={c} selected={spec.lawn === c.id} onClick={() => setSpec({ ...spec, lawn: c.id })}/>
        ))}
      </div>
    </Section>
    <Section icon="eye" title="表示オプション" defaultOpen={false}>
      <label className="toggle" style={{ padding: '6px 0' }}>
        <input
          type="checkbox"
          checked={spec.showLabels}
          onChange={e => setSpec({ ...spec, showLabels: e.target.checked })}
        />
        <span className="toggle-track"><span className="toggle-thumb"/></span>
        <span style={{ fontSize: 12, color: 'var(--ink)', fontWeight: 500 }}>部屋名ラベルを表示(平面図モード)</span>
      </label>
    </Section>
  </div>
);

const InteriorPanel = ({ floor, setFloor }) => {
  const rooms1F = [
    { name: 'LDK',           area: 27.4, light: 92, name2: 'リビング・ダイニング・キッチン' },
    { name: '玄関',          area: 4.8,  light: 28, name2: 'シューズクロークあり' },
    { name: '畳コーナー',     area: 6.6,  light: 64, name2: '掘りごたつ風' },
    { name: '洗面・浴室',     area: 6.2,  light: 24, name2: 'UB 1620サイズ' },
    { name: 'パントリー',     area: 2.4,  light: 12, name2: 'キッチン奥' },
  ];
  const rooms2F = [
    { name: '主寝室',         area: 13.5, light: 86, name2: 'WIC付き' },
    { name: '洋室 A',         area: 8.0,  light: 70, name2: '東窓スリット' },
    { name: '洋室 B',         area: 9.6,  light: 60, name2: 'レイアウト可変' },
  ];
  const rooms = floor === '2F' ? rooms2F : rooms1F;
  return (
    <div>
      <Section icon="floor" title="階層">
        <div style={{ display: 'flex', gap: 6, padding: '0' }}>
          {['1F', '2F'].map(f => (
            <button
              key={f}
              onClick={() => setFloor(f === '1F' ? '1f' : '2f')}
              className={`tag ${(floor === '1F' ? f === '1F' : f === '2F') ? 'is-active' : ''}`}
              style={{ flex: 1, padding: '10px', fontSize: 13, fontWeight: 600 }}
            >
              {f}
            </button>
          ))}
        </div>
      </Section>
      <Section icon="floor" title={`${floor} 室一覧`} count={rooms.length}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {rooms.map(r => (
            <div key={r.name} style={{
              padding: '11px 13px',
              background: 'var(--surface-2)',
              borderRadius: 10,
              border: '1px solid var(--line-2)',
              cursor: 'pointer',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontWeight: 600, fontSize: 13 }}>{r.name}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{r.area} m²</span>
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{r.name2}</div>
              <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name="sun" size={11}/>
                <div style={{ flex: 1, height: 4, background: 'var(--bg-2)', borderRadius: 999 }}>
                  <div style={{ width: r.light + '%', height: '100%', background: 'var(--accent)', borderRadius: 999 }}/>
                </div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', width: 28, textAlign: 'right' }}>{r.light}%</span>
              </div>
            </div>
          ))}
        </div>
      </Section>
      <Section icon="spec" title="面積サマリ">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <Metric label="1F"     value="58.2" unit="m²"/>
          <Metric label="2F"     value="47.0" unit="m²"/>
          <Metric label="延床"   value="105.2" unit="m²"/>
          <Metric label="建ぺい率" value="52.9" unit="%"/>
        </div>
      </Section>
    </div>
  );
};

const PerformancePanel = () => (
  <div>
    <Section icon="sun" title="シミュレーション条件">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div className="current-value">
          <span className="current-value-label">地域区分</span>
          <span className="current-value-strong" style={{ marginLeft: 'auto' }}>6地域</span>
          <Icon name="chevDown" size={14}/>
        </div>
        <div className="current-value">
          <span className="current-value-label">基準日</span>
          <span className="current-value-strong" style={{ marginLeft: 'auto' }}>冬至 · 12/22</span>
          <Icon name="chevDown" size={14}/>
        </div>
        <div className="current-value">
          <span className="current-value-label">基準時刻</span>
          <span className="current-value-strong" style={{ marginLeft: 'auto' }}>11:00 - 14:00</span>
          <Icon name="chevDown" size={14}/>
        </div>
        <div className="current-value">
          <span className="current-value-label">気象データ</span>
          <span className="current-value-strong" style={{ marginLeft: 'auto' }}>拡張アメダス</span>
          <Icon name="chevDown" size={14}/>
        </div>
      </div>
    </Section>
    <Section icon="leaf" title="表示する項目">
      <div className="tag-row">
        <span className="tag is-active">UA値</span>
        <span className="tag is-active">C値</span>
        <span className="tag is-active">ηAC</span>
        <span className="tag is-active">日射</span>
        <span className="tag is-active">一次E</span>
        <span className="tag">壁内結露</span>
        <span className="tag">換気熱損失</span>
        <span className="tag">遮音</span>
      </div>
    </Section>
    <Section icon="sun" title="性能グレード判定" defaultOpen={false}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div className="current-value"><span className="current-value-strong">★</span><span style={{ marginLeft: 8 }}>HEAT20 G2 達成</span></div>
        <div className="current-value"><span className="current-value-strong">★</span><span style={{ marginLeft: 8 }}>ZEH 水準クリア</span></div>
        <div className="current-value"><span className="current-value-strong">★</span><span style={{ marginLeft: 8 }}>長期優良住宅 該当</span></div>
        <div className="current-value" style={{ opacity: 0.6 }}>
          <span style={{ color: 'var(--ink-3)' }}>HEAT20 G3</span>
          <span style={{ marginLeft: 8, color: 'var(--ink-3)', fontSize: 11 }}>UA 0.08 不足</span>
        </div>
      </div>
    </Section>
    <Section icon="leaf" title="エネルギー詳細" defaultOpen={false}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <Metric label="冷房" value="14.2" unit="GJ/年"/>
        <Metric label="暖房" value="18.6" unit="GJ/年"/>
        <Metric label="給湯" value="22.4" unit="GJ/年"/>
        <Metric label="家電" value="15.8" unit="GJ/年"/>
      </div>
    </Section>
    <Section icon="spec" title="改善案" defaultOpen={false}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ padding: '10px 12px', background: 'var(--surface-2)', borderRadius: 9, border: '1px solid var(--line-2)' }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)' }}>+ Low-E複層 → トリプル</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>UA -0.06 · 投資 +38万円 · 回収 12年</div>
        </div>
        <div style={{ padding: '10px 12px', background: 'var(--surface-2)', borderRadius: 9, border: '1px solid var(--line-2)' }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)' }}>+ 屋根断熱厚 200→260mm</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>UA -0.03 · 投資 +18万円 · 回収 8年</div>
        </div>
      </div>
    </Section>
  </div>
);

const SunBar = ({ label, pct, variant = 'normal' }) => {
  const gradient = variant === 'warn'
    ? 'linear-gradient(90deg, oklch(0.62 0.13 55), oklch(0.56 0.12 25))'
    : variant === 'positive'
    ? 'linear-gradient(90deg, oklch(0.55 0.08 145), oklch(0.62 0.10 110))'
    : 'linear-gradient(90deg, var(--accent), oklch(0.72 0.13 70))';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <span style={{ fontSize: 11, color: 'var(--ink-3)', width: 64, whiteSpace: 'nowrap' }}>{label}</span>
      <div style={{ flex: 1, height: 8, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: gradient, borderRadius: 999, transition: 'width 0.3s' }}/>
      </div>
      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-2)', width: 36, textAlign: 'right' }}>{pct}%</span>
    </div>
  );
};

// 現在の仕様の要約
const CurrentSummary = ({ spec, compact = false }) => {
  const find = (arr, id) => arr.find(x => x.id === id) || arr[0];
  const items = [
    { label: '外壁(北)',   v: find(WALL_COLORS, spec.wall) },
    { label: '外壁(南)',   v: find(WALL_COLORS, spec.wallSouth) },
    { label: 'ポーチ',     v: find(WALL_COLORS, spec.wallPorch) },
    { label: '屋根',       v: find(ROOF_COLORS, spec.roof) },
    { label: '軒天',       v: find(SOFFIT_COLORS, spec.soffit) },
    { label: '窓枠',       v: find(FRAME_COLORS, spec.frame) },
  ];
  return (
    <div className="current-summary" style={{ display: 'flex', flexWrap: 'nowrap', gap: 6, overflowX: 'auto', paddingBottom: 2 }}>
      {items.map(it => (
        <div key={it.label} className="spec-dot">
          <span className="spec-dot-chip" style={{ background: it.v.hex }}/>
          {!compact && <span style={{ color: '#6b6258' }}>{it.label}</span>}
          <strong style={{ color: '#241f1a' }}>{it.v.name}</strong>
        </div>
      ))}
    </div>
  );
};

// 使用素材レジェンド (中央下・横一列スクロール) — 平面図Aの凡例風
//   3Dビュー内に一列で横スクロール、デザインは .float-panel と同じガラスバー
const MaterialLegendBar = ({ spec, collapsed, onToggle }) => {
  const find = (arr, id) => arr.find(x => x.id === id) || arr[0];
  const rows = [
    { label: '外壁 北',   v: find(WALL_COLORS, spec.wall) },
    { label: '外壁 南',   v: spec.wallSouthEnabled ? find(WALL_COLORS, spec.wallSouth) : { ...find(WALL_COLORS, spec.wall), name: find(WALL_COLORS, spec.wall).name + ' (北と同色)' } },
    { label: 'ポーチ',    v: spec.wallPorchEnabled ? find(WALL_COLORS, spec.wallPorch) : { ...find(WALL_COLORS, spec.wall), name: find(WALL_COLORS, spec.wall).name + ' (北と同色)' } },
    { label: '段差横壁',  v: spec.wallStepEnabled  ? find(WALL_COLORS, spec.wallStep)  : { ...find(WALL_COLORS, spec.wall), name: find(WALL_COLORS, spec.wall).name + ' (北と同色)' } },
    { label: '屋根',      v: find(ROOF_COLORS, spec.roof) },
    { label: '軒天',      v: find(SOFFIT_COLORS, spec.soffit) },
    { label: '窓枠',      v: find(FRAME_COLORS, spec.frame) },
    { label: '玄関ドア',  v: find(DOOR_STYLES, spec.doorStyle) },
  ];

  if (collapsed) {
    return (
      <div className="material-legend-bar is-collapsed" onClick={onToggle} role="button">
        <span className="material-legend-bar-pill-text">
          <Icon name="eye" size={13}/>
          <span className="t-eyebrow">EXTERIOR MATERIAL</span>
          <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{rows.length}</span>
        </span>
      </div>
    );
  }

  return (
    <div className="material-legend-bar">
      <div className="material-legend-bar-head">
        <span className="t-eyebrow">EXTERIOR MATERIAL</span>
        <span className="material-legend-bar-count">{rows.length}</span>
      </div>
      <div className="material-legend-bar-scroll">
        {rows.map(r => (
          <span key={r.label} className="material-legend-bar-chip">
            <span className="material-legend-bar-chip-swatch" style={{ background: r.v.hex }}/>
            <span className="material-legend-bar-chip-label">{r.label}</span>
            <span className="material-legend-bar-chip-name">{r.v.name}</span>
          </span>
        ))}
      </div>
      <button className="material-legend-bar-toggle" onClick={onToggle} title="閉じる">
        <Icon name="chevDown" size={13}/>
      </button>
    </div>
  );
};

// ── パネル切替: モード -> パネル ────
const PanelContent = ({ mode, spec, setSpec, floor, setFloor }) => {
  if (mode === 'interior') return <InteriorPanel floor={floor === '2f' ? '2F' : '1F'} setFloor={setFloor}/>;
  if (mode === 'perf')     return <PerformancePanel/>;
  return <FinishesPanel spec={spec} setSpec={setSpec}/>;
};

// パネルのタイトル
const panelTitle = (mode) => {
  if (mode === 'interior') return '内装 · 部屋一覧';
  if (mode === 'perf')     return '性能 · 環境シミュレーション';
  return '外観 · 仕上げ';
};

// ════════════════════════════════════════════
// レイアウト A — 「平面図」型
// 左サイド固定パネル + 開閉ボタン
// ════════════════════════════════════════════
const LayoutA = ({ theme, onThemeToggle, density }) => {
  const [mode, setMode] = useState('exterior');
  const [viewMode, setViewMode] = useState('ext');
  const [spec, setSpec] = useState(window.HV.initialSpec);
  const [panelOpen, setPanelOpen] = useState(true);
  const [perfTab, setPerfTab] = useState('summary');

  // モード切替時に viewMode を妥当値へ
  const handleModeChange = (m) => {
    setMode(m);
    if (m === 'interior') setViewMode('1f');
    else setViewMode('ext');
  };

  // 性能モード時: サイドバーを縦タブナビに使う
  const perfTabs = window.HV.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: '🧭' },
  ];

  // サイドバー幅 (px)
  const SIDEBAR_W = 288;

  return (
    <div className={`app density-${density} is-fullbleed layout-a`}>
      <TopBar theme={theme} onThemeToggle={onThemeToggle} mode={mode} onModeChange={handleModeChange}/>
      <main style={{ position: 'relative', overflow: 'hidden' }}>

        {/* ── 3D / 性能ビュー: 全幅フルブリード ── */}
        {mode === 'perf' ? (
          /* 性能モード: 上部ツールバーに内容が隠れないよう top をオフセット、左はサイドバー分 */
          <div style={{
            position: 'absolute',
            top: 84, right: 0, bottom: 0,
            left: panelOpen ? SIDEBAR_W + 12 : 0,
            transition: 'left 0.22s',
          }}>
            <window.HV.PerformancePage theme={theme} tab={perfTab} onTabChange={setPerfTab}/>
          </div>
        ) : (
          /* 外観 / 内装: 3D が全幅に広がる */
          <div style={{ position: 'absolute', inset: 0 }}>
            <Viewport theme={theme} viewMode={viewMode} onViewModeChange={setViewMode} mode={mode} spec={spec}/>
          </div>
        )}

        {/* ── ガラスサイドバー: 左側オーバーレイ ── */}
        <aside
          className="layout-a-sidebar"
          style={{
            position: 'absolute',
            left: panelOpen ? 12 : -(SIDEBAR_W + 20),
            top: 88,
            bottom: 60,
            width: SIDEBAR_W,
            transition: 'left 0.22s cubic-bezier(0.4, 0, 0.2, 1)',
          }}
        >
          {mode === 'perf' ? (
            /* 縦タブナビ */
            <>
              <div className="panel-header" style={{ borderRadius: '16px 16px 0 0' }}>
                <div className="t-h-section">性能 · 情報</div>
                <button className="icon-btn" onClick={() => setPanelOpen(false)} title="パネルを閉じる">
                  <Icon name="chevLeft" size={16}/>
                </button>
              </div>
              <nav style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4, padding: '12px', overflowY: 'auto' }}>
                {perfTabs.map(t => (
                  <button
                    key={t.id}
                    onClick={() => setPerfTab(t.id)}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 12,
                      padding: '11px 14px',
                      borderRadius: 10,
                      border: 'none',
                      background: perfTab === t.id ? 'var(--accent)' : 'transparent',
                      color: perfTab === t.id ? '#fff' : 'var(--ink)',
                      cursor: 'pointer',
                      textAlign: 'left',
                      transition: 'background 0.15s',
                      width: '100%',
                    }}
                    onMouseEnter={e => { if (perfTab !== t.id) e.currentTarget.style.background = 'var(--surface-2)'; }}
                    onMouseLeave={e => { if (perfTab !== t.id) e.currentTarget.style.background = 'transparent'; }}
                  >
                    <span style={{ fontSize: 20 }}>{t.icon}</span>
                    <span style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                      <span style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.2 }}>{t.label}</span>
                      <span style={{ fontSize: 10, opacity: 0.72, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{t.sub}</span>
                    </span>
                  </button>
                ))}
              </nav>
            </>
          ) : (
            /* 外観 / 内装モード: スクロールパネル */
            <>
              <div className="panel-header" style={{ borderRadius: '16px 16px 0 0' }}>
                <div className="t-h-section">{panelTitle(mode)}</div>
                <button className="icon-btn" onClick={() => setPanelOpen(false)} title="パネルを閉じる">
                  <Icon name="chevLeft" size={16}/>
                </button>
              </div>
              <div className="scroll" style={{ flex: 1, minHeight: 0 }}>
                <PanelContent mode={mode} spec={spec} setSpec={setSpec} floor={viewMode} setFloor={setViewMode}/>
              </div>
              <div className="panel-foot" style={{ borderRadius: '0 0 16px 16px' }}>
                <button className="btn is-ghost" style={{ flex: 1 }}><Icon name="reset" size={14}/> 初期値</button>
                <button className="btn" style={{ flex: 1 }}><Icon name="edit" size={14}/> 寸法編集</button>
                <button className="btn is-primary" style={{ flex: 1 }}><Icon name="copy" size={14}/> 仕様コピー</button>
              </div>
            </>
          )}
        </aside>

        {/* サイドバー再表示ボタン (閉じた時) */}
        {!panelOpen && (
          <button
            onClick={() => setPanelOpen(true)}
            style={{
              position: 'absolute',
              left: 12,
              top: 88,
              zIndex: 21,
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              padding: '8px 14px',
              background: 'color-mix(in oklch, var(--surface) 88%, transparent)',
              border: '1px solid color-mix(in oklch, var(--line) 70%, transparent)',
              borderRadius: 999,
              color: 'var(--ink)',
              cursor: 'pointer',
              fontSize: 12,
              fontWeight: 600,
              backdropFilter: 'blur(12px)',
              WebkitBackdropFilter: 'blur(12px)',
              boxShadow: 'var(--shadow-md)',
            }}
          >
            <Icon name="panel" size={14}/>
            <span>{mode === 'perf' ? '性能 · 情報' : panelTitle(mode)}</span>
            <Icon name="chevRight" size={14}/>
          </button>
        )}

        {/* 外観オーバーレイ: 右側プロジェクト情報 */}
        {mode === 'exterior' && (
          <>
            <div className="quick-stat" style={{ top: 88, right: 16 }}>
              <div className="quick-stat-lbl">延床面積</div>
              <div className="quick-stat-val">168.4 <span style={{ fontSize: 11, fontWeight: 400 }}>m²</span></div>
            </div>
            <div className="quick-stat" style={{ top: 162, right: 16 }}>
              <div className="quick-stat-lbl">UA値</div>
              <div className="quick-stat-val">0.42</div>
            </div>
            <div style={{ position: 'absolute', bottom: 72, left: '50%', transform: 'translateX(-50%)', maxWidth: 'calc(100% - 320px)' }}>
              <CurrentSummary spec={spec} compact/>
            </div>
          </>
        )}
        {mode === 'interior' && (
          <div className="quick-stat" style={{ top: 88, right: 16 }}>
            <div className="quick-stat-lbl">{viewMode === '2f' ? '2F 延床' : '1F 延床'}</div>
            <div className="quick-stat-val">{viewMode === '2f' ? '47.0' : '58.2'} <span style={{ fontSize: 11, fontWeight: 400 }}>m²</span></div>
          </div>
        )}
      </main>
      <StatusBar/>
    </div>
  );
};

// ════════════════════════════════════════════
// レイアウト B — 「ドック」型 (デフォルト)
// 3D全幅フルブリード + 下部ドック + 左側ガラスサイドバー(オーバーレイ)
// 外観: サイドバー = 仕上げパネル
// 内装: サイドバー = iframe #sb (CSS注入でガラス化)
// 性能: サイドバー = 縦タブナビ + 右側にPerformancePage
// ════════════════════════════════════════════
const LayoutB = ({ theme, onThemeToggle, density }) => {
  const [mode, setMode] = useState('exterior');
  const [viewMode, setViewMode] = useState('ext');
  const [spec, setSpec] = useState(window.HV.initialSpec);
  const [panelOpen, setPanelOpen] = useState(false); // 既定: 閉じる(3Dを全画面で見せる)
  const [editOpen, setEditOpen] = useState(false);    // 寸法編集パネル(iframe側 .open に同期)
  const [perfTab, setPerfTab] = useState('summary');

  const SIDEBAR_W = 288;
  const perfTabs = window.HV.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: '🧭' },
  ];

  // iframe側の #edit-panel.open を MutationObserver で監視して React state を同期
  useEffect(() => {
    if (mode !== 'exterior') return;
    const f = document.querySelector('[data-iframe-type="exterior"]') || document.querySelector('.viewport-iframe');
    if (!f) return;
    let obs = null;
    let cancelled = false;
    const attach = () => {
      if (cancelled) return;
      try {
        const doc = f.contentDocument;
        const ep = doc?.getElementById('edit-panel');
        if (!ep) return setTimeout(attach, 200);
        setEditOpen(ep.classList.contains('open'));
        obs = new MutationObserver(() => setEditOpen(ep.classList.contains('open')));
        obs.observe(ep, { attributes: true, attributeFilter: ['class'] });
      } catch (e) { setTimeout(attach, 200); }
    };
    attach();
    const onLoad = () => attach();
    f.addEventListener('load', onLoad);
    return () => {
      cancelled = true;
      obs?.disconnect();
      f.removeEventListener('load', onLoad);
    };
  }, [mode]);

  const toggleDimensionEdit = () => {
    try {
      const f = document.querySelector('[data-iframe-type="exterior"]') || document.querySelector('.viewport-iframe');
      f?.contentWindow?.toggleEdit?.();
    } catch (e) {}
  };

  const handleModeChange = (m) => {
    setMode(m);
    if (m === 'interior') setViewMode('1f'); else setViewMode('ext');
    // 性能モードはサイドバーを自動で開く。外観/内装への切替時は閉じる
    setPanelOpen(m === 'perf');
  };

  // 寸法編集は外観(3D/平面図)時のみ
  const canEdit = mode === 'exterior';
  // 仕上げ/内装編集パネルはドックに表示するか
  const hasFinishesPanel = mode === 'exterior' || mode === 'interior';
  // 使用素材レジェンドは外観モード時のみ
  const showMaterialLegend = mode === 'exterior' && !editOpen;

  // 寸法編集パネル: iframe内の #edit-panel を .float-panel と同デザインへリスタイル
  // 開閉は iframe 側の toggleEdit に委譲（React state は別管理せず、dock-btn から直接呼ぶ）
  useEffect(() => {
    if (mode !== 'exterior') return;
    const f = document.querySelector('[data-iframe-type="exterior"]') || document.querySelector('.viewport-iframe');
    if (!f) return;
    let cancelled = false;
    const inject = () => {
      if (cancelled) return;
      try {
        const doc = f.contentDocument;
        if (!doc || !doc.body) return setTimeout(inject, 150);
        if (doc.getElementById('__edit_overlay_css')) return;
        const style = doc.createElement('style');
        style.id = '__edit_overlay_css';
        // 仕上げパネル(.float-panel) と同じデザイン: 左側フロート / 白サーフェス / 角丸16 / 影
        // 元の #edit-panel は右側fixed・濃緑ヘッダ — リスタイルして仕上げパネル形状に揃える
        // ※ 表示/非表示の transform は元実装(translateX(105%) ↔ 0)を踏襲して衝突を避ける
        style.textContent = `
          /* Position + chrome — open/close via opacity (animation-free) */
          #edit-panel {
            position: fixed !important;
            top: 88px !important;
            right: 16px !important;
            left: auto !important;
            bottom: 80px !important;
            width: 380px !important;
            max-height: calc(100vh - 168px) !important;
            z-index: 999 !important;
            background: #ffffff !important;
            color: #1a1614 !important;
            border: 1px solid #d8d0c2 !important;
            border-right: 1px solid #d8d0c2 !important;
            border-radius: 16px !important;
            box-shadow: 0 24px 48px -16px rgba(40,28,14,0.22), 0 4px 12px rgba(40,28,14,0.08) !important;
            transform: none !important;
            /* visibility は遷移に含めず即時に隠す → CSS注入直後の残像(フェード中に見える)を防ぐ */
            transition: opacity .15s ease !important;
            opacity: 0 !important;
            visibility: hidden !important;
            pointer-events: none !important;
            overflow: hidden !important;
            display: flex !important;
            flex-direction: column !important;
            padding: 0 !important;
          }
          #edit-panel.open {
            transform: none !important;
            opacity: 1 !important;
            visibility: visible !important;
            pointer-events: auto !important;
          }
          #edit-head {
            background: #faf7f1 !important;
            color: #1a1614 !important;
            border: none !important;
            border-bottom: 1px solid #e8e2d6 !important;
            padding: 14px 18px !important;
            font-family: "Shippori Mincho", "Hiragino Mincho ProN", serif !important;
            font-size: 14px !important;
            font-weight: 700 !important;
            letter-spacing: 0.02em !important;
            text-align: left !important;
            position: relative !important;
          }
          #edit-head::after {
            content: "×";
            position: absolute;
            top: 50%;
            right: 14px;
            transform: translateY(-50%);
            cursor: pointer;
            font-size: 20px;
            line-height: 1;
            color: #8a7f73;
            width: 28px; height: 28px;
            display: grid;
            place-items: center;
            border-radius: 50%;
            transition: background .12s;
            pointer-events: none;
          }
          #edit-head:hover::after { background: #ebe6dc; color: #1a1614; }
          #edit-body {
            background: #ffffff !important;
            color: #1a1614 !important;
            padding: 12px 16px !important;
            flex: 1 !important;
            overflow-y: auto !important;
          }
          #edit-body .ed-sec, #edit-body fieldset, #edit-body .ed-grp {
            background: #faf7f1 !important;
            border: 1px solid #e8e2d6 !important;
            border-radius: 10px !important;
            padding: 12px 14px !important;
            margin-bottom: 10px !important;
            color: #1a1614 !important;
          }
          #edit-body label, #edit-body .ed-label, #edit-body legend {
            color: #4a423b !important;
            font-size: 12px !important;
            font-weight: 600 !important;
          }
          #edit-body input[type="text"],
          #edit-body input[type="number"],
          #edit-body select,
          #edit-body .ed-inp {
            background: #ffffff !important;
            color: #1a1614 !important;
            border: 1px solid #d8d0c2 !important;
            border-radius: 7px !important;
            padding: 5px 9px !important;
            font-size: 12px !important;
            font-family: 'JetBrains Mono', monospace !important;
          }
          #edit-body .ed-btn, #edit-body button {
            background: #ffffff !important;
            color: #1a1614 !important;
            border: 1px solid #d8d0c2 !important;
            border-radius: 8px !important;
            padding: 7px 11px !important;
            font-size: 12px !important;
            font-weight: 600 !important;
            cursor: pointer !important;
          }
          #edit-body .ed-btn:hover, #edit-body button:hover {
            border-color: #8a7f73 !important;
            background: #faf7f1 !important;
          }
          #edit-body .ed-btn.danger {
            background: oklch(0.96 0.04 25) !important;
            color: oklch(0.40 0.12 25) !important;
            border-color: oklch(0.78 0.10 25) !important;
          }
          #edit-foot {
            background: #faf7f1 !important;
            border-top: 1px solid #e8e2d6 !important;
            padding: 12px 16px !important;
            display: flex !important;
            gap: 8px !important;
            flex-shrink: 0 !important;
          }
          #edit-foot .ed-btn { flex: 1 !important; justify-content: center !important; text-align: center !important; }
        `;
        doc.head.appendChild(style);
        // ヘッダ::after はpointer-events:noneだが、ヘッダ右端のクリックで閉じる
        const head = doc.getElementById('edit-head');
        if (head && !head.__closeBound) {
          head.__closeBound = true;
          head.addEventListener('click', (ev) => {
            const rect = head.getBoundingClientRect();
            if (ev.clientX > rect.right - 44) {
              try { f.contentWindow?.toggleEdit?.(); } catch (e) {}
            }
          });
        }
      } catch (e) { /* same-origin/timing */ }
    };
    inject();
    const onLoad = () => inject();
    f.addEventListener('load', onLoad);
    return () => { cancelled = true; f.removeEventListener('load', onLoad); };
  }, [mode]);

  // 内装モード: iframe内の編集サイドバーを仕上げパネル(.float-panel) と同デザインへリスタイル + 開閉同期
  // 内装 iframe は初回切替時に遅延生成されるため、見つかるまでリトライする
  useEffect(() => {
    if (mode !== 'interior') return;
    let cancelled = false;
    const getFrame = () => document.querySelector('[data-iframe-type="interior"]');
    const inject = () => {
      if (cancelled) return;
      const f = getFrame();
      if (!f) return setTimeout(inject, 150); // iframe が DOM に追加されるまで待つ
      try {
        const doc = f.contentDocument;
        if (!doc || !doc.body) return setTimeout(inject, 150);
        if (!doc.getElementById('__interior_overlay_css')) {
          const style = doc.createElement('style');
          style.id = '__interior_overlay_css';
          // 内装編集サイドバー: 右ガラスサイドバーとしてフロート（3D表示を隠しにくい右側）
          // top:88px bottom:132px right:12px width:288px — ドックの上に収まる高さ
          style.textContent = `
            #main { padding-right: 0 !important; padding-left: 0 !important; }
            #sb {
              position: fixed !important;
              top: 88px !important;
              right: 12px !important;
              bottom: 132px !important;
              left: auto !important;
              width: 288px !important;
              z-index: 999 !important;
              background: rgba(250,247,241,0.92) !important;
              color: #1a1614 !important;
              border: 1px solid rgba(216,208,194,0.70) !important;
              border-radius: 16px !important;
              box-shadow: 0 24px 48px -16px rgba(40,28,14,0.18), 0 4px 12px rgba(40,28,14,0.06) !important;
              -webkit-backdrop-filter: blur(18px) saturate(150%) !important;
              backdrop-filter: blur(18px) saturate(150%) !important;
              transition: transform .22s cubic-bezier(0.4,0,0.2,1), opacity .18s !important;
              padding: 14px !important;
              gap: 8px !important;
              overflow-y: auto;
            }
            body.__panel-closed #sb {
              transform: translateX(calc(100% + 24px)) !important;
              opacity: 0 !important;
              pointer-events: none !important;
            }
            #sb .sb-title {
              background: transparent !important;
              border: none !important;
              color: #1a1614 !important;
              font-family: "Shippori Mincho", "Hiragino Mincho ProN", serif !important;
              font-size: 14px !important;
              font-weight: 700 !important;
              letter-spacing: 0.02em !important;
              padding: 4px 4px 8px !important;
              border-bottom: 1px solid #e8e2d6 !important;
              text-align: left !important;
              margin-bottom: 6px !important;
            }
            #sb .sb-link {
              background: oklch(0.93 0.025 105) !important;
              color: oklch(0.30 0.05 105) !important;
              border: 1px solid oklch(0.78 0.04 105) !important;
              border-radius: 9px !important;
              font-size: 12px !important;
              padding: 9px 12px !important;
              font-weight: 600 !important;
            }
            #sb .sb-link:hover {
              background: oklch(0.88 0.04 105) !important;
              color: oklch(0.25 0.05 105) !important;
            }
            #sb .sec {
              background: #faf7f1 !important;
              border: 1px solid #e8e2d6 !important;
              border-radius: 10px !important;
              padding: 10px 12px !important;
              color: #1a1614 !important;
            }
            #sb .sec-h {
              color: #8a7f73 !important;
              border-bottom: 1px solid #e8e2d6 !important;
              font-weight: 700 !important;
              font-size: 10px !important;
              letter-spacing: 0.1em !important;
              padding-bottom: 6px !important;
              margin-bottom: 8px !important;
            }
            #sb .sec-h::after { color: #b8ada0 !important; }
            #sb .room-btn, #sb .light-btn, #sb .vp-btn {
              background: #ffffff !important;
              color: #4a423b !important;
              border: 1px solid #d8d0c2 !important;
              border-radius: 7px !important;
              font-size: 12px !important;
              padding: 8px 6px !important;
              font-weight: 500 !important;
            }
            #sb .room-btn:hover, #sb .light-btn:hover, #sb .vp-btn:hover {
              background: #faf7f1 !important;
              border-color: #8a7f73 !important;
              color: #1a1614 !important;
            }
            #sb .room-btn.act, #sb .light-btn.act {
              background: oklch(0.93 0.025 105) !important;
              color: oklch(0.30 0.05 105) !important;
              border-color: oklch(0.52 0.07 105) !important;
              font-weight: 700 !important;
            }
            #sb .sw {
              border-radius: 7px !important;
              box-shadow: 0 0 0 1px rgba(0,0,0,0.08), inset 0 -8px 16px rgba(0,0,0,0.15);
            }
            #sb .sw:hover {
              border-color: oklch(0.52 0.07 105) !important;
            }
            #sb .sw.sel {
              border-color: oklch(0.52 0.07 105) !important;
              box-shadow: 0 0 0 2px oklch(0.52 0.07 105), inset 0 -8px 16px rgba(0,0,0,0.15) !important;
            }
            #sb .sw-lbl {
              color: #8a7f73 !important;
              font-weight: 500 !important;
            }
            #sb .sw-col:hover .sw-lbl { color: #1a1614 !important; }
            #sb .ap-row, #sb .furn-row {
              color: #4a423b !important;
              font-size: 11px !important;
            }
            #sb .ap-inp, #sb .furn-inp {
              background: #ffffff !important;
              color: #1a1614 !important;
              border: 1px solid #d8d0c2 !important;
              border-radius: 6px !important;
              font-family: 'JetBrains Mono', monospace !important;
            }
            #sb .save-btn {
              border-radius: 8px !important;
              font-size: 12px !important;
              padding: 9px !important;
            }
            #sb .save-btn.primary {
              background: oklch(0.55 0.08 145) !important;
              color: #ffffff !important;
              border-color: oklch(0.55 0.08 145) !important;
            }
            #sb .save-btn.secondary {
              background: #ffffff !important;
              color: #4a423b !important;
              border-color: #d8d0c2 !important;
            }
            #sb .save-btn.danger {
              background: oklch(0.96 0.04 25) !important;
              color: oklch(0.40 0.12 25) !important;
              border-color: oklch(0.78 0.10 25) !important;
            }
            #sb .chip {
              background: #faf7f1 !important;
              border: 1px solid #e8e2d6 !important;
              color: #4a423b !important;
            }
            /* スクロールバー */
            #sb::-webkit-scrollbar { width: 8px; }
            #sb::-webkit-scrollbar-track { background: transparent; }
            #sb::-webkit-scrollbar-thumb { background: #b8ada0; border-radius: 4px; border: 2px solid #ffffff; }
          `;
          doc.head.appendChild(style);
        }
        doc.body.classList.toggle('__panel-closed', !panelOpen);
        // load イベントを iframe に登録（inject のたびに付け直さないよう一度だけ）
        if (!f.__intLoadBound) {
          f.__intLoadBound = true;
          f.addEventListener('load', () => { if (!cancelled) inject(); });
        }
      } catch (e) { /* same-origin/timing */ }
    };
    inject();
    return () => { cancelled = true; };
  }, [mode, panelOpen]);

  return (
    <div className={`app density-${density} is-fullbleed`}>
      <TopBar theme={theme} onThemeToggle={onThemeToggle} mode={mode} onModeChange={handleModeChange} showModeSwitch={false}/>
      <main style={{ position: 'relative', overflow: 'hidden' }}>

        {/* ── 3D / 性能ビュー: 全幅フルブリード ── */}
        {mode === 'perf' ? (
          /* 性能モード: 上部ツールバーに内容が隠れないよう top をオフセット、左はサイドバー分 */
          <div style={{
            position: 'absolute',
            top: 84, right: 0, bottom: 0,
            left: panelOpen ? SIDEBAR_W + 12 : 0,
            transition: 'left 0.22s',
          }}>
            <window.HV.PerformancePage theme={theme} tab={perfTab} onTabChange={setPerfTab}/>
          </div>
        ) : (
          /* 絶対配置ラッパーで明示的に親いっぱいに広げる (height:100% が確実に解決するよう) */
          <div style={{ position: 'absolute', inset: 0 }}>
            <Viewport theme={theme} viewMode={viewMode} onViewModeChange={setViewMode} mode={mode} spec={spec}/>
          </div>
        )}

        {/* ── ガラスサイドバー: 外観(仕上げ)=右側 / 性能(縦タブ)=左側 ── */}
        {/* 外観は建物が左寄りに描画されるため、仕上げパネルは右に置いて建物を隠さない */}
        {/* 内装モードは iframe #sb が代わりに同位置(右)に表示される */}
        {(mode === 'exterior' || mode === 'perf') && (
          <aside
            className="layout-a-sidebar"
            style={{
              position: 'absolute',
              top: 88,
              bottom: 132,   /* ドックの上 */
              width: SIDEBAR_W,
              /* 閉じている時は描画自体を止め、モード切替(左右入替)時の残像を防ぐ */
              visibility: panelOpen ? 'visible' : 'hidden',
              ...(mode === 'exterior'
                ? { right: panelOpen ? 12 : -(SIDEBAR_W + 20), transition: 'right 0.22s cubic-bezier(0.4,0,0.2,1)' }
                : { left:  panelOpen ? 12 : -(SIDEBAR_W + 20), transition: 'left 0.22s cubic-bezier(0.4,0,0.2,1)' }),
            }}
          >
            {mode === 'perf' ? (
              /* 縦タブナビ */
              <>
                <div className="panel-header" style={{ borderRadius: '16px 16px 0 0' }}>
                  <div className="t-h-section">性能 · 情報</div>
                  <button className="icon-btn" onClick={() => setPanelOpen(false)} title="パネルを閉じる">
                    <Icon name="chevLeft" size={16}/>
                  </button>
                </div>
                <nav style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4, padding: '12px', overflowY: 'auto' }}>
                  {perfTabs.map(t => (
                    <button
                      key={t.id}
                      onClick={() => setPerfTab(t.id)}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 12,
                        padding: '11px 14px', borderRadius: 10, border: 'none', width: '100%',
                        background: perfTab === t.id ? 'var(--accent)' : 'transparent',
                        color: perfTab === t.id ? '#fff' : 'var(--ink)',
                        cursor: 'pointer', textAlign: 'left', transition: 'background 0.15s',
                      }}
                      onMouseEnter={e => { if (perfTab !== t.id) e.currentTarget.style.background = 'var(--surface-2)'; }}
                      onMouseLeave={e => { if (perfTab !== t.id) e.currentTarget.style.background = 'transparent'; }}
                    >
                      <span style={{ fontSize: 20 }}>{t.icon}</span>
                      <span style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.2 }}>{t.label}</span>
                        <span style={{ fontSize: 10, opacity: 0.72, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{t.sub}</span>
                      </span>
                    </button>
                  ))}
                </nav>
              </>
            ) : (
              /* 外観: 仕上げパネル */
              <>
                <div className="panel-header" style={{ borderRadius: '16px 16px 0 0' }}>
                  <div className="t-h-section">外観 · 仕上げ</div>
                  <button className="icon-btn" onClick={() => setPanelOpen(false)} title="パネルを閉じる">
                    <Icon name="close" size={14}/>
                  </button>
                </div>
                <div className="scroll" style={{ flex: 1, minHeight: 0 }}>
                  <PanelContent mode={mode} spec={spec} setSpec={setSpec} floor={viewMode} setFloor={setViewMode}/>
                </div>
              </>
            )}
          </aside>
        )}

        {/* 使用素材レジェンド: Layout A 平面図と同じ spec-dot スタイル */}
        {showMaterialLegend && (
          <div style={{
            position: 'absolute',
            bottom: 148,
            left: '50%',
            transform: 'translateX(-50%)',
            maxWidth: 'calc(100% - 340px)',
            zIndex: 12,
          }}>
            <CurrentSummary spec={spec} compact/>
          </div>
        )}

        {/* 右上: プロジェクト情報（右側のパネル類と重なるので編集/仕上げ表示中は隠す） */}
        {mode === 'exterior' && !editOpen && !panelOpen && (
          <div className="project-info-card">
            <div className="t-eyebrow">PROJECT</div>
            <div className="serif" style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.25 }}>{projectMeta.client}</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 6 }}>
              <Metric label="延床" value="168.4" unit="m²"/>
              <Metric label="UA値" value="0.42" unit="W/m²K"/>
            </div>
          </div>
        )}

        {/* Bottom dock */}
        <div className="dock">
          <button className={`dock-btn ${mode === 'exterior' ? 'is-active' : ''}`} onClick={() => handleModeChange('exterior')}>
            <Icon name="cube" size={18}/>
            <span className="dock-btn-label">外観</span>
          </button>
          <button className={`dock-btn ${mode === 'interior' ? 'is-active' : ''}`} onClick={() => handleModeChange('interior')}>
            <Icon name="floor" size={18}/>
            <span className="dock-btn-label">内装</span>
          </button>
          <button className={`dock-btn ${mode === 'perf' ? 'is-active' : ''}`} onClick={() => handleModeChange('perf')}>
            <Icon name="sun" size={18}/>
            <span className="dock-btn-label">性能</span>
          </button>
          {hasFinishesPanel && (<>
            <div className="dock-divider"/>
            <button
              className={`dock-btn ${panelOpen ? 'is-active' : ''}`}
              onClick={() => { setPanelOpen(!panelOpen); if (!panelOpen && editOpen) toggleDimensionEdit(); }}
              title={mode === 'interior' ? '壁クロス・床・家具などを編集' : '外壁・屋根などの仕上げを編集'}
            >
              <Icon name="paint" size={18}/>
              <span className="dock-btn-label">{mode === 'interior' ? '内装編集' : '仕上げ'}</span>
            </button>
          </>)}
          {mode === 'perf' && (<>
            <div className="dock-divider"/>
            <button
              className={`dock-btn ${panelOpen ? 'is-active' : ''}`}
              onClick={() => setPanelOpen(!panelOpen)}
              title="性能・情報のタブ一覧を開閉"
            >
              <Icon name="panel" size={18}/>
              <span className="dock-btn-label">タブ</span>
            </button>
          </>)}
          {canEdit && (
            <button
              className={`dock-btn ${editOpen ? 'is-active' : ''}`}
              title="寸法・窓・配置の手動修正"
              onClick={() => { toggleDimensionEdit(); if (!editOpen) setPanelOpen(false); }}
            >
              <Icon name="edit" size={18}/>
              <span className="dock-btn-label">寸法編集</span>
            </button>
          )}
          <div className="dock-divider"/>
          <button className="dock-btn" title="現在の仕様をクリップボードへコピー">
            <Icon name="copy" size={18}/>
            <span className="dock-btn-label">仕様コピー</span>
          </button>
          <button className="dock-btn" title="PDFをエクスポート">
            <Icon name="download" size={18}/>
            <span className="dock-btn-label">PDF</span>
          </button>
        </div>
      </main>
      <StatusBar/>
    </div>
  );
};

// ════════════════════════════════════════════
// レイアウト C — 「アトリエ」型
// 没入ビュー + 右端ドロワー
// ════════════════════════════════════════════
const LayoutC = ({ theme, onThemeToggle, density }) => {
  const [mode, setMode] = useState('exterior');
  const [viewMode, setViewMode] = useState('ext');
  const [spec, setSpec] = useState(window.HV.initialSpec);
  const [panelOpen, setPanelOpen] = useState(true);

  const handleModeChange = (m) => {
    setMode(m);
    if (m === 'interior') setViewMode('1f'); else setViewMode('ext');
    setPanelOpen(true);
  };

  const drawerWidth = panelOpen ? 380 : 0;

  return (
    <div className={`app density-${density}`}>
      <TopBar theme={theme} onThemeToggle={onThemeToggle} mode={mode} onModeChange={handleModeChange}/>
      <main style={{ position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, transition: 'right 0.25s', right: drawerWidth }}>
          <Viewport theme={theme} viewMode={viewMode} onViewModeChange={setViewMode} mode={mode} spec={spec} chromeStyle="floating"/>

          {/* 左下 overlay: 現在の状態 (perfモードはダッシュボードが全画面なので非表示) */}
          {mode !== 'perf' && (
          <div className="float-panel" style={{ left: 16, bottom: 16, width: 380 }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <div>
                <div className="t-eyebrow">{mode === 'exterior' ? 'CURRENT SCHEME' : 'FLOOR PLAN'}</div>
                <h3 className="serif" style={{ fontSize: 17, marginTop: 2 }}>
                  {mode === 'exterior' && 'A案 · ダークオリーブ基調'}
                  {mode === 'interior' && (viewMode === '2f' ? '2階 · 主寝室 + 洋室2室' : '1階 · LDK + 玄関 + 水回り')}
                </h3>
              </div>
            </div>
            {mode === 'exterior' && <CurrentSummary spec={spec} compact/>}
            {mode === 'interior' && (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                <Metric label="1F" value="58.2" unit="m²"/>
                <Metric label="2F" value="47.0" unit="m²"/>
                <Metric label="延床" value="105.2" unit="m²"/>
              </div>
            )}
          </div>
          )}

          {/* Drawer tabs (when drawer closed) */}
          {!panelOpen && (
            <button className="drawer-tab" style={{ top: 16, right: 16 }} onClick={() => setPanelOpen(true)}>
              <Icon name="panel" size={14}/> {panelTitle(mode)}
              <Icon name="chevLeft" size={14}/>
            </button>
          )}
        </div>

        {/* Drawer */}
        {panelOpen && (
          <aside
            className="drawer"
            style={{
              top: 16, right: 16, bottom: 16,
              width: drawerWidth - 32,
              animation: 'slideUp 0.18s ease',
            }}
          >
            <div className="panel-header" style={{ borderBottom: '1px solid var(--line)' }}>
              <div className="t-h-section">{panelTitle(mode)}</div>
              <button className="icon-btn" onClick={() => setPanelOpen(false)} title="パネルを閉じる">
                <Icon name="close" size={16}/>
              </button>
            </div>
            <div className="scroll" style={{ flex: 1 }}>
              <PanelContent mode={mode} spec={spec} setSpec={setSpec} floor={viewMode} setFloor={setViewMode}/>
            </div>
            <div className="panel-foot">
              <button className="btn is-ghost" style={{ flex: 1 }}><Icon name="reset" size={14}/> 初期値</button>
              <button className="btn is-primary" style={{ flex: 1 }}><Icon name="copy" size={14}/> 仕様コピー</button>
            </div>
          </aside>
        )}
      </main>
      <StatusBar/>
    </div>
  );
};

Object.assign(window.HV, {
  LayoutA, LayoutB, LayoutC,
  FinishesPanel, PerformancePanel, InteriorPanel, CurrentSummary,
});
