/* =========================================================
   라우터 · 데모 전환 패널 · 앱 루트 (v2)
   ========================================================= */
function DemoSwitcher(){ useStore(); const [open,setOpen]=useState(false); const s=window.STRO.state.session; const pr1=window.STRO.state.proposals.filter(p=>p.infId==='i1').sort((a,b)=>b.createdAt.localeCompare(a.createdAt))[0];
  const as=(uid,to)=>{ api.loginAs(uid); go(to); setOpen(false); };
  const rt=parseHash(); const inThread=s && rt.path.startsWith('/messages/') ? rt.path.slice(10) : null;
  const msgScen=[
    ['광고주: 메시지 목록','응답 대기 · 협의 · 기한 초과 · 거절','u_a1','/messages'],
    ['제안 발송 후 응답 대기','온기다원 → 하루 (남은 시간 표시)','u_a1','/messages/t_prd_wait'],
    ['인플루언서(하루): 제안 확인·답변','수락 · 조건 협의 · 거절','u_i1','/messages/t_prd_wait'],
    ['회신 후 조건 협의','소희의 조건 협의 요청 (안 읽음 1)','u_a1','/messages/t_pr2'],
    ['72시간 기한 초과','루멘 스튜디오 → 하루','u_a1','/messages/t_pr1'],
    ['정상적인 제안 거절','픽셀하우스 → 지훈','u_a1','/messages/t_prd_decl'],
    ['대화가 없는 신규 계정','새봄상회 (광고주, 시연)','u_a2','/messages'],
    ['다른 계정 확인: 소희','본인 대화만 표시되는지','u_i10','/messages'],
  ];
  const scen=[
    ['첫 방문 메인','역할 진입 · 카테고리 · 비교 예시','guest','/'],
    ['비회원 둘러보기','가입 없이 검색 · 예시 프로필','guest','/adv/find?fresh=1'],
    ['광고주: 저장한 비교표','저장 당시 조건 복원 · 정보 변경 표시','u_a1','/adv/boards'],
    ['광고주: 검색 → 비교 → 제안','유튜브 쇼츠 조건으로 검색','u_a1','/adv/find?preset=shorts'],
    ['광고주: 후보 보드','카밍 세럼 쇼츠 리뷰 섭외','u_a1','/adv/boards/bd1'],
    ['인플루언서(하루): 받은 제안 응답','가장 최근 받은 제안','u_i1', pr1?'/inf/proposals/'+pr1.id:'/inf/proposals'],
    ['광고주: 답변 확인','보낸 제안','u_a1','/adv/proposals'],
    ['인플루언서: 협업 조건 수정','수정 → 검색·비교에 반영','u_i1','/inf/conditions'],
    ['운영자: 정보 확인·갱신','소유·수치 확인, 재확인 기준','u_op','/admin/verify'],
  ];
  return <><button className="demo-fab" onClick={()=>setOpen(o=>!o)} aria-expanded={open} aria-label="프로토타입 데모 메뉴"><span className="dot"/>데모<span className="lbl-role"> 전환</span> {s && <span className="lbl-role" style={{opacity:.7,fontWeight:500}}>· {s.role==='influencer'?'인플루언서':s.role==='advertiser'?'광고주':'운영자'}</span>}</button>
    {open && <div className="demo-panel" role="dialog" aria-label="데모 메뉴"><div className="row" style={{marginBottom:6}}><b style={{fontSize:13}}>데모 메뉴</b><span className="spacer"/><button className="db" style={{width:44,height:36,justifyContent:'center',marginBottom:0}} aria-label="데모 메뉴 닫기" onClick={()=>setOpen(false)}><Icon name="x" size={16}/></button></div><p style={{marginBottom:10}}>프로토타입 검토용 메뉴입니다. 실제 서비스에는 포함되지 않습니다.</p>
      <h4>역할 전환</h4>
      {[['u_a1','광고주 · 한결파트너스 (김다은)','/adv/find'],['u_i1','인플루언서 · 하루','/inf/profile'],['u_op','STRO 운영자','/admin/profiles']].map(([u,l,to])=><button key={u} className={'db '+(s?.userId===u?'on':'')} onClick={()=>as(u,to)}>{l}{s?.userId===u && <small>현재</small>}</button>)}
      <h4>시나리오</h4>
      {scen.map(([t,d,u,to])=><button key={t} className="db" onClick={()=>{ if(u==='guest'){ api.logout(); go(to); setOpen(false); } else as(u,to); }}><span><b style={{display:'block',fontSize:12}}>{t}</b><span style={{fontSize:11,color:'#A59F92'}}>{d}</span></span></button>)}
      <h4>메시지 시연</h4>
      {msgScen.map(([t,d,u,to])=><button key={t} className="db" onClick={()=>as(u,to)}><span><b style={{display:'block',fontSize:12}}>{t}</b><span style={{fontSize:11,color:'#A59F92'}}>{d}</span></span></button>)}
      {inThread && <button className="db" onClick={()=>{ window.STRO.msg.simulateIncoming(inThread); setOpen(false); toast('상대방 메시지가 도착한 상황을 만들었습니다.',{demo:true}); }}><Icon name="chat" size={14}/>이 대화에 상대 메시지 도착 (시연)</button>}
      <button className="db" onClick={async()=>{ setOpen(false); if(await confirmDialog({title:'시연 대화를 다시 만들까요?',body:'‘응답 대기’·‘정상 거절’ 시연 제안과 그 대화만 현재 시각 기준으로 다시 만듭니다. 직접 보낸 제안과 대화는 그대로 유지됩니다.',okText:'다시 만들기'})){ window.STRO.msg.regenerateDemo(); toast('시연 대화를 다시 만들었습니다.'); } }}><Icon name="refresh" size={14}/>시연 대화 다시 만들기</button>
      <h4>시연 기준일</h4>
      <button className={'db '+(window.STRO.clock.isFixed()?'on':'')} onClick={()=>{ api.setDemoClock(!window.STRO.clock.isFixed()); toast(window.STRO.clock.isFixed()?`시연 기준일 ${fmt.dateY(window.STRO.clock.demoDate())}로 고정했습니다.`:'실제 한국 날짜·시간으로 돌아왔습니다.'); }}><span><b style={{display:'block',fontSize:12}}>{window.STRO.clock.isFixed()?`고정 중 · ${fmt.dateY(window.STRO.clock.demoDate())}`:'실제 한국 날짜 사용 중'}</b><span style={{fontSize:11,color:'#A59F92'}}>{window.STRO.clock.isFixed()?'눌러서 실제 날짜로 전환':`눌러서 ${fmt.dateY(window.STRO.clock.demoDate())}로 고정 (시연 데이터 기준)`}</span></span></button>
      <h4>데이터</h4>
      <button className="db" onClick={async()=>{ setOpen(false); if(await confirmDialog({title:'시연 데이터를 초기화할까요?',body:'이 브라우저에 저장된 보드·제안·검색·프로필 수정이 처음 상태로 돌아갑니다.',danger:true,okText:'초기화'})){ api.reset(); go('/'); toast('시연 데이터를 초기화했습니다.'); } }}><Icon name="refresh" size={14}/>시연 데이터 초기화</button>
      {s && <button className="db" onClick={()=>{ api.logout(); go('/'); setOpen(false); }}><Icon name="logout" size={14}/>로그아웃</button>}
    </div>}</>; }

