/* 详细机型库（壳内层）— 品牌 logo 网格 → 点入品牌机型；按价格分组视图。
   数据：BRANDS/DB_STATS（dbdata.jsx，_mkdb.py 从本地 db dump 生成）；DBTV（data.jsx）补 6 台演示机的面板/亮点。
   深链：?tool=db · &dbv=price · &b=品牌中文名 */
const dbCx = (...a) => a.filter(Boolean).join(' ');
const dbQ = (k) => new URLSearchParams(location.search).get(k);
const DBTV_DETAIL = {};
DBTV.forEach((t) => { DBTV_DETAIL[t.id] = t; });

const DB_PRICE_BUCKETS = [
  { label: '5 千内', test: (p) => p < 5000 },
  { label: '5 千 – 1 万', test: (p) => p >= 5000 && p < 10000 },
  { label: '1 – 2 万', test: (p) => p >= 10000 && p < 20000 },
  { label: '2 万以上', test: (p) => p >= 20000 },
];

function DbModelRow({ zh, m }) {
  const det = DBTV_DETAIL[m.id];
  const sub = [det && det.panel, m.size && `${m.size}″`, det && det.hl].filter(Boolean).join(' · ');
  return (
    <div className="db-row">
      <div className="dbr-tt">
        <b>{zh} {m.m}</b>
        {sub && <small>{sub}</small>}
      </div>
      {m.price > 0
        ? <span className="dbr-p">¥{m.price.toLocaleString()}</span>
        : <span className="dbr-p na">未录价</span>}
    </div>
  );
}

function DbScreen({ onBack }) {
  const { useState, useRef } = React;
  const [mode, setMode] = useState(dbQ('dbv') === 'price' ? 'price' : 'brand');
  const b0 = BRANDS.find((b) => b.zh === dbQ('b')) || null;
  const [brand, setBrand] = useState(b0);
  const prev = useRef(b0);
  if (brand) prev.current = brand;
  const det = brand || prev.current; /* 收回滑动期间面板内容不消失 */
  const sync = (fn) => { const u = new URL(location); fn(u.searchParams); history.replaceState(null, '', u); };
  const pickBrand = (b) => { sync((p) => { if (b) p.set('b', b.zh); else p.delete('b'); }); setBrand(b); };

  return (
    <div className="db-app">
      <div className="db-head">
        <button className="mh-back" onClick={brand ? () => pickBrand(null) : onBack}
          aria-label={brand ? '返回品牌列表' : '返回主页'}><Icon name="arrowLeft" size={16} /></button>
        <div className="db-ht">
          <b>{brand ? brand.zh : '机型库'}</b>
          <small>{brand ? `共收录 ${brand.models.length} 款机型` : `在库 ${DB_STATS.inStock} 台 · ${DB_STATS.brands} 个品牌`}</small>
        </div>
      </div>

      <div className="db-panes" style={{ '--pane': brand ? 1 : 0 }}>
        {/* 面板 1：品牌网格 / 价格分组 */}
        <div className="db-pane">
          <div className="db-seg" style={{ '--seg-active': mode === 'price' ? 1 : 0 }}>
            <span className="seg-thumb"></span>
            <button className={mode === 'brand' ? 'on' : ''} onClick={() => setMode('brand')}>按品牌</button>
            <button className={mode === 'price' ? 'on' : ''} onClick={() => setMode('price')}>按价格</button>
          </div>
          {mode === 'brand' ? (
            <div className="bgrid">
              {BRANDS.map((b) => (
                <button key={b.zh} className="bcard" onClick={() => pickBrand(b)}>
                  <span className={dbCx('bd-logo', b.box && 'box')}
                    style={b.box ? { background: b.color } : { color: b.color }}>{b.en}</span>
                  {b.zh.toLowerCase() !== b.en.toLowerCase() && <b className="bd-zh">{b.zh}</b>}
                  <small className="bd-n">共收录 {b.models.length} 款机型</small>
                </button>
              ))}
            </div>
          ) : (
            DB_PRICE_BUCKETS.map((bk) => {
              const items = BRANDS.flatMap((b) => b.models.filter((m) => m.price > 0 && bk.test(m.price))
                .map((m) => ({ ...m, zh: b.zh }))).sort((a, c) => a.price - c.price);
              if (!items.length) return null;
              return (
                <React.Fragment key={bk.label}>
                  <div className="dbg-h">{bk.label}<em>{items.length} 台</em></div>
                  {items.map((m) => <DbModelRow key={m.id} zh={m.zh} m={m} />)}
                </React.Fragment>
              );
            })
          )}
        </div>

        {/* 面板 2：品牌机型 */}
        <div className="db-pane">
          {det && det.models.map((m) => <DbModelRow key={m.id} zh={det.zh} m={m} />)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DbScreen });
