/* match-app.jsx — shell: nav, region, router, toast, tweaks, mount */
const DA = window.DM;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "brand": ["oklch(0.64 0.20 296)","oklch(0.74 0.17 298)","oklch(0.82 0.13 300)","oklch(0.50 0.20 292)"],
  "matchFlow": "hybrid",
  "wallLayout": "cards",
  "density": "regular",
  "matchAnim": "animated"
}/*EDITMODE-END*/;

const BRAND_SETS = {
  "Violet":  ["oklch(0.64 0.20 296)","oklch(0.74 0.17 298)","oklch(0.82 0.13 300)","oklch(0.50 0.20 292)"],
  "Electric":["oklch(0.60 0.18 250)","oklch(0.72 0.16 248)","oklch(0.82 0.12 245)","oklch(0.48 0.17 255)"],
  "Magenta": ["oklch(0.62 0.22 350)","oklch(0.72 0.19 350)","oklch(0.82 0.14 350)","oklch(0.50 0.21 348)"]
};

function applyBrand(arr){
  const r = document.documentElement.style;
  r.setProperty('--v-sig', arr[0]); r.setProperty('--v-bright', arr[1]);
  r.setProperty('--v-neon', arr[2]); r.setProperty('--v-deep', arr[3]);
}

/* ---------------- toast ---------------- */
function useToast(){
  const [msg, setMsg] = useState(null);
  useEffect(()=>{ window.dmToast = (m)=>{ setMsg(m); clearTimeout(window.__tT); window.__tT=setTimeout(()=>setMsg(null), 3000); }; },[]);
  return msg;
}

/* ---------------- nav ---------------- */
function Nav({ en, view, go, theme, setTheme, lang, setLang, region, setRegion }){
  const links = [['home',en?'Home':'首页'],['lobby',en?'Lobby':'大厅'],['wall',en?'Team Wall':'车队墙'],['match',en?'Smart Match':'智能匹配'],['community',en?'Community':'社区']];
  const [regOpen, setRegOpen] = useState(false);
  return (
    <header style={{ position:'sticky', top:0, zIndex:100, backdropFilter:'blur(16px) saturate(1.3)',
      background:'color-mix(in oklab, var(--bg) 80%, transparent)', borderBottom:'1px solid var(--line-soft)' }}>
      <div className="wrap" style={{ display:'flex', alignItems:'center', gap:18, height:66 }}>
        <a onClick={()=>go('home')} className="logo" style={{ fontSize:21, cursor:'pointer' }}>DEMAN <span className="accent">MATCH</span><span className="tld">电鳗开黑</span></a>
        <nav style={{ display:'flex', gap:2, marginLeft:6 }} className="nav-links">
          {links.map(([k,lbl])=>(
            <a key={k} onClick={()=>go(k)} style={{ fontFamily:'var(--cn)', fontWeight:600, fontSize:14, cursor:'pointer', padding:'8px 13px', borderRadius:'var(--r-xs)',
              color: view===k?'var(--v-bright)':'var(--text-dim)', background: view===k?'color-mix(in oklab,var(--v-sig) 14%,transparent)':'transparent' }}>{lbl}</a>
          ))}
        </nav>
        <div style={{ marginLeft:'auto', display:'flex', alignItems:'center', gap:9 }}>
          {/* region */}
          <div style={{ position:'relative' }}>
            <button className="chip" style={{ cursor:'pointer' }} onClick={()=>setRegOpen(o=>!o)}>
              <Ic k="globe" w={14}/> {en?DA.REGIONS.find(r=>r.key===region).en:DA.REGIONS.find(r=>r.key===region).cn} <Ic k="chevron" w={12} style={{ transform:'rotate(90deg)' }}/>
            </button>
            {regOpen && (
              <div className="card" style={{ position:'absolute', top:'120%', right:0, padding:6, minWidth:180, zIndex:50, boxShadow:'var(--shadow)' }}>
                {DA.REGIONS.map(r=>(
                  <button key={r.key} disabled={!r.live} onClick={()=>{ if(r.live){ setRegion(r.key); setRegOpen(false); } }} style={{ width:'100%', display:'flex', alignItems:'center', gap:9, padding:'9px 10px', border:'none', borderRadius:'var(--r-xs)', cursor:r.live?'pointer':'not-allowed',
                    background: region===r.key?'var(--surface-2)':'transparent', color: r.live?'var(--text)':'var(--text-mute)', fontFamily:'var(--cn)', fontSize:13.5, fontWeight:600, textAlign:'left' }}>
                    <span>{r.flag}</span>{en?r.en:r.cn}
                    {!r.live && <span className="chip" style={{ marginLeft:'auto', fontSize:9.5, padding:'2px 7px' }}>{en?'Soon':'即将'}</span>}
                    {region===r.key && <Ic k="check" w={14} style={{ marginLeft:'auto', color:'var(--q-lime)' }}/>}
                  </button>
                ))}
              </div>
            )}
          </div>
          <button className="chip" style={{ cursor:'pointer', width:38, padding:0, height:38, justifyContent:'center' }} onClick={()=>setLang(lang==='en'?'zh':'en')} title="Language">
            <span style={{ fontFamily:'var(--mono)', fontSize:11.5 }}>{lang==='en'?'中':'EN'}</span>
          </button>
          <button className="chip" style={{ cursor:'pointer', width:38, padding:0, height:38, justifyContent:'center' }} onClick={()=>setTheme(theme==='dark'?'light':'dark')} title="Theme">
            <Ic k={theme==='dark'?'sun':'moon'} w={16}/>
          </button>
          <button onClick={()=>go('me')} title={en?'Profile':'我的'} style={{ position:'relative', border:'none', background:'none', cursor:'pointer', padding:0 }}>
            <span style={{ position:'absolute', top:-2, right:-2, width:9, height:9, borderRadius:'50%', background:'var(--q-coral)', border:'2px solid var(--bg)', zIndex:2 }} />
            <Av name={DA.ME.name} size={38} dot="online" />
          </button>
          <button className="btn btn-go btn-sm nav-cta" onClick={()=>go('start')}><Ic k="plus" w={14}/>{en?'Start a team':'发车'}</button>
        </div>
      </div>
    </header>
  );
}

