// ─── Pachi screens — Home, Data Detail, Event Detail ───
const { useState } = React;

function HomeScreen({ nav }) {
  const D = window.PACHI_DATA;
  const [areaTab, setAreaTab] = useState(0);
  const eventBanners = D.events.slice(1).map(e => ({ id: e.id, banner: e.banner }));
  return (
    <Screen activeTab="home" nav={nav}>
      <Header
        onSearch={() => nav.go('search')}
        onMenu={() => nav.go('menu')}
        onLogo={() => nav.go('home')} />
      <SearchBar onClick={() => nav.go('search')} />
      <HeroBanner src="assets/main_banner_tenkai.png" label="本日 OPEN"
        onClick={() => nav.go('event', { id: 'tenkai' })} />

      <SectionHeader kicker="HOT EVENTS" title="開催中イベント" action="一覧"
        onAction={() => nav.go('eventlist')} />
      <EventBannerList events={eventBanners}
        onSelect={(e) => nav.go('event', { id: e.id })} />

      <SectionHeader kicker="QUICK ACCESS" title="クイックメニュー" />
      <MenuIconGrid items={D.quickMenu} onSelect={(it) => {
        const map = {
          hall_search: 'hall', machine_list: 'machine', ranking: 'ranking',
          event: 'eventlist', favorite: 'mypage',
          new_machine: 'machine', specialty_store: 'hall',
          morning_lineup: 'hall', at_art: 'machine', good_facilities: 'hall',
        };
        const route = map[it.id] || map[it.key] || 'hall';
        nav.go(route);
      }} />

      <SectionHeader kicker="FIND HALL" title="エリアから探す" />
      <div style={{ padding: '0 12px 8px' }}>
        <AreaStationToggle active={areaTab} onChange={setAreaTab} />
      </div>
      <AreaButtonGrid areas={D.areas}
        onSelect={(a) => nav.go('area', { id: a.id })} />

      <SectionHeader kicker="NEAR YOU" title="注目ホール" action="もっと見る"
        onAction={() => nav.go('hall')} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {D.shops.map(s => (
          <StoreCard key={s.id} shop={s} onClick={() => nav.go('store', { shopId: s.id })} />
        ))}
      </div>

      <SectionHeader kicker="TODAY'S PICK" title="本日の注目機種" action="もっと見る"
        onAction={() => nav.go('machine')} />
      <MachineThumbnailGrid machines={D.machines.slice(0, 6)} columns={3}
        onSelect={(m) => nav.go('data', { shopId: 'konibet-shinjuku', machineKey: m.id === 'monkeyturn' ? 'monkeyturn-112' : 'hokuto-247' })} />

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

function SearchBar({ onClick }) {
  return (
    <div style={{ padding: '10px 12px 0' }} onClick={onClick}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer',
        background: 'linear-gradient(180deg, #1a0708 0%, #050202 100%)',
        border: `1px solid ${PACHI_TOKENS.goldDim}`,
        padding: '8px 12px',
      }}>
        <Icon name="search" size={16} color={PACHI_TOKENS.gold} />
        <span style={{
          color: PACHI_TOKENS.textDim, fontSize: 13,
          fontFamily: '"Noto Sans JP", system-ui',
        }}>店舗名 / 機種名 / 駅名で検索</span>
      </div>
    </div>
  );
}

function Footer() {
  return (
    <div style={{
      margin: '24px 12px 0', padding: '14px 12px',
      borderTop: `1px solid ${PACHI_TOKENS.hairline}`,
      borderBottom: `1px solid ${PACHI_TOKENS.hairline}`,
      textAlign: 'center',
    }}>
      <div style={{
        color: PACHI_TOKENS.gold, fontSize: 14, fontWeight: 900, letterSpacing: 4,
        fontFamily: '"Bebas Neue", system-ui',
        textShadow: '0 0 8px rgba(245,197,66,0.5)',
      }}>PACHI</div>
      <div style={{
        color: PACHI_TOKENS.textDim, fontSize: 10, marginTop: 4,
        fontFamily: '"Noto Sans JP", system-ui', letterSpacing: 0.5,
      }}>パチンコ・パチスロ情報サイト</div>
      <div style={{
        color: PACHI_TOKENS.textDim, fontSize: 9.5, marginTop: 6,
        fontFamily: '"Noto Sans JP", system-ui',
      }}>利用規約 ・ プライバシーポリシー ・ お問い合わせ</div>
    </div>
  );
}

