// Pachi — additional screens and global state
// Mounted into window so screens.jsx can reference them.

const { useState: useStateExtra, useEffect: useEffectExtra } = React;

// ─── Global favorites store (in-memory across the App instance) ───
window.PACHI_STATE = window.PACHI_STATE || {
  favoriteShops: new Set(),
  favoriteMachines: new Set(['hokuto-247']),
  favoriteEvents: new Set(['tenkai']),
};

// ─── Generic empty/list screen ───
function PageHeader({ kicker, title, subtitle }) {
  return (
    <div style={{ margin: '14px 12px 16px' }}>
      {kicker && (
        <div style={{
          color: PACHI_TOKENS.gold, fontSize: 9, letterSpacing: 4, fontWeight: 700,
          fontFamily: '"Bebas Neue", system-ui', textTransform: 'uppercase',
          opacity: 0.8,
        }}>{kicker}</div>
      )}
      <h2 style={{
        margin: '4px 0 0', color: PACHI_TOKENS.gold, fontSize: 22, fontWeight: 900,
        fontFamily: '"Noto Sans JP", system-ui', letterSpacing: 0.5,
        textShadow: '0 0 10px rgba(245,197,66,0.5), 0 1px 0 #000',
      }}>{title}</h2>
      {subtitle && (
        <div style={{
          color: PACHI_TOKENS.textMid, fontSize: 12, marginTop: 4,
          fontFamily: '"Noto Sans JP", system-ui',
        }}>{subtitle}</div>
      )}
      <div style={{
        height: 1, marginTop: 10,
        background: 'linear-gradient(90deg, #f5c542 0%, transparent 80%)',
      }} />
    </div>
  );
}