/* ---------------- footer ---------------- */
function Foot({ en, go }){
  return (
    <footer style={{ borderTop:'1px solid var(--line-soft)', marginTop:40, padding:'34px 0 28px' }}>
      <div className="wrap" style={{ display:'flex', alignItems:'center', gap:16, flexWrap:'wrap' }}>
        <a className="logo" style={{ fontSize:18 }}>DEMAN <span className="accent">MATCH</span></a>
        <span style={{ fontFamily:'var(--mono)', fontSize:11.5, color:'var(--text-mute)' }}>{en?'The smart LFG layer for the Deman community · NA':'电鳗社区的智能找车层 · 美服'}</span>
        <a href="../index.html" style={{ marginLeft:'auto', fontFamily:'var(--cn)', fontSize:13, color:'var(--text-dim)' }}>← {en?'Deman matrix':'电鳗矩阵'}</a>
        <a href="../play/Deman Play.html" style={{ fontFamily:'var(--cn)', fontSize:13, color:'var(--text-dim)' }}>Deman Play</a>
      </div>
      <div className="wrap" style={{ display:'flex', alignItems:'center', gap:18, flexWrap:'wrap', marginTop:22, paddingTop:20, borderTop:'1px solid var(--line-soft)' }}>
        <span style={{ fontFamily:'var(--mono)', fontSize:11.5, color:'var(--text-mute)' }}>© 2018–2026 Deman One Corp · All rights reserved.</span>
        <a onClick={()=>go('legal')} style={{ cursor:'pointer', fontFamily:'var(--cn)', fontSize:13, color:'var(--text-mute)' }}>{en?'Terms of Service':'服务条款'}</a>
        <a onClick={()=>go('legal')} style={{ cursor:'pointer', fontFamily:'var(--cn)', fontSize:13, color:'var(--text-mute)' }}>{en?'Privacy Policy':'隐私政策'}</a>
        <a href="mailto:info@demanone.com" style={{ fontFamily:'var(--mono)', fontSize:12.5, color:'var(--text-mute)' }}>info@demanone.com</a>
        <span style={{ marginLeft:'auto', fontFamily:'var(--mono)', fontSize:11.5, color:'var(--text-mute)' }}>demanmatch.com</span>
      </div>
    </footer>
  );
}