// ─── Data Detail Screen ───
function DataDetailScreen({ nav, params }) {
  const D = window.PACHI_DATA;
  const key = params.machineKey || 'hokuto-247';
  const md = D.machineData[key] || D.machineData['hokuto-247'];
  const [day, setDay] = useState(0);
  const [fav, setFav] = useState(false);
  const machine = D.machines.find(m => m.id === md.machineId);
  const otherMachines = D.machines.filter(m => m.id !== md.machineId).slice(0, 6);

  return (
    <Screen activeTab="data" nav={nav}>
      <Header title="台データ" onBack={() => nav.back()} />

      {/* Title bar */}
      <div style={{
        margin: '12px 12px 0', padding: '10px 12px',
        background: 'linear-gradient(90deg, #2a0d0e 0%, #6a0509 50%, #2a0d0e 100%)',
        border: `1px solid ${PACHI_TOKENS.gold}`,
        boxShadow: '0 0 16px rgba(224,37,43,0.4), 0 4px 10px rgba(0,0,0,0.6)',
        position: 'relative', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <CornerTicks />
        <img src={machine?.thumbnail} alt="" style={{
          width: 56, height: 62, objectFit: 'cover', flexShrink: 0,
          border: `1px solid ${PACHI_TOKENS.gold}`,
        }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            color: PACHI_TOKENS.textDim, fontSize: 10, letterSpacing: 1.5,
            fontFamily: '"Bebas Neue", system-ui',
          }}>{md.shopName}</div>
          <div 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)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{md.machineName}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 2 }}>
            <span style={{
              color: PACHI_TOKENS.textMid, fontSize: 10, fontWeight: 700,
              fontFamily: '"Noto Sans JP", system-ui',
            }}>台番号</span>
            <span style={{
              color: '#fff8e6', fontSize: 22, fontWeight: 900,
              fontFamily: '"Bebas Neue", system-ui', letterSpacing: 1,
              textShadow: '0 0 8px rgba(245,197,66,0.4)',
            }}>{md.machineNumber}</span>
          </div>
        </div>
        <button onClick={() => setFav(!fav)} style={{
          background: fav ? 'linear-gradient(180deg, #f5c542, #8a6914)' : 'transparent',
          color: fav ? '#1a0606' : PACHI_TOKENS.gold,
          border: `1px solid ${PACHI_TOKENS.gold}`,
          padding: '6px 8px', fontSize: 9, fontWeight: 900, cursor: 'pointer',
          fontFamily: '"Noto Sans JP", system-ui', flexShrink: 0,
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1,
        }}>
          <Icon name="star" size={16} fill={fav} />
          <span style={{ fontSize: 9 }}>{fav ? '登録済' : 'お気に入り'}</span>
        </button>
      </div>

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

      {/* Play CTA */}
      <PlayButton machineName={md.machineName} />

      <div style={{ height: 12 }} />
      <DayTabs active={day} onChange={setDay} />

      <div style={{ height: 14 }} />
      <GraphPanel data={md} />

      <SectionHeader kicker="STATS" title="基本データ" />
      <StatsPanel data={md} />

      <SectionHeader kicker="HISTORY" title="当り履歴" />
      <HistoryPanel history={md.history} />

      <SectionHeader kicker="RELATED" title="同店の他機種" action="全機種" />
      <MachineThumbnailGrid machines={otherMachines} columns={3}
        onSelect={(m) => nav.go('data', { shopId: md.shopId, machineKey: m.id === 'monkeyturn' ? 'monkeyturn-112' : 'hokuto-247' })} />

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