// ─── Hall list screen ───
function HallListScreen({ nav, params = {} }) {
  const D = window.PACHI_DATA;
  const [filter, setFilter] = useStateExtra('all');
  const filters = [
    { id: 'all',     label: 'すべて' },
    { id: 'today',   label: '本日イベント' },
    { id: 'fav',     label: 'お気に入り' },
    { id: 'rating',  label: '評価高い順' },
  ];
  let shops = [...D.shops];
  if (filter === 'today')  shops = shops.filter(s => s.todayEvent);
  if (filter === 'fav')    shops = shops.filter(s => window.PACHI_STATE.favoriteShops.has(s.id));
  if (filter === 'rating') shops = shops.sort((a, b) => b.rating - a.rating);

  return (
    <Screen activeTab="hall" nav={nav}>
      <Header title="ホール検索" onBack={() => nav.back()} />
      <PageHeader kicker="HALL SEARCH" title={params.areaLabel ? `${params.areaLabel}のホール` : '近くのホール'}
        subtitle={`${shops.length} 件 ・ 並び順: ${filters.find(f => f.id === filter)?.label}`} />

      {/* Filter chips */}
      <div style={{
        display: 'flex', gap: 6, padding: '0 12px 12px', overflowX: 'auto',
      }}>
        {filters.map(f => {
          const on = f.id === filter;
          return (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              flexShrink: 0,
              background: on ? 'linear-gradient(180deg, #f5c542, #8a6914)' : 'transparent',
              color: on ? '#1a0606' : PACHI_TOKENS.gold,
              border: `1px solid ${PACHI_TOKENS.gold}`,
              padding: '9px 14px', fontSize: 12, fontWeight: 900, cursor: 'pointer',
              fontFamily: '"Noto Sans JP", system-ui',
            }}>{f.label}</button>
          );
        })}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {shops.map(s => (
          <StoreCard key={s.id} shop={s} onClick={() => nav.go('store', { shopId: s.id })} />
        ))}
        {shops.length === 0 && (
          <EmptyState text="該当するホールがありません" />
        )}
      </div>
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─── Store detail screen ───
function StoreDetailScreen({ nav, params }) {
  const D = window.PACHI_DATA;
  const shop = D.shops.find(s => s.id === params.shopId) || D.shops[0];
  const [, force] = useStateExtra(0);
  const isFav = window.PACHI_STATE.favoriteShops.has(shop.id);

  const machines = D.machines.slice(0, 9);
  // pick 4 numbers per machine
  const dataKeys = Object.keys(D.machineData);

  return (
    <Screen activeTab="hall" nav={nav}>
      <Header title="店舗詳細" onBack={() => nav.back()} />

      {/* Brand hero */}
      <div style={{
        margin: '12px 12px 0', position: 'relative',
        border: `2px solid ${PACHI_TOKENS.gold}`,
        boxShadow: '0 0 24px rgba(224,37,43,0.4), 0 6px 18px rgba(0,0,0,0.6)',
        aspectRatio: '16/9', overflow: 'hidden',
        background: '#000',
      }}>
        <img src={shop.image} alt="" style={{
          width: '100%', height: '100%', objectFit: 'cover', display: 'block',
        }} />
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, transparent 40%, rgba(0,0,0,0.85) 100%)',
        }} />
        <div style={{
          position: 'absolute', bottom: 10, left: 12, right: 12,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Stars rating={shop.rating} />
            <span style={{ color: PACHI_TOKENS.gold, fontSize: 12, fontWeight: 900 }}>{shop.rating}</span>
            <span style={{ color: PACHI_TOKENS.textDim, fontSize: 11 }}>({shop.ratingCount}件)</span>
          </div>
          <div style={{
            color: PACHI_TOKENS.gold, fontSize: 18, fontWeight: 900,
            fontFamily: '"Noto Sans JP", system-ui',
            textShadow: '0 0 8px rgba(245,197,66,0.6), 0 1px 0 #000',
          }}>{shop.name}</div>
        </div>
        <CornerTicks />
      </div>

      {/* Action row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, padding: '12px' }}>
        <button onClick={() => {
          if (isFav) window.PACHI_STATE.favoriteShops.delete(shop.id);
          else window.PACHI_STATE.favoriteShops.add(shop.id);
          force(x => x + 1);
        }} style={{
          padding: '12px 0',
          background: isFav ? 'linear-gradient(180deg, #f5c542, #8a6914)' : 'transparent',
          color: isFav ? '#1a0606' : PACHI_TOKENS.gold,
          border: `1px solid ${PACHI_TOKENS.gold}`,
          fontSize: 12, fontWeight: 900, cursor: 'pointer',
          fontFamily: '"Noto Sans JP", system-ui',
        }}><span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}><Icon name="star" size={15} fill={isFav} />{isFav ? 'お気に入り登録済' : 'お気に入りに追加'}</span></button>
        <button style={{
          padding: '12px 0',
          background: 'linear-gradient(180deg, #2a0d0e, #0a0303)',
          color: PACHI_TOKENS.gold,
          border: `1px solid ${PACHI_TOKENS.gold}`,
          fontSize: 12, fontWeight: 900, cursor: 'pointer',
          fontFamily: '"Noto Sans JP", system-ui',
        }}><span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}><Icon name="phone" size={15} />電話で問い合わせ</span></button>
      </div>

      {/* Info */}
      <SectionHeader kicker="STORE INFO" title="店舗情報" />
      <GoldFrame style={{ margin: '0 12px', padding: '12px 14px' }}>
        <InfoRow label="住所" value={shop.address} />
        <InfoRow label="アクセス" value={shop.station} />
        <InfoRow label="営業時間" value={shop.openHours} />
        <InfoRow label="設置台数" value={`パチスロ ${shop.slotCount}台`} />
        <InfoRow label="エリア" value={shop.area} last />
      </GoldFrame>

      {/* Today's machines */}
      <SectionHeader kicker="TODAY" title="本日の出玉ランキング" action="全台" />
      <div style={{ margin: '0 12px' }}>
        <GoldFrame>
          {dataKeys.concat(['hokuto-247','monkeyturn-112']).slice(0, 5).map((k, i) => {
            const md = D.machineData[k];
            const m  = D.machines.find(x => x.id === md.machineId);
            return (
              <div key={i} onClick={() => nav.go('data', { shopId: shop.id, machineKey: k })} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                borderTop: i === 0 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
                cursor: 'pointer',
              }}>
                <div style={{
                  width: 26, height: 26, display: 'grid', placeItems: 'center',
                  background: i < 3 ? 'linear-gradient(135deg, #f5c542, #8a6914)' : 'transparent',
                  border: `1px solid ${i < 3 ? PACHI_TOKENS.gold : PACHI_TOKENS.goldDim}`,
                  color: i < 3 ? '#1a0606' : PACHI_TOKENS.gold,
                  fontSize: 13, fontWeight: 900, fontFamily: '"Bebas Neue", system-ui',
                  flexShrink: 0,
                }}>{i + 1}</div>
                <img src={m.thumbnail} style={{ width: 36, height: 40, objectFit: 'cover', border: `1px solid ${PACHI_TOKENS.goldDim}`, flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ color: PACHI_TOKENS.gold, fontSize: 12, fontWeight: 900,
                    fontFamily: '"Noto Sans JP", system-ui',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  }}>{m.name}</div>
                  <div style={{ color: PACHI_TOKENS.textDim, fontSize: 11 }}>{md.machineNumber}番台</div>
                </div>
                <div style={{
                  color: md.payoutDiff >= 0 ? PACHI_TOKENS.red : '#3070d8',
                  fontSize: 16, fontWeight: 900, fontFamily: '"Bebas Neue", system-ui',
                  letterSpacing: 1,
                  textShadow: `0 0 6px ${md.payoutDiff >= 0 ? 'rgba(224,37,43,0.5)' : 'rgba(48,112,216,0.5)'}`,
                }}>{md.payoutDiff > 0 ? '+' : ''}{md.payoutDiff.toLocaleString()}<span style={{ fontSize: 9, marginLeft: 1, color: PACHI_TOKENS.textDim }}>枚</span></div>
              </div>
            );
          })}
        </GoldFrame>
      </div>

      <SectionHeader kicker="MACHINES" title="設置機種" action="全機種" />
      <MachineThumbnailGrid machines={machines} columns={3}
        onSelect={(m) => nav.go('data', { shopId: shop.id, machineKey: m.id === 'monkeyturn' ? 'monkeyturn-112' : 'hokuto-247' })} />

      <div style={{ height: 24 }} />
    </Screen>
  );
}