/* ---------------- app ---------------- */
function App(){
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState('home');
  const [theme, setTheme] = useState(t.theme);
  const [lang, setLang] = useState('zh');
  const [region, setRegion] = useState('na');
  const [lobbyGame, setLobbyGame] = useState('lol');
  const [meTab, setMeTab] = useState('profile');
  const [party, setParty] = useState(null);
  const [dataVer, setDataVer] = useState(0);   // bumps when DMApi swaps seed→real data
  const en = lang==='en';
  const toast = useToast();

  useEffect(()=>{ document.documentElement.setAttribute('data-theme', theme); },[theme]);
  useEffect(()=>{ setTheme(t.theme); },[t.theme]);
  useEffect(()=>{ document.documentElement.setAttribute('data-lang', lang); },[lang]);
  useEffect(()=>{ applyBrand(t.brand || BRAND_SETS.Violet); },[t.brand]);
  // data adapter: re-render on fresh data; hydrate (seed now, real backend when DM_API_CONFIG.enabled)
  useEffect(()=>{ const h=()=>setDataVer(v=>v+1); document.addEventListener('dm:data', h); if(window.DMApi) window.DMApi.hydrate(); return ()=>document.removeEventListener('dm:data', h); },[]);
  useEffect(()=>{ if(window.DMApi){ window.DMApi.CONFIG.region=region; window.DMApi.hydrate(); } },[region]);

  function go(v){ setView(v); window.scrollTo({ top:0, behavior:'instant' in window ? 'instant' : 'auto' }); }
  function openParty(p){ setParty(p); go('room'); }
  function joined(p){ window.dmToast(en?'You\'re in! Host notified — opening the room.':'上车成功!车主已收到提醒,正在进入房间。'); setParty(p); go('room'); }

  return (
    <div>
      <Nav en={en} view={view} go={go} theme={theme} setTheme={setTheme} lang={lang} setLang={setLang} region={region} setRegion={setRegion} />
      <main key={'data'+dataVer}>
        {view==='home' && <HomeView en={en} go={go} onOpen={openParty} t={t} />}
        {view==='lobby' && <LobbyView en={en} go={go} setLobbyGame={setLobbyGame} />}
        {view==='wall' && <TeamWall en={en} onOpen={openParty} t={t} />}
        {view==='match' && <SmartMatch en={en} onOpen={openParty} onJoined={joined} t={t} />}
        {view==='start' && <StartView en={en} onBack={()=>go('wall')} onCreate={(p)=>{ DA.PARTIES.unshift(p); window.dmToast(en?'Car is live — pushed to the wall, queue & Discord.':'车已发出 —— 已挂上车队墙、匹配池和 Discord。'); openParty(p); }} />}
        {view==='room' && party && <RoomView p={party} en={en} onBack={()=>go('wall')} onApply={joined} t={t} />}
        {view==='community' && <CommunityView en={en} />}
        {view==='me' && <MeView en={en} tab={meTab} setTab={setMeTab} onOpen={openParty} />}
        {view==='legal' && <LegalView en={en} onBack={()=>go('home')} />}
      </main>
      <Foot en={en} go={go} />

      {/* toast */}
      {toast && (
        <div style={{ position:'fixed', bottom:26, left:'50%', transform:'translateX(-50%)', zIndex:400,
          background:'var(--surface)', border:'1.5px solid var(--line)', borderRadius:'var(--r-sm)', padding:'13px 20px', boxShadow:'var(--shadow)',
          display:'flex', alignItems:'center', gap:11, maxWidth:'90vw' }}>
          <span style={{ width:9, height:9, borderRadius:'50%', background:'var(--q-lime)', flex:'none', boxShadow:'0 0 8px var(--q-lime)' }} />
          <span style={{ fontFamily:'var(--cn)', fontSize:13.5, color:'var(--text)' }}>{toast}</span>
        </div>
      )}

      {/* tweaks */}
      <TweaksPanel title="Tweaks">
        <TweakSection label={en?'Smart match flow':'智能匹配流程'} />
        <TweakRadio label={en?'Flow':'流程'} value={t.matchFlow} options={[{value:'queue',label:en?'Queue':'挂队列'},{value:'browse',label:en?'Browse':'主动浏览'},{value:'hybrid',label:en?'Hybrid':'混合'}]} onChange={v=>setTweak('matchFlow',v)} />
        <TweakRadio label={en?'Match animation':'匹配动效'} value={t.matchAnim} options={[{value:'animated',label:en?'Radar':'雷达'},{value:'instant',label:en?'Instant':'瞬时'}]} onChange={v=>setTweak('matchAnim',v)} />

        <TweakSection label={en?'Team wall':'车队墙'} />
        <TweakRadio label={en?'Layout':'布局'} value={t.wallLayout} options={[{value:'cards',label:en?'Cards':'卡片'},{value:'rows',label:en?'Rows':'频道行'},{value:'lanes',label:en?'Lanes':'看板'}]} onChange={v=>setTweak('wallLayout',v)} />
        <TweakRadio label={en?'Card density':'卡片密度'} value={t.density} options={[{value:'regular',label:en?'Regular':'标准'},{value:'compact',label:en?'Compact':'紧凑'}]} onChange={v=>setTweak('density',v)} />

        <TweakSection label={en?'Look':'外观'} />
        <TweakRadio label={en?'Theme':'主题'} value={t.theme} options={[{value:'dark',label:en?'Dark':'深色'},{value:'light',label:en?'Light':'浅色'}]} onChange={v=>setTweak('theme',v)} />
        <TweakColor label={en?'Brand accent':'品牌主色'} value={t.brand}
          options={[BRAND_SETS.Violet, BRAND_SETS.Electric, BRAND_SETS.Magenta]}
          onChange={v=>setTweak('brand',v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