// ─── Event Detail Screen ───
function EventDetailScreen({ nav, params }) {
  const D = window.PACHI_DATA;
  const ev = D.events.find(e => e.id === params.id) || D.events[0];
  const targetMachines = D.machines.filter(m => ev.targetMachineIds.includes(m.id));
  const otherEvents = D.events.filter(e => e.id !== ev.id).slice(0, 2);

  return (
    <Screen activeTab="home" nav={nav}>
      <Header title="イベント詳細" onBack={() => nav.back()} />

      {/* Hero */}
      <div style={{
        margin: '12px 12px 0', position: 'relative',
        border: `2px solid ${PACHI_TOKENS.gold}`,
        boxShadow: '0 0 28px rgba(224,37,43,0.55), 0 6px 20px rgba(0,0,0,0.7)',
      }}>
        <img src={ev.banner} alt="" style={{ display: 'block', width: '100%', height: 'auto' }} />
        <CornerTicks />
      </div>

      {/* Title block */}
      <div style={{ margin: '14px 12px 0' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
          {ev.tags.map(t => (
            <span key={t} style={{
              background: 'linear-gradient(180deg, #e0252b, #9a0f15)',
              color: '#fff', fontSize: 10, fontWeight: 900, padding: '3px 8px',
              border: `1px solid ${PACHI_TOKENS.gold}`, letterSpacing: 1,
              fontFamily: '"Noto Sans JP", system-ui',
            }}>#{t}</span>
          ))}
        </div>
        <h2 style={{
          margin: 0, color: PACHI_TOKENS.gold, fontSize: 22, fontWeight: 900,
          lineHeight: 1.2, letterSpacing: 0.5,
          fontFamily: '"Noto Sans JP", system-ui',
          textShadow: '0 0 10px rgba(245,197,66,0.5), 0 1px 0 #000',
        }}>{ev.title}</h2>
        <div style={{
          color: PACHI_TOKENS.textMid, fontSize: 12, marginTop: 4,
          fontFamily: '"Noto Sans JP", system-ui',
        }}>{ev.shopName}</div>
      </div>

      {/* Schedule */}
      <SectionHeader kicker="SCHEDULE" title="開催日程" />
      <GoldFrame style={{ margin: '0 12px', padding: '12px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 56, height: 56, display: 'grid', placeItems: 'center',
            background: 'linear-gradient(180deg, #2a0d0e, #0a0203)',
            border: `1px solid ${PACHI_TOKENS.gold}`,
            flexShrink: 0,
          }}>
            <div style={{ color: PACHI_TOKENS.gold, fontSize: 9, fontWeight: 700, fontFamily: '"Bebas Neue", system-ui' }}>MAY</div>
            <div style={{ color: '#fff8e6', fontSize: 22, fontWeight: 900, lineHeight: 1, fontFamily: '"Bebas Neue", system-ui', textShadow: '0 0 6px rgba(245,197,66,0.5)' }}>01</div>
            <div style={{ color: PACHI_TOKENS.textDim, fontSize: 8, fontFamily: '"Bebas Neue", system-ui' }}>FRI</div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{
              color: PACHI_TOKENS.textHi, fontSize: 13, fontWeight: 700,
              fontFamily: '"Noto Sans JP", system-ui',
            }}>{ev.date}</div>
            <div style={{
              color: PACHI_TOKENS.textDim, fontSize: 12, marginTop: 2,
              fontFamily: '"Noto Sans JP", system-ui',
            }}>並び順抽選 9:30 ~ ・ OPEN 10:00</div>
          </div>
        </div>
      </GoldFrame>

      {/* Description */}
      <SectionHeader kicker="DETAILS" title="イベント内容" />
      <GoldFrame style={{ margin: '0 12px', padding: '12px 14px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {ev.description.map((line, i) => (
            <p key={i} style={{
              margin: 0, color: PACHI_TOKENS.textHi, fontSize: 13, lineHeight: 1.7,
              fontFamily: '"Noto Sans JP", system-ui',
            }}>{line}</p>
          ))}
        </div>
        {ev.content.length > 0 && (
          <div style={{
            display: 'flex', flexDirection: 'column', gap: 0,
            marginTop: 14, paddingTop: 12,
            borderTop: `1px solid ${PACHI_TOKENS.hairline}`,
          }}>
            {ev.content.map((c, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 0',
                borderBottom: i === ev.content.length - 1 ? 'none' : `1px solid ${PACHI_TOKENS.hairline}`,
              }}>
                <span style={{
                  width: 28, height: 28, display: 'grid', placeItems: 'center',
                  background: 'linear-gradient(135deg, #f5c542 0%, #8a6914 100%)',
                  color: '#1a0606', fontSize: 14, fontWeight: 900, flexShrink: 0,
                  borderRadius: '50%',
                  boxShadow: 'inset 0 -2px 3px rgba(0,0,0,0.4)',
                }}><Icon name="check" size={15} color="#1a0606" /></span>
                <span style={{
                  color: PACHI_TOKENS.gold, fontSize: 13, fontWeight: 900,
                  fontFamily: '"Noto Sans JP", system-ui',
                  textShadow: '0 0 4px rgba(245,197,66,0.4)',
                }}>{c.text}</span>
              </div>
            ))}
          </div>
        )}
      </GoldFrame>

      {/* Target machines */}
      <SectionHeader kicker="TARGET MACHINES" title={`対象機種 ${targetMachines.length}機種`} />
      <MachineThumbnailGrid machines={targetMachines} columns={3}
        onSelect={(m) => nav.go('data', { shopId: 'konibet-shinjuku', machineKey: m.id === 'monkeyturn' ? 'monkeyturn-112' : 'hokuto-247' })} />

      {/* CTA */}
      <div style={{ padding: '20px 12px 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <button onClick={() => {
          const s = window.PACHI_STATE; const id = ev.id;
          if (s.favoriteEvents.has(id)) s.favoriteEvents.delete(id);
          else s.favoriteEvents.add(id);
          // simple feedback
          alert(s.favoriteEvents.has(id) ? 'お気に入りに追加しました' : 'お気に入りを解除しました');
        }} style={{
          width: '100%', padding: '14px',
          background: 'linear-gradient(180deg, #f5c542 0%, #d4a017 50%, #8a6914 100%)',
          border: `1px solid ${PACHI_TOKENS.gold}`,
          color: '#1a0606', fontSize: 15, fontWeight: 900, letterSpacing: 2,
          fontFamily: '"Noto Sans JP", system-ui', cursor: 'pointer',
          boxShadow: '0 0 14px rgba(245,197,66,0.5), inset 0 -2px 0 rgba(0,0,0,0.3)',
        }}><span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}><Icon name="star" size={16} fill color="#1a0606" />お気に入りに追加</span></button>
        <button onClick={() => {
          // pick the matching shop, default to konibet
          const shop = window.PACHI_DATA.shops.find(s => s.name === ev.shopName) || window.PACHI_DATA.shops[0];
          nav.go('store', { shopId: shop.id });
        }} style={{
          width: '100%', padding: '12px',
          background: 'linear-gradient(180deg, #1a0708 0%, #050202 100%)',
          border: `1px solid ${PACHI_TOKENS.gold}`,
          color: PACHI_TOKENS.gold, fontSize: 13, fontWeight: 700, letterSpacing: 1,
          fontFamily: '"Noto Sans JP", system-ui', cursor: 'pointer',
        }}>店舗ページへ ›</button>
      </div>

      {/* Related events */}
      <SectionHeader kicker="RELATED" title="関連イベント" />
      <div style={{ padding: '0 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {otherEvents.map(e => (
          <div key={e.id} onClick={() => nav.go('event', { id: e.id })} style={{
            cursor: 'pointer', position: 'relative',
            border: `1px solid ${PACHI_TOKENS.gold}`,
          }}>
            <img src={e.banner} alt="" style={{ display: 'block', width: '100%', height: 'auto' }} />
          </div>
        ))}
      </div>

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

// ─── Screen wrapper — passthrough; ResponsivePachi supplies background + bottom nav ───
function Screen({ children }) {
  return <div>{children}</div>;
}

Object.assign(window, { HomeScreen, DataDetailScreen, EventDetailScreen, Screen });