function InfoRow({ label, value, last }) {
  return (
    <div style={{
      display: 'flex', gap: 12, padding: '8px 0',
      borderBottom: last ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
    }}>
      <span style={{
        color: PACHI_TOKENS.textDim, fontSize: 12, fontWeight: 700, width: 76, flexShrink: 0,
        fontFamily: '"Noto Sans JP", system-ui',
      }}>{label}</span>
      <span style={{
        color: PACHI_TOKENS.textHi, fontSize: 13, flex: 1,
        fontFamily: '"Noto Sans JP", system-ui',
      }}>{value}</span>
    </div>
  );
}

// ─── Machine list (full grid w/ filter) ───
function MachineListScreen({ nav }) {
  const D = window.PACHI_DATA;
  const [maker, setMaker] = useStateExtra('all');
  const makers = ['all', ...new Set(D.machines.map(m => m.maker))];
  const filtered = maker === 'all' ? D.machines : D.machines.filter(m => m.maker === maker);

  return (
    <Screen activeTab="machine" nav={nav}>
      <Header title="機種一覧" onBack={() => nav.back()} />
      <PageHeader kicker="MACHINE LIST" title="全機種" subtitle={`${filtered.length} 機種`} />

      <div style={{ display: 'flex', gap: 6, padding: '0 12px 12px', overflowX: 'auto' }}>
        {makers.map(mk => {
          const on = mk === maker;
          return (
            <button key={mk} onClick={() => setMaker(mk)} style={{
              flexShrink: 0,
              background: on ? 'linear-gradient(180deg, #e0252b, #6a0509)' : 'transparent',
              color: on ? '#fff' : PACHI_TOKENS.gold,
              border: `1px solid ${PACHI_TOKENS.gold}`,
              padding: '9px 16px', fontSize: 12, fontWeight: 900, cursor: 'pointer',
              fontFamily: '"Noto Sans JP", system-ui',
            }}>{mk === 'all' ? 'すべて' : mk}</button>
          );
        })}
      </div>

      <MachineThumbnailGrid machines={filtered} columns={3}
        onSelect={(m) => nav.go('data', { shopId: 'konibet-shinjuku', machineKey: m.id === 'monkeyturn' ? 'monkeyturn-112' : 'hokuto-247' })} />

      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─── Settings: toggle switch ───
function Toggle({ on, onChange }) {
  return (
    <button onClick={onChange} aria-pressed={on} style={{
      width: 44, height: 24, flexShrink: 0, cursor: 'pointer', padding: 0,
      borderRadius: 12, position: 'relative',
      border: `1px solid ${on ? PACHI_TOKENS.gold : PACHI_TOKENS.hairline}`,
      background: on ? 'linear-gradient(180deg, #f5c542, #8a6914)' : '#1a0708',
      transition: 'all 0.15s',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 22 : 2,
        width: 18, height: 18, borderRadius: '50%',
        background: on ? '#1a0606' : '#6b5a34',
        transition: 'left 0.15s',
      }} />
    </button>
  );
}

// ─── Settings: modal content per row ───
const SETTINGS_TEXT = {
  '利用規約': [
    ['第1条（適用）', '本規約は、当サイト（以下「本サービス」）の提供条件および利用者と運営者との間の権利義務関係を定めるものです。'],
    ['第2条（利用登録）', '本サービスは店舗・機種・イベント情報の閲覧を目的とし、掲載情報の正確性・最新性を保証するものではありません。'],
    ['第3条（禁止事項）', '法令または公序良俗に違反する行為、本サービスの運営を妨害する行為、他の利用者に不利益を与える行為を禁止します。'],
    ['第4条（免責）', '掲載された営業情報・設定示唆等に基づく利用者の行動について、運営者は一切の責任を負いません。'],
    ['第5条（規約の変更）', '運営者は必要と判断した場合、利用者に通知することなく本規約を変更できるものとします。'],
  ],
  'プライバシーポリシー': [
    ['取得する情報', '本サービスはお気に入り登録・通知設定等の情報を端末内（localStorage）に保存します。個人を特定する情報の送信は行いません。'],
    ['利用目的', '取得した情報は、お気に入り表示・通知の出し分け等、利便性向上のためにのみ利用します。'],
    ['第三者提供', '法令に基づく場合を除き、取得した情報を第三者へ提供することはありません。'],
    ['アクセス解析', 'サービス改善のため匿名のアクセス統計を利用する場合があります。個人を識別する用途では利用しません。'],
    ['お問い合わせ', '本ポリシーに関するお問い合わせは、設定内の「お問い合わせ」よりご連絡ください。'],
  ],
};

function SettingsModal({ which, onClose, nav, notif, setNotif }) {
  const [sent, setSent] = useStateExtra(false);
  useEffectExtra(() => { setSent(false); }, [which]);
  if (!which) return null;

  let body = null;
  if (which === 'アカウント設定') {
    body = (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[['ニックネーム', 'ゲストユーザー'], ['ID', 'P-000123'], ['会員ランク', 'ブロンズ'], ['登録メール', 'guest@example.com']].map(([k, v]) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '10px 0', borderBottom: `1px solid ${PACHI_TOKENS.hairline}` }}>
            <span style={{ color: PACHI_TOKENS.textDim, fontSize: 12 }}>{k}</span>
            <span style={{ color: PACHI_TOKENS.textHi, fontSize: 13, fontWeight: 700 }}>{v}</span>
          </div>
        ))}
        <div style={{ color: PACHI_TOKENS.textDim, fontSize: 11, marginTop: 4 }}>
          ※ 会員機能は準備中です。現在はゲストとしてご利用いただけます。
        </div>
      </div>
    );
  } else if (which === '通知設定') {
    const rows = [['event', 'イベント・新台情報'], ['favorite', 'お気に入りホールの更新'], ['ranking', 'ランキング更新のお知らせ']];
    body = (
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {rows.map(([key, label], i) => (
          <div key={key} style={{ display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 0', borderTop: i === 0 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}` }}>
            <span style={{ flex: 1, color: PACHI_TOKENS.textHi, fontSize: 13 }}>{label}</span>
            <Toggle on={!!notif[key]} onChange={() => setNotif({ ...notif, [key]: !notif[key] })} />
          </div>
        ))}
        <div style={{ color: PACHI_TOKENS.textDim, fontSize: 11, marginTop: 8 }}>
          設定はこの端末に保存されます。
        </div>
      </div>
    );
  } else if (which === 'お問い合わせ') {
    body = sent ? (
      <div style={{ textAlign: 'center', padding: '18px 0' }}>
        <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'center' }}>
          <Icon name="check" size={32} color={PACHI_TOKENS.gold} />
        </div>
        <div style={{ color: PACHI_TOKENS.textHi, fontSize: 13 }}>送信しました。お問い合わせありがとうございます。</div>
      </div>
    ) : (
      <form onSubmit={(e) => { e.preventDefault(); setSent(true); }} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[['お名前', 'text', 'name'], ['メールアドレス', 'email', 'email']].map(([ph, type]) => (
          <input key={ph} type={type} placeholder={ph} required style={{
            padding: '10px 12px', background: '#1a0708', border: `1px solid ${PACHI_TOKENS.hairline}`,
            color: PACHI_TOKENS.textHi, fontSize: 13, fontFamily: '"Noto Sans JP", system-ui', borderRadius: 4,
          }} />
        ))}
        <textarea placeholder="お問い合わせ内容" required rows={4} style={{
          padding: '10px 12px', background: '#1a0708', border: `1px solid ${PACHI_TOKENS.hairline}`,
          color: PACHI_TOKENS.textHi, fontSize: 13, fontFamily: '"Noto Sans JP", system-ui', borderRadius: 4, resize: 'vertical',
        }} />
        <button type="submit" style={{
          padding: '11px', background: 'linear-gradient(180deg, #f5c542, #8a6914)',
          color: '#1a0606', border: `1px solid ${PACHI_TOKENS.gold}`, fontSize: 13, fontWeight: 900,
          cursor: 'pointer', fontFamily: '"Noto Sans JP", system-ui',
        }}>送信する</button>
      </form>
    );
  } else if (which === 'ログアウト') {
    body = (
      <div>
        <div style={{ color: PACHI_TOKENS.textHi, fontSize: 13, marginBottom: 16 }}>ログアウトしますか？</div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button onClick={onClose} style={{
            flex: 1, padding: '11px', background: 'transparent', border: `1px solid ${PACHI_TOKENS.hairline}`,
            color: PACHI_TOKENS.textHi, fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: '"Noto Sans JP", system-ui',
          }}>キャンセル</button>
          <button onClick={() => { onClose(); nav.go('home'); }} style={{
            flex: 1, padding: '11px', background: 'linear-gradient(180deg, #e0252b, #7a1418)',
            color: '#fff', border: `1px solid ${PACHI_TOKENS.gold}`, fontSize: 13, fontWeight: 900,
            cursor: 'pointer', fontFamily: '"Noto Sans JP", system-ui',
          }}>ログアウト</button>
        </div>
      </div>
    );
  } else if (SETTINGS_TEXT[which]) {
    body = (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {SETTINGS_TEXT[which].map(([h, t]) => (
          <div key={h}>
            <div style={{ color: PACHI_TOKENS.gold, fontSize: 13, fontWeight: 900, marginBottom: 4 }}>{h}</div>
            <div style={{ color: PACHI_TOKENS.textMid, fontSize: 12, lineHeight: 1.7 }}>{t}</div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 120,
      background: 'rgba(0,0,0,0.72)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 460, maxHeight: '82vh', overflowY: 'auto',
        background: 'linear-gradient(180deg, #1a0708, #050202)',
        borderTop: `2px solid ${PACHI_TOKENS.gold}`,
        borderLeft: `1px solid ${PACHI_TOKENS.gold}`, borderRight: `1px solid ${PACHI_TOKENS.gold}`,
        boxShadow: '0 -8px 30px rgba(0,0,0,0.8)', padding: '18px 16px 24px',
        borderRadius: '10px 10px 0 0',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <span style={{ color: PACHI_TOKENS.gold, fontSize: 16, fontWeight: 900,
            fontFamily: '"Noto Sans JP", system-ui', textShadow: '0 0 6px rgba(245,197,66,0.5)' }}>{which}</span>
          <button onClick={onClose} style={{ ...iconBtnR }} aria-label="閉じる"><Icon name="close" size={16} /></button>
        </div>
        {body}
      </div>
    </div>
  );
}

// ─── My page ───
function MyPageScreen({ nav }) {
  const D = window.PACHI_DATA;
  const favShopIds = [...window.PACHI_STATE.favoriteShops];
  const favShops = D.shops.filter(s => favShopIds.includes(s.id));
  const favEvents = D.events.filter(e => window.PACHI_STATE.favoriteEvents.has(e.id));

  const [openSetting, setOpenSetting] = useStateExtra(null);
  const [notif, setNotifState] = useStateExtra(() => {
    try { return JSON.parse(localStorage.getItem('pachi_notif')) || { event: true, favorite: true, ranking: false }; }
    catch (e) { return { event: true, favorite: true, ranking: false }; }
  });
  const setNotif = (n) => { setNotifState(n); try { localStorage.setItem('pachi_notif', JSON.stringify(n)); } catch (e) {} };

  return (
    <Screen activeTab="mypage" nav={nav}>
      <Header title="マイページ" />

      {/* Profile card */}
      <div style={{
        margin: '12px 12px 0', padding: '14px 14px',
        background: 'linear-gradient(135deg, #2a0d0e 0%, #6b2fb3 50%, #2a0d0e 100%)',
        border: `1px solid ${PACHI_TOKENS.gold}`,
        boxShadow: '0 0 16px rgba(107,47,179,0.3), 0 4px 14px rgba(0,0,0,0.6)',
        position: 'relative', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <CornerTicks />
        <div style={{
          width: 56, height: 56, display: 'grid', placeItems: 'center',
          borderRadius: '50%',
          background: 'linear-gradient(135deg, #f5c542, #8a6914)',
          color: '#1a0606', fontSize: 24, fontWeight: 900, fontFamily: '"Bebas Neue"',
          boxShadow: '0 0 12px rgba(245,197,66,0.5), inset 0 -3px 0 rgba(0,0,0,0.3)',
          flexShrink: 0,
        }}>P</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ color: PACHI_TOKENS.textDim, fontSize: 9, letterSpacing: 1.5, fontFamily: '"Bebas Neue"' }}>WELCOME BACK</div>
          <div style={{ color: PACHI_TOKENS.gold, fontSize: 17, fontWeight: 900,
            fontFamily: '"Noto Sans JP", system-ui',
            textShadow: '0 0 6px rgba(245,197,66,0.5)' }}>ゲストユーザー様</div>
          <div style={{ color: PACHI_TOKENS.textHi, fontSize: 11, marginTop: 2 }}>ID: P-000123 ・ ランク: ブロンズ</div>
        </div>
      </div>

      {/* Stat row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, padding: '12px' }}>
        {[
          { k: 'お気に入り店舗', v: favShops.length },
          { k: '訪問済店舗',   v: 12 },
          { k: 'ポイント',      v: 1284 },
        ].map(s => (
          <GoldFrame key={s.k} style={{ padding: '10px 6px', textAlign: 'center' }}>
            <div style={{
              color: PACHI_TOKENS.gold, fontSize: 22, fontWeight: 900,
              fontFamily: '"Bebas Neue", system-ui',
              textShadow: '0 0 8px rgba(245,197,66,0.5)',
            }}>{s.v}</div>
            <div style={{ color: PACHI_TOKENS.textDim, fontSize: 10, fontFamily: '"Noto Sans JP", system-ui' }}>{s.k}</div>
          </GoldFrame>
        ))}
      </div>

      <SectionHeader kicker="FAVORITES" title="お気に入りホール" action={favShops.length > 0 ? '管理' : null} />
      {favShops.length === 0 ? (
        <div style={{ padding: '0 12px' }}>
          <GoldFrame style={{ padding: 18, textAlign: 'center' }}>
            <div style={{ color: PACHI_TOKENS.textDim, fontSize: 12, fontFamily: '"Noto Sans JP", system-ui', marginBottom: 10 }}>
              お気に入りホールはまだありません
            </div>
            <button onClick={() => nav.go('hall')} style={{
              padding: '8px 18px', background: 'linear-gradient(180deg, #f5c542, #8a6914)',
              color: '#1a0606', border: `1px solid ${PACHI_TOKENS.gold}`,
              fontSize: 11, fontWeight: 900, cursor: 'pointer',
              fontFamily: '"Noto Sans JP", system-ui',
            }}>ホールを探す</button>
          </GoldFrame>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {favShops.map(s => <StoreCard key={s.id} shop={s} onClick={() => nav.go('store', { shopId: s.id })} />)}
        </div>
      )}

      <SectionHeader kicker="EVENTS" title="お気に入りイベント" />
      <div style={{ padding: '0 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {favEvents.map(e => (
          <div key={e.id} onClick={() => nav.go('event', { id: e.id })} style={{
            cursor: 'pointer', border: `1px solid ${PACHI_TOKENS.gold}`,
          }}>
            <img src={e.banner} alt="" style={{ display: 'block', width: '100%', height: 'auto' }} />
          </div>
        ))}
      </div>

      <SectionHeader kicker="SETTINGS" title="設定" />
      <div style={{ margin: '0 12px' }}>
        <GoldFrame>
          {[
            { k: 'アカウント設定', i: 'settings' },
            { k: '通知設定', i: 'bell' },
            { k: '利用規約', i: 'doc' },
            { k: 'プライバシーポリシー', i: 'lock' },
            { k: 'お問い合わせ', i: 'mail' },
            { k: 'ログアウト', i: 'power' },
          ].map((row, i, a) => (
            <div key={row.k} onClick={() => setOpenSetting(row.k)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
              borderTop: i === 0 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
              cursor: 'pointer',
            }}>
              <Icon name={row.i} size={16} color={PACHI_TOKENS.gold} />
              <span style={{ flex: 1, color: PACHI_TOKENS.textHi, fontSize: 13,
                fontFamily: '"Noto Sans JP", system-ui' }}>{row.k}</span>
              <span style={{ color: PACHI_TOKENS.gold }}>›</span>
            </div>
          ))}
        </GoldFrame>
      </div>
      <div style={{ height: 24 }} />
      <SettingsModal which={openSetting} onClose={() => setOpenSetting(null)}
        nav={nav} notif={notif} setNotif={setNotif} />
    </Screen>
  );
}

// ─── Ranking ───
function RankingScreen({ nav }) {
  const D = window.PACHI_DATA;
  const [tab, setTab] = useStateExtra('payout');
  const tabs = [
    { id: 'payout',   label: '差枚' },
    { id: 'rate',     label: '合成確率' },
    { id: 'visit',    label: '人気' },
  ];

  // Build ranked list
  const dataKeys = Object.keys(D.machineData);
  const ranked = [...dataKeys].sort((a, b) => D.machineData[b].payoutDiff - D.machineData[a].payoutDiff);
  const ext = [];
  // pad with synthetic data so list has 8
  for (let i = 0; i < 8; i++) {
    if (i < ranked.length) ext.push(ranked[i]);
    else {
      const m = D.machines[(i + 2) % D.machines.length];
      ext.push({ syn: true, machine: m, payoutDiff: 6240 - i * 800, machineNumber: 1234 + i, total: 8650 + i * 200, bb: 70 - i * 4, rb: 18 - i });
    }
  }

  return (
    <Screen activeTab="data" nav={nav}>
      <Header title="ランキング" onBack={() => nav.back()} />
      <PageHeader kicker="RANKING" title="全台差枚ランキング" subtitle="本日 リアルタイム更新" />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', margin: '0 12px',
        border: `1px solid ${PACHI_TOKENS.gold}` }}>
        {tabs.map((t, i) => {
          const on = t.id === tab;
          return (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: on ? 'linear-gradient(180deg, #f5c542, #8a6914)' : 'transparent',
              color: on ? '#1a0606' : PACHI_TOKENS.gold,
              border: 'none', borderRight: i < 2 ? `1px solid ${PACHI_TOKENS.gold}` : 'none',
              padding: '10px 0', fontSize: 12, fontWeight: 900, cursor: 'pointer',
              fontFamily: '"Noto Sans JP", system-ui',
            }}>{t.label}</button>
          );
        })}
      </div>

      <div style={{ height: 12 }} />

      <div style={{ margin: '0 12px' }}>
        <GoldFrame>
          {ext.map((entry, i) => {
            const isReal = !entry.syn;
            const md = isReal ? D.machineData[entry] : entry;
            const m  = isReal ? D.machines.find(x => x.id === md.machineId) : entry.machine;
            const num = isReal ? md.machineNumber : entry.machineNumber;
            const diff = isReal ? md.payoutDiff : entry.payoutDiff;
            return (
              <div key={i} onClick={() => isReal && nav.go('data', { shopId: 'konibet-shinjuku', machineKey: entry })} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                borderTop: i === 0 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
                cursor: isReal ? 'pointer' : 'default',
              }}>
                <div style={{
                  width: 28, height: 28, display: 'grid', placeItems: 'center',
                  background: i === 0 ? 'linear-gradient(135deg, #f5c542, #8a6914)' :
                              i === 1 ? 'linear-gradient(135deg, #c0c0c0, #707070)' :
                              i === 2 ? 'linear-gradient(135deg, #cd7f32, #6e3a0a)' : 'transparent',
                  border: `1px solid ${i < 3 ? PACHI_TOKENS.gold : PACHI_TOKENS.goldDim}`,
                  color: i < 3 ? '#1a0606' : PACHI_TOKENS.gold,
                  fontSize: 14, fontWeight: 900, fontFamily: '"Bebas Neue"', flexShrink: 0,
                }}>{i + 1}</div>
                <img src={m.thumbnail} style={{ width: 40, height: 44, objectFit: 'cover',
                  border: `1px solid ${PACHI_TOKENS.goldDim}`, flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ color: PACHI_TOKENS.gold, fontSize: 12, fontWeight: 900,
                    fontFamily: '"Noto Sans JP", system-ui',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  }}>{m.name}</div>
                  <div style={{ color: PACHI_TOKENS.textDim, fontSize: 11 }}>{num}番台</div>
                </div>
                <div style={{
                  color: diff >= 0 ? PACHI_TOKENS.red : '#3070d8',
                  fontSize: 18, fontWeight: 900, fontFamily: '"Bebas Neue", system-ui',
                  letterSpacing: 1,
                  textShadow: `0 0 6px ${diff >= 0 ? 'rgba(224,37,43,0.5)' : 'rgba(48,112,216,0.5)'}`,
                }}>{diff > 0 ? '+' : ''}{diff.toLocaleString()}<span style={{ fontSize: 10, color: PACHI_TOKENS.textDim, marginLeft: 1 }}>枚</span></div>
              </div>
            );
          })}
        </GoldFrame>
      </div>
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─── Search ───
function SearchScreen({ nav }) {
  const D = window.PACHI_DATA;
  const [q, setQ] = useStateExtra('');
  const ql = q.trim().toLowerCase();
  const shopHits = ql ? D.shops.filter(s => s.name.toLowerCase().includes(ql) || s.address.includes(q) || s.station.includes(q)) : [];
  const machineHits = ql ? D.machines.filter(m => m.name.toLowerCase().includes(ql)) : [];

  const recent = ['北斗の拳', 'スロット天国', 'モンキーターン', '新宿', '天界'];
  const popular = ['北斗の拳', 'モンキーターン', 'バジリスク絆2', 'バイオハザード', 'GOD EATER'];

  return (
    <Screen activeTab="hall" nav={nav}>
      <Header title="検索" onBack={() => nav.back()} />

      <div style={{ padding: '12px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: 'linear-gradient(180deg, #1a0708 0%, #050202 100%)',
          border: `1px solid ${PACHI_TOKENS.gold}`,
          padding: '10px 12px',
          boxShadow: '0 0 8px rgba(245,197,66,0.2)',
        }}>
          <Icon name="search" size={17} color={PACHI_TOKENS.gold} />
          <input value={q} autoFocus onChange={e => setQ(e.target.value)}
            placeholder="店舗名 / 機種名 / 駅名 で検索"
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: PACHI_TOKENS.textHi, fontSize: 13, fontFamily: '"Noto Sans JP", system-ui',
            }} />
          {q && (
            <button onClick={() => setQ('')} style={{
              background: 'transparent', border: 'none', color: PACHI_TOKENS.textDim,
              cursor: 'pointer', padding: 4,
            }}><Icon name="close" size={14} /></button>
          )}
        </div>
      </div>

      {!ql ? (
        <>
          <SectionHeader kicker="HISTORY" title="最近の検索" />
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, padding: '0 12px' }}>
            {recent.map(t => (
              <button key={t} onClick={() => setQ(t)} style={{
                background: 'transparent', color: PACHI_TOKENS.textHi,
                border: `1px solid ${PACHI_TOKENS.goldDim}`,
                padding: '8px 14px', fontSize: 13, cursor: 'pointer',
                fontFamily: '"Noto Sans JP", system-ui',
              }}>{t}</button>
            ))}
          </div>
          <SectionHeader kicker="TRENDING" title="人気の検索ワード" />
          <div style={{ margin: '0 12px' }}>
            <GoldFrame>
              {popular.map((t, i) => (
                <div key={t} onClick={() => setQ(t)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px',
                  borderTop: i === 0 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
                  cursor: 'pointer',
                }}>
                  <span style={{
                    color: i < 3 ? PACHI_TOKENS.red : PACHI_TOKENS.textDim,
                    fontSize: 14, fontWeight: 900, fontFamily: '"Bebas Neue"',
                    width: 18, textAlign: 'center',
                  }}>{i + 1}</span>
                  <span style={{ flex: 1, color: PACHI_TOKENS.textHi, fontSize: 13,
                    fontFamily: '"Noto Sans JP", system-ui' }}>{t}</span>
                  <span style={{ color: PACHI_TOKENS.gold }}>›</span>
                </div>
              ))}
            </GoldFrame>
          </div>
        </>
      ) : (
        <>
          {shopHits.length > 0 && (
            <>
              <SectionHeader kicker="HALLS" title={`ホール (${shopHits.length})`} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {shopHits.map(s => <StoreCard key={s.id} shop={s} onClick={() => nav.go('store', { shopId: s.id })} />)}
              </div>
            </>
          )}
          {machineHits.length > 0 && (
            <>
              <SectionHeader kicker="MACHINES" title={`機種 (${machineHits.length})`} />
              <MachineThumbnailGrid machines={machineHits} columns={3}
                onSelect={(m) => nav.go('data', { shopId: 'konibet-shinjuku', machineKey: m.id === 'monkeyturn' ? 'monkeyturn-112' : 'hokuto-247' })} />
            </>
          )}
          {shopHits.length === 0 && machineHits.length === 0 && (
            <EmptyState text={`「${q}」に該当する結果はありません`} />
          )}
        </>
      )}

      <div style={{ height: 24 }} />
    </Screen>
  );
}

function EmptyState({ text }) {
  return (
    <div style={{ padding: '40px 12px', textAlign: 'center' }}>
      <div style={{
        color: PACHI_TOKENS.gold, fontSize: 36, fontWeight: 900, opacity: 0.4,
        fontFamily: '"Bebas Neue", system-ui',
      }}>—</div>
      <div style={{ color: PACHI_TOKENS.textDim, fontSize: 12, marginTop: 8,
        fontFamily: '"Noto Sans JP", system-ui' }}>{text}</div>
    </div>
  );
}

// ─── Event list ───
function EventListScreen({ nav }) {
  const D = window.PACHI_DATA;
  return (
    <Screen activeTab="home" nav={nav}>
      <Header title="イベント一覧" onBack={() => nav.back()} />
      <PageHeader kicker="EVENTS" title="開催中・予定イベント" subtitle={`${D.events.length} 件`} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: '0 12px' }}>
        {D.events.map(e => (
          <div key={e.id} onClick={() => nav.go('event', { id: e.id })} style={{
            cursor: 'pointer', border: `1px solid ${PACHI_TOKENS.gold}`,
            background: '#000', position: 'relative',
            boxShadow: '0 0 10px rgba(224,37,43,0.25)',
          }}>
            <img src={e.banner} alt="" style={{ display: 'block', width: '100%', height: 'auto' }} />
            <div style={{
              padding: '10px 12px',
              background: 'linear-gradient(180deg, #15090a, #0a0405)',
              borderTop: `1px solid ${PACHI_TOKENS.hairline}`,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ color: PACHI_TOKENS.gold, fontSize: 14, fontWeight: 900,
                  fontFamily: '"Noto Sans JP", system-ui',
                  textShadow: '0 0 4px rgba(245,197,66,0.4)' }}>{e.title}</span>
                <span style={{ color: PACHI_TOKENS.textDim, fontSize: 11,
                  fontFamily: '"Bebas Neue"', letterSpacing: 1 }}>{e.date}</span>
              </div>
              <div style={{ color: PACHI_TOKENS.textMid, fontSize: 12, marginTop: 2,
                fontFamily: '"Noto Sans JP", system-ui' }}>{e.shopName}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─── Area detail (drilldown) ───
function AreaDetailScreen({ nav, params }) {
  const D = window.PACHI_DATA;
  const area = D.areas.find(a => a.id === params.id) || D.areas[0];
  const subAreas = {
    kanto:    ['東京都', '神奈川県', '千葉県', '埼玉県', '茨城県', '栃木県', '群馬県'],
    kansai:   ['大阪府', '京都府', '兵庫県', '奈良県', '和歌山県', '滋賀県'],
    chubu:    ['愛知県', '静岡県', '岐阜県', '三重県', '長野県', '新潟県', '富山県', '石川県', '福井県', '山梨県'],
    tohoku:   ['北海道', '青森県', '岩手県', '宮城県', '秋田県', '山形県', '福島県'],
    chugoku:  ['広島県', '岡山県', '山口県', '島根県', '鳥取県', '徳島県', '香川県', '愛媛県', '高知県'],
    kyushu:   ['福岡県', '佐賀県', '長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県', '沖縄県'],
  }[area.id] || [];

  return (
    <Screen activeTab="hall" nav={nav}>
      <Header title="エリア検索" onBack={() => nav.back()} />
      <PageHeader kicker="AREA" title={area.label} subtitle={`${area.halls.toLocaleString()} ホール`} />

      <div style={{ margin: '0 12px' }}>
        <GoldFrame>
          {subAreas.map((p, i) => (
            <div key={p} onClick={() => nav.go('hall', { areaLabel: p })} style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '12px 14px',
              borderTop: i === 0 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
              cursor: 'pointer',
            }}>
              <span style={{ color: PACHI_TOKENS.textHi, fontSize: 13, fontWeight: 700,
                fontFamily: '"Noto Sans JP", system-ui' }}>{p}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ color: PACHI_TOKENS.textDim, fontSize: 11 }}>{Math.floor(area.halls / subAreas.length + Math.random() * 20)} 件</span>
                <span style={{ color: PACHI_TOKENS.gold, fontSize: 16, fontWeight: 900 }}>›</span>
              </div>
            </div>
          ))}
        </GoldFrame>
      </div>
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─── Menu (header ≡) ───
function MenuScreen({ nav }) {
  const items = [
    { k: 'ホール検索',     route: 'hall' },
    { k: '機種一覧',       route: 'machine' },
    { k: 'ランキング',     route: 'ranking' },
    { k: 'イベント一覧',   route: 'eventlist' },
    { k: 'お気に入り',     route: 'mypage' },
    { k: '新台入替',       route: 'machine' },
    { k: 'パチスロ専門店', route: 'hall' },
    { k: '朝イチ並び',     route: 'hall' },
    { k: 'AT/ART狙い',     route: 'machine' },
    { k: '設備が充実',     route: 'hall' },
  ];
  return (
    <Screen activeTab="home" nav={nav}>
      <Header title="メニュー" onBack={() => nav.back()} />
      <div style={{ height: 12 }} />
      <div style={{ margin: '0 12px' }}>
        <GoldFrame>
          {items.map((row, i) => (
            <div key={row.k} onClick={() => nav.go(row.route)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '14px 14px',
              borderTop: i === 0 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
              cursor: 'pointer',
            }}>
              <span style={{ width: 6, height: 6, background: PACHI_TOKENS.gold, flexShrink: 0, boxShadow: '0 0 4px rgba(245,197,66,0.6)' }} />
              <span style={{ flex: 1, color: PACHI_TOKENS.textHi, fontSize: 13, fontWeight: 700,
                fontFamily: '"Noto Sans JP", system-ui' }}>{row.k}</span>
              <span style={{ color: PACHI_TOKENS.gold }}>›</span>
            </div>
          ))}
        </GoldFrame>
      </div>
      <div style={{ height: 24 }} />
    </Screen>
  );
}

Object.assign(window, {
  HallListScreen, StoreDetailScreen, MachineListScreen, MyPageScreen,
  RankingScreen, SearchScreen, EventListScreen, AreaDetailScreen, MenuScreen,
  PageHeader, EmptyState, InfoRow,
});
