/* global React */
const { useState, useMemo, useEffect, useRef } = React;

const D = window.BANDORI_DATA;
const bandById = (id) => D.BANDS.find(b => b.id === id) || D.BANDS[0];

// ───── Header ─────
function UtilityBar() {
  return (
    <div className="bf-utility">
      <div className="bf-container">
        <div className="bf-uleft">
          <span><span className="bf-pulse"></span>实时</span>
          <span>更新于 2026.05.09 14:32 JST</span>
          <span className="bf-hide-mobile">编辑者 12 人在线</span>
        </div>
        <div className="bf-uright">
          <span className="bf-hide-mobile">JASRAC No. 9026452001Y31015</span>
          <span style={{color:'#fff'}}>简体</span>
          <span style={{opacity:.4}}>/</span>
          <span>日本語</span>
          <span style={{opacity:.4}}>/</span>
          <span>EN</span>
        </div>
      </div>
    </div>
  );
}

function Masthead({ search, setSearch }) {
  return (
    <header className="bf-mast">
      <div className="bf-container">
        <a href="index.html" className="bf-logo" aria-label="bandori.fans home">
          <span className="lg-words">
            <span className="lg-tag" aria-hidden="true">F A N &nbsp;&nbsp; A R C H I V E</span>
            <span className="lg-1">
              <span className="lg-bandori">BAND<span className="lg-O">O</span>R<span className="lg-i">i</span></span><span className="dot">.</span><span className="lg-fans">FANS</span>
            </span>
            <span className="lg-strip">
              <span className="lg-strip-jp">バンドリ ファン資料庫</span>
              <span className="lg-strip-sep">/</span>
              <span>BanG Dream! 系列</span>
              <span className="lg-strip-sep">/</span>
              <span>EST. 2024</span>
            </span>
          </span>
        </a>
        <div className="bf-mast-meta bf-hide-mobile">
          <span className="ml-tag">// 站点说明</span>
          <span className="ml-desc">把 BanG Dream! 系列散落在各个官方渠道的资讯整合到一处 ——
          9 个团体、上千首歌、数百场演出、声优生日、CD/BD 发售情报，
          全部由粉丝义工共同维护，开放编辑、可订阅日历、可提交订正。</span>
        </div>
        <div className="bf-search">
          <input
            placeholder="跨库搜索 — 曲目 / 团体 / 会场 / 活动"
            value={search}
            onChange={e=>setSearch(e.target.value)}
          />
          <span className="bf-skbd">⌘ K</span>
          <button>搜索</button>
        </div>
      </div>
    </header>
  );
}

function PrimaryNav() {
  return (
    <nav className="bf-nav">
      <div className="bf-container">
        {D.SECONDARY_NAV.map((n, i) => (
          <a key={n.id} href={n.href} className={i===0 ? 'active':''}>
            <span className="nv-jp">{n.jp}</span>
            <span className="nv-cn bf-hide-mobile">{n.cn}</span>
          </a>
        ))}
        <div className="bf-nav-spacer"></div>
        <div className="bf-nav-misc bf-hide-mobile">
          <span>随机条目 ↗</span>
          <span>·</span>
          <span>提交订正 ↗</span>
          <span>·</span>
          <span>X @bandori_fans ↗</span>
        </div>
      </div>
    </nav>
  );
}