/* 이전 버전 URL → 새 화면 (제거된 대행·정산·검수 동선) */
const LEGACY = [
  [/^\/adv\/(dashboard|campaigns(\/.*)?|saved|brands(\/.*)?)$/, '/adv/find'],
  [/^\/adv\/collabs$/, '/adv/proposals'],
  [/^\/adv\/costs$/, '/adv/plan'],
  [/^\/inf\/(dashboard|campaigns(\/.*)?|applications|collabs)$/, '/inf/proposals'],
  [/^\/inf\/settlement$/, '/inf/stats'],
  [/^\/collab\/.*$/, null],
  [/^\/admin$/, '/admin/profiles'], [/^\/admin\/(influencers)$/, '/admin/verify'], [/^\/admin\/(advertisers|campaigns(\/.*)?|collabs)$/, '/admin/profiles'], [/^\/admin\/inquiries$/, '/admin/reports'],
  [/^\/onboarding\/advertiser$/, '/adv/find'], [/^\/onboarding\/influencer\/done$/, '/inf/profile'],
];
function legacyTarget(path){ for(const [re,to] of LEGACY){ if(re.test(path)){ if(to) return to; const s=window.STRO.state.session; return s?.role==='influencer'?'/inf/proposals':'/adv/proposals'; } } return null; }