function BandSwitcher({ active, setActive }) {
  return (
    <div className="bf-bands">
      <div className="bf-container">
        {D.BANDS.map(b => (
          <button
            key={b.id}
            className={'bf-band' + (active===b.id ? ' active':'')}
            style={{'--band-color': b.color}}
            onClick={()=>setActive(b.id)}
          >
            <span className="bf-bdot"></span>
            <span className="bf-bnm">
              <span className="bf-bnm-en">{b.id==='all' ? '全部团体' : b.name}</span>
              <span className="bf-bnm-jp">{b.id==='all' ? 'ALL · 9 BANDS' : b.romaji}</span>
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ───── Section title ─────
function SectionTitle({ jp, cn, more = '查看全部 →', href = 'subpage.html' }) {
  return (
    <div className="bf-section-title">
      <div className="st-title">{cn}<span className="st-jp">{jp}</span></div>
      <a className="st-more" href={href}>{more}</a>
    </div>
  );
}

// ───── Hero modules ─────
function WhatDayCard({ active }) {
  const items = active==='all' ? D.TODAY_HISTORY : D.TODAY_HISTORY.filter(i => i.band===active);
  const list = items.length ? items : D.TODAY_HISTORY;
  return (
    <div className="bf-whatday">
      <div className="bf-whatday-hd">
        <span className="wd-jp">// TODAY IN BANDORI</span>
        <span className="wd-cn">今日纪念日</span>
      </div>
      <div className="bf-whatday-date">
        <span className="wd-y">2026</span>
        <span className="wd-md">05.09</span>
        <span className="wd-d">星期六</span>
      </div>
      <div className="bf-whatday-list">
        {list.slice(0,5).map((it, i) => {
          const b = bandById(it.band);
          return (
            <div key={i} className="wd-row" style={{'--band-color': b.color}}>
              <div className="wd-y2">{it.y}</div>
              <div className="wd-mark"></div>
              <div className="wd-text">
                <span className="wd-band">{b.id==='all' ? 'BANDORI' : b.romaji}</span>
                {it.text}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LiveSpotlight({ active }) {
  const list = D.LIVES.filter(l => active==='all' || l.band===active);
  const live = list[0] || D.LIVES[0];
  const b = bandById(live.band);
  return (
    <a href="subpage.html?p=lives" className="bf-spotlight" style={{'--accent': b.accent, background: b.color, color: b.ink}}>
      <span className="sp-tag">即将开演 / NEXT LIVE</span>
      <span className="sp-title">{live.title}</span>
      <dl className="sp-meta">
        <dt>日期</dt><dd>{live.d}（周{live.day}）</dd>
        <dt>会场</dt><dd>{live.venue}</dd>
        <dt>地区</dt><dd>{live.city}</dd>
        <dt>状态</dt><dd>{live.status === 'soldout' ? '已售罄' : live.status === 'lottery' ? '抽选受理中' : '一般贩售中'}</dd>
      </dl>
      <span className="sp-cta">查看演出详情 →</span>
    </a>
  );
}

function QuickStats({ active }) {
  const b = bandById(active);
  const newsCount = D.NEWS.filter(n => active==='all' || n.band===active).length;
  const liveCount = D.LIVES.filter(l => active==='all' || l.band===active).length;
  const relCount  = D.RELEASES.filter(r => active==='all' || r.band===active).length;
  return (
    <div className="bf-quick">
      <div className="bf-quickcard qc-live" style={{'--band-color': b.color}}>
        <span className="qc-tag">// 当前筛选团体</span>
        <span className="qc-num">{b.id==='all' ? '全 9 团体' : b.name}</span>
        <span className="qc-meta">{b.id==='all' ? 'BanG Dream! · ALL BANDS' : b.romaji}</span>
      </div>
      <div className="bf-quickcard">
        <span className="qc-tag">// 本周新增</span>
        <span className="qc-num">{newsCount}<span style={{fontSize:14, color:'var(--ink-3)', marginLeft:6, fontFamily:'var(--mono)', fontStyle:'normal'}}>条</span></span>
        <span className="qc-meta">最近 7 日新闻</span>
      </div>
      <div className="bf-quickcard">
        <span className="qc-tag">// 即将到来</span>
        <span className="qc-num" style={{fontSize:24, lineHeight:1.2}}>
          {liveCount} 场 / {relCount} 张
        </span>
        <span className="qc-meta">两个月内的演出与发售 · 可加入日历</span>
      </div>
    </div>
  );
}

function Hero({ active }) {
  return (
    <section className="bf-hero">
      <div className="bf-container">
        <div className="bf-hero-grid bf-hero-grid-2">
          <WhatDayCard active={active} />
          <LiveSpotlight active={active} />
        </div>
      </div>
    </section>
  );
}

// ───── News ─────
function NewsList({ active }) {
  const list = D.NEWS.filter(n => active==='all' || n.band===active);
  const rows = list.length ? list : D.NEWS;
  return (
    <div>
      <SectionTitle jp="LATEST NEWS" cn="最新新闻" more="全部新闻 →" href="subpage.html?p=news" />
      <div className="bf-news">
        {rows.slice(0,12).map((n, i) => {
          const b = bandById(n.band);
          return (
            <a className="bf-news-row" href="subpage.html?p=news" key={i} style={{'--band-color': b.color}}>
              <span className="nw-d">{n.d}</span>
              <span className="nw-t">{n.t}</span>
              <span className="nw-title">
                <span className="nw-band">{b.id==='all' ? 'BANDORI' : b.romaji}</span>
                {n.title}
              </span>
              <span className="nw-source">{n.source}</span>
            </a>
          );
        })}
      </div>
    </div>
  );
}

// ───── Calendar grid ─────
function CalendarStrip() {
  const todayKey = '2026.05.09';
  return (
    <div>
      <SectionTitle jp="UPCOMING / MAY" cn="近期日历 · 5 月" more="完整日历 →" href="subpage.html?p=cal" />
      <div className="bf-cal-grid">
        {D.CALENDAR.slice(0,14).map((c, i) => {
          return (
            <div key={i} className={'bf-cal-cell' + (c.d===todayKey ? ' is-today':'')}>
              <div className="bf-cal-head">
                <span className="ch-d">{c.d.slice(-2)}</span>
                <span className="ch-w">周{c.day}</span>
              </div>
              {c.items.slice(0,2).map((ev, j) => {
                const b = bandById(ev.band);
                return (
                  <a key={j} className="bf-cal-event" href="subpage.html?p=cal" style={{'--band-color': b.color}}>
                    {ev.title}
                  </a>
                );
              })}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ───── Releases table ─────
function ReleasesTable({ active }) {
  const list = D.RELEASES.filter(r => active==='all' || r.band===active);
  const rows = list.length ? list : D.RELEASES;
  return (
    <div>
      <SectionTitle jp="UPCOMING RELEASES" cn="最新 CD / BD 发售" more="唱片资料库 →" href="subpage.html?p=releases" />
      <table className="bf-tbl">
        <thead>
          <tr><th style={{width:96}}>日期</th><th style={{width:60}}>类型</th><th style={{width:140}}>团体</th><th>标题</th><th className="bf-hide-mobile">品番</th></tr>
        </thead>
        <tbody>
          {rows.slice(0,8).map((r,i) => {
            const b = bandById(r.band);
            return (
              <tr key={i}>
                <td className="td-d">{r.d}</td>
                <td><span className="td-kind">{r.kind}</span></td>
                <td><span className="td-band" style={{background: b.color, color: b.ink}}>{b.romaji}</span></td>
                <td className="td-title"><a href="subpage.html?p=releases">{r.title}</a><small>{r.meta}</small></td>
                <td className="td-cat bf-hide-mobile">{r.cat}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ───── Lives table ─────
function LivesTable({ active }) {
  const list = D.LIVES.filter(l => active==='all' || l.band===active);
  const rows = list.length ? list : D.LIVES;
  return (
    <div>
      <SectionTitle jp="UPCOMING LIVES" cn="近期演出" more="活动出演 →" href="subpage.html?p=lives" />
      <table className="bf-tbl">
        <thead>
          <tr><th style={{width:120}}>日期</th><th style={{width:140}}>团体</th><th>演出名称</th><th className="bf-hide-mobile">会场</th><th style={{width:96}} className="bf-hide-mobile">状态</th></tr>
        </thead>
        <tbody>
          {rows.slice(0,8).map((l,i) => {
            const b = bandById(l.band);
            return (
              <tr key={i}>
                <td className="td-d">{l.d}（周{l.day}）</td>
                <td><span className="td-band" style={{background: b.color, color: b.ink}}>{b.romaji}</span></td>
                <td className="td-title"><a href="subpage.html?p=lives">{l.title}</a><small>{l.venue} · {l.city}</small></td>
                <td className="bf-hide-mobile td-cat">{l.venue}</td>
                <td className="bf-hide-mobile"><span className="td-status" data-s={l.status}>{l.status==='soldout' ? '售罄' : l.status==='lottery' ? '抽选' : '贩售中'}</span></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ───── Database grid ─────
function DatabaseGrid() {
  return (
    <section className="bf-db">
      <div className="bf-container">
        <SectionTitle jp="DATABASE / 10 个互链子库" cn="资料库" more="全部索引 →" href="subpage.html?p=database" />
        <div className="bf-db-grid">
          {D.DATABASES.map((db, i) => (
            <a key={db.id} href="subpage.html?p=database" className="bf-db-card">
              <span className="db-num">{String(i+1).padStart(2,'0')} / 10</span>
              <span className="db-jp">{db.jp}</span>
              <span className="db-cn">{db.cn} · /{db.slug}</span>
              <span className="db-desc">{db.desc}</span>
              <span className="db-count">{db.count} →</span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// ───── Footer ─────
function Footer() {
  return (
    <footer className="bf-foot">
      <div className="bf-container">
        <div className="bf-foot-grid">
          <div>
            <div className="bf-foot-mast">bandori<span className="dot">.</span>fans</div>
            <p className="bf-foot-discl">
              本站为 BanG Dream! 系列的非官方粉丝站点。
              与株式会社 Bushiroad 及其关联公司无任何关系。
              不保证信息完全准确，欢迎通过下方表单提交订正。
            </p>
          </div>
          <div>
            <h4>站点</h4>
            <ul>
              <li><a href="subpage.html?p=news">新闻</a></li>
              <li><a href="subpage.html?p=cal">日历</a></li>
              <li><a href="subpage.html?p=whatday">今日纪念日</a></li>
              <li><a href="subpage.html?p=database">资料库</a></li>
            </ul>
          </div>
          <div>
            <h4>参与共建</h4>
            <ul>
              <li><a href="placeholder.html?p=edit">条目编辑指南</a></li>
              <li><a href="placeholder.html?p=fix">资料订正表单</a></li>
              <li><a href="placeholder.html?p=contact">联系我们</a></li>
              <li><a href="placeholder.html?p=changelog">更新日志</a></li>
            </ul>
          </div>
          <div>
            <h4>法律</h4>
            <ul>
              <li><a href="placeholder.html?p=privacy">隐私政策</a></li>
              <li><a href="placeholder.html?p=terms">使用条款</a></li>
              <li><span style={{color:'rgba(255,255,255,0.5)'}}>JASRAC 9026452001Y31015</span></li>
            </ul>
          </div>
        </div>
        <div className="bf-foot-bottom">
          <span>© 2024–2026 bandori.fans / 粉丝运营 · 非营利 · 非官方</span>
          <span>build 2026.05.09 · commit a8f2e1c · editors 12 · entries 4,872</span>
        </div>
      </div>
    </footer>
  );
}



// ───── Homepage quick-access strip ─────
function QuickAccess() {
  const links = [
    { id:'news',     k:'NEWS',     jp:'最新新闻',     cn:'15 条本周更新',          href:'subpage.html?p=news' },
    { id:'lives',    k:'LIVES',    jp:'近期演出',     cn:'12 场 · 武道馆/横滨/Zepp', href:'subpage.html?p=lives' },
    { id:'releases', k:'RELEASES', jp:'最新发售',     cn:'10 张 · CD/BD 接下两月',   href:'subpage.html?p=releases' },
    { id:'database', k:'DATABASE', jp:'10 子库索引', cn:'4,872 条目 · 互链',         href:'subpage.html?p=database' },
  ];
  return (
    <section className="bf-qa">
      <div className="bf-container">
        <div className="bf-qa-hd">
          <span className="bf-qa-tag">// MORE FROM bandori.fans</span>
          <span className="bf-qa-cn">在其他板块继续浏览</span>
        </div>
        <div className="bf-qa-grid">
          {links.map(l => (
            <a key={l.id} href={l.href} className="bf-qa-card">
              <span className="qa-k">{l.k}</span>
              <span className="qa-jp">{l.jp}</span>
              <span className="qa-cn">{l.cn}</span>
              <span className="qa-arrow">→</span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  UtilityBar, Masthead, PrimaryNav, BandSwitcher,
  Hero, NewsList, CalendarStrip, ReleasesTable, LivesTable,
  DatabaseGrid, Footer, bandById, QuickAccess,
});