const ROUTES = [
  ['/', ()=> <HomePage/>, 'public', 'bare'],
  ['/start', ()=> <HomePage/>, 'public', 'bare'],
  ['/login', ()=> <LoginPage/>, 'public', 'bare'],
  ['/reset', ()=> <ResetPage/>, 'public', 'bare'],
  ['/reset/new', ()=> LIVE ? <NewPasswordPage/> : <NotFound/>, 'public', 'bare'],
  ['/signup/:role', p=> <SignupPage key={p.role} role={p.role==='advertiser'?'advertiser':'influencer'}/>, 'public', 'bare'],
  ['/help', ()=> <HelpPage/>, 'public', 'bare'],
  /* 광고주 — 검색·상세·이용권은 비회원도 열람 가능 */
  ['/adv/find', ()=> <AdvFind/>, 'guest-ok'],
  ['/adv/influencers/:id', p=> <AdvInfluencerDetail id={p.id}/>, 'guest-ok'],
  ['/adv/plan', ()=> <AdvPlan/>, 'guest-ok'],
  ['/adv/compare', ()=> <AdvCompare/>, 'guest-ok'],
  ['/adv/boards', ()=> <AdvBoards/>, 'advertiser'],
  ['/adv/boards/:id', p=> <AdvBoardDetail id={p.id}/>, 'advertiser'],
  ['/adv/proposals', ()=> <AdvProposals/>, 'advertiser'],
  ['/adv/proposals/:id', p=> <AdvProposalDetail id={p.id}/>, 'advertiser'],
  ['/adv/searches', ()=> <AdvSearches/>, 'advertiser'],
  /* 인플루언서 */
  ['/onboarding/influencer', ()=> <InfOnboarding/>, 'influencer', 'bare'],
  ['/inf/profile', ()=> <InfProfile/>, 'influencer'],
  ['/inf/conditions', ()=> <InfConditions/>, 'influencer'],
  ['/inf/proposals', ()=> <InfProposals/>, 'influencer'],
  ['/inf/proposals/:id', p=> <InfProposalDetail id={p.id}/>, 'influencer'],
  ['/inf/stats', ()=> <InfStats/>, 'influencer'],
  ['/settings', ()=> <SettingsPage/>, 'auth'],
  /* 1:1 메시지 (광고주·인플루언서) */
  ['/messages', ()=> <MessagesPage/>, 'auth'],
  ['/messages/:id', p=> <MessagesPage id={p.id}/>, 'auth'],
  /* 운영자 */
  ['/admin/profiles', ()=> <AdminProfiles/>, 'admin'],
  ['/admin/verify', ()=> <AdminVerify/>, 'admin'],
  ['/admin/reports', ()=> <AdminReports/>, 'admin'],
  ['/admin/usage', ()=> <AdminUsage/>, 'admin'],
];

/* 실제 서비스에서 서버 연결 전이라 '준비 중'으로 보여 줄 화면 (브라우저에만 저장되는 일이 없도록) */
const LIVE_SOON = {'/adv/plan':'이용권', '/adv/boards':'후보 보드', '/adv/boards/:id':'후보 보드', '/adv/proposals':'보낸 제안', '/adv/proposals/:id':'보낸 제안', '/adv/searches':'저장한 검색',
  '/inf/proposals':'받은 제안', '/inf/proposals/:id':'받은 제안', '/inf/stats':'노출·제안 통계', '/messages':'메시지', '/messages/:id':'메시지', '/admin/reports':'오류·신고', '/admin/usage':'이용 현황'};

/* 모바일: 표를 카드형 목록으로 — th 텍스트를 각 td의 data-label로 복사 */
function labelTables(){ document.querySelectorAll('table.table:not(.no-rwd)').forEach(t=>{ const ths=[...t.querySelectorAll('thead th')].map(th=>th.textContent.trim()); if(!t.classList.contains('rwd')) t.classList.add('rwd'); if(!ths.length) return; t.querySelectorAll('tbody tr').forEach(tr=>[...tr.children].forEach((td,i)=>{ const l=ths[i]||''; if(td.getAttribute('data-label')!==l) td.setAttribute('data-label',l); })); }); }
function useTableLabels(){ useEffect(()=>{ labelTables(); let t=0; const mo=new MutationObserver(()=>{ clearTimeout(t); t=setTimeout(labelTables,30); }); mo.observe(document.getElementById('root'),{childList:true,subtree:true}); return ()=>{ mo.disconnect(); clearTimeout(t); }; },[]); }

function App(){ useStore(); const r=useRoute(); const s=window.STRO.state.session; useTableLabels();
  const booting = LIVE && (window.STRO.state.live||{}).boot!=='ready';
  useEffect(()=>{ const t=setTimeout(()=>document.body.classList.toggle('has-savebar', !!document.querySelector('.save-bar')),50); return ()=>clearTimeout(t); });
  useEffect(()=>{ api.setLastRoute(r.full); },[r.full]);
  const legacy=booting?null:legacyTarget(r.path);
  useEffect(()=>{ if(legacy){ toast('이전 화면은 정리되어 새 화면으로 이동했습니다.'); history.replaceState(null,'','#'+legacy); window.dispatchEvent(new HashChangeEvent('hashchange')); } },[r.path]);
  if(booting) return <><BootScreen/><Toasts/><ConfirmHost/></>;
  if(legacy) return null;
  let found=null, params={};
  for(const rt of ROUTES){ const m=match(rt[0], r.path); if(m){ found=rt; params=m; break; } }
  let content;
  if(!found) content = s ? <Shell role={s.role}><NotFound/></Shell> : <NotFound/>;
  else if(LIVE && LIVE_SOON[found[0]]) content = <Shell role={s?s.role:'advertiser'}><LiveSoon title={LIVE_SOON[found[0]]}/></Shell>;
  else { const [, comp, access, layout] = found;
    if(access==='public') content = comp(params);
    else if(access==='guest-ok'){ if(s && s.role!=='advertiser') content = <Shell role={s.role}><Forbidden need="광고주"/></Shell>; else content = <Shell role="advertiser">{comp(params)}</Shell>; }
    else if(!s){ content = <LoginPage/>; }
    else if(access!=='auth' && access!==s.role) content = <Shell role={s.role}><Forbidden need={access==='admin'?'STRO 운영자':access==='advertiser'?'광고주':'인플루언서'}/></Shell>;
    else content = layout==='bare' ? comp(params) : <Shell role={s.role}>{comp(params)}</Shell>;
  }
  return <>{LIVE ? <LiveEnvBar/> : window.STRO.clock.isFixed() && <div className="demo-clock no-print" role="note">시연 기준일 {fmt.dateY(window.STRO.clock.demoDate())} 고정 중</div>}{content}{!LIVE && <DemoSwitcher/>}{LIVE && <LiveNotice/>}<Toasts/><ConfirmHost/></>; }

(function(){ const st=window.STRO.state; if((!location.hash || location.hash==='#' || location.hash==='#/') && st.lastRoute && st.session && st.lastRoute!=='/') location.hash='#'+st.lastRoute; })();
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
/* 실제 서비스: 로그인 상태·공개 프로필을 서버에서 불러옴 */
if(LIVE){ if(window.STRO.live) window.STRO.live.boot(); else { window.STRO.state.live={boot:'error', error:'필요한 파일을 불러오지 못했습니다. 새로고침해 주세요.'}; window.STRO._core.commit(); } }
