function route() {
  const key=location.hash.slice(1);
  return key==='connections'||key==='catalog'||media.some(m=>m.id===key)?key:'overview';
}
function Sidebar({page,open,close,isReal}) {
  const link=(id,label,icon,mark)=> <a key={id} className={'nav-item '+(page===id?'active':'')} href={'#'+id} aria-current={page===id?'page':undefined} onClick={close}>{mark?<Mark m={mark} small/>:<Icon name={icon}/>}<span>{label}</span>{page===id && <i/>}</a>;
  return <>{open && <button className="scrim" aria-label="メニューを閉じる" onClick={close}/>}<aside className={'sidebar '+(open?'opened':'')} id="main-menu">
    <div className="identity"><span className="brand-symbol" aria-hidden="true"><i/><i/><i/></span><div><div className="wordmark">BUDDY<span>×</span>BOARD</div><small>SNSダッシュボード</small></div>
      <button className="mobile-close" aria-label="メニューを閉じる" onClick={close}><Icon name="close"/></button></div>
    <nav aria-label="メインナビゲーション"><div className="nav-label">ダッシュボード</div>{link('overview','全体サマリー','grid')}
      <div className="nav-label">媒体別</div>{media.map(m=>link(m.id,m.name,m.id,m))}
      <div className="nav-rule"/>{link('catalog','取れるデータ','posts')}<div className="nav-label">設定</div>{link('connections','連携と更新','link')}</nav>
    <div className="sidebar-bottom"><Icon name={isReal?'check':'flask'} size={16}/>{isReal?'実データ連携（YouTube）':'デモ環境（ダミーデータ）'}</div></aside></>;
}
function App() {
  const [page,setPage]=useState(route);
  const [brandList,setBrandList]=useState(brands);
  const [accountMap,setAccountMap]=useState(accounts);
  const [brand,setBrand]=useState(brands[0].id);
  const [choices,setChoices]=useState({});
  const [status,setStatus]=useState({});
  const [days,setDays]=useState(28);
  const [open,setOpen]=useState(false);
  const [notice,setNotice]=useState(null);
  const [platforms,setPlatforms]=useState(null);
  const [catalogError,setCatalogError]=useState(false);

  useEffect(()=>{
    fetch('data/metricCatalog.json').then(response=>{
      if(!response.ok)throw new Error('catalog');
      return response.json();
    }).then(catalog=>setPlatforms(catalog.platforms)).catch(()=>setCatalogError(true));

    fetch('data/youtubeRealData.json').then(response=>{
      if(!response.ok)return null;
      return response.json();
    }).then(real=>{
      if(!real || !real.channel)return;
      const adapted = makeRealBrandEntries(real);
      setBrandList([adapted.brand, ...brands]);
      setAccountMap({...accounts, ...adapted.accounts});
      setBrand(adapted.brand.id);
    }).catch(()=>{});
  },[]);

  const inflight=useRef(new Set());
  const scope=useRef('');
  useEffect(()=>{
    const change=()=>{setPage(route());setOpen(false);setNotice(null);window.scrollTo(0,0)};
    const escape=e=>{if(e.key==='Escape')setOpen(false)};
    window.addEventListener('hashchange',change);window.addEventListener('keydown',escape);
    return ()=>{window.removeEventListener('hashchange',change);window.removeEventListener('keydown',escape)};
  },[]);
  useEffect(()=>{if(!notice)return;const timer=setTimeout(()=>setNotice(null),5500);return ()=>clearTimeout(timer)},[notice]);

  const currentBrandObj = brandList.find(b=>b.id===brand) || brandList[0];
  const entries=media.map(m=>{
    const group=brand+'-'+m.id;
    const options=accountMap[group] || accounts[brands[0].id+'-'+m.id];
    const selected=choices[group]||0;
    const a=options[selected] || options[0];
    return {...a,...status[a.handle],group,options,selected,data:metrics(a,days)};
  });
  const entry=entries.find(e=>e.medium.id===page);
  const targets=entry?[entry]:entries;
  const currentScope=[brand,page,...targets.map(e=>e.handle)].join('/');
  scope.current=currentScope;
  const last=targets.filter(e=>e.time).map(e=>e.time).sort().at(-1);
  const isBusy=targets.some(e=>e.busy);
  const isRealBrand = Boolean(currentBrandObj?.isReal);

  function refresh(list,connect=false) {
    const batch=list.filter(e=>!e.isReal && (connect||e.state==='on') && !inflight.current.has(e.handle));
    if(!batch.length)return;
    batch.forEach(e=>inflight.current.add(e.handle));
    setNotice(null);
    setStatus(prev=>{
      const next={...prev};batch.forEach(e=>next[e.handle]={...prev[e.handle],busy:true,result:null});return next;
    });
    window.setTimeout(()=>{
      const clock=new Intl.DateTimeFormat('ja-JP',{timeZone:'Asia/Tokyo',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'}).format(new Date());
      const failed=batch.filter(e=>e.failOnce && !e.attempted && !connect);
      setStatus(prev=>{
        const next={...prev};
        batch.forEach(e=>{
          const error=failed.includes(e);
          next[e.handle]={...prev[e.handle],state:'on',busy:false,attempted:true,time:error?e.time:clock,result:error?'error':'done'};
        });
        return next;
      });
      batch.forEach(e=>inflight.current.delete(e.handle));
      if(scope.current===currentScope)setNotice({error:failed.length>0,text:failed.length?failed.map(e=>e.medium.name).join('・')+' の取得に失敗しました。もう一度再取得してください。':(connect?'連携が完了しました':batch.length+'媒体の更新が完了しました')});
    },950);
  }

  const isCatalog=page==='catalog';
  const hasPeriod=page==='overview'||Boolean(entry);
  const title=entry?entry.medium.name:isCatalog?'取れるデータ':page==='connections'?'連携と更新':'全体サマリー';
  const loadingCatalog=<p role="status">{catalogError?'一覧データを読み込めませんでした。ページを再読み込みしてください。':'一覧データを読み込んでいます…'}</p>;
  const activeDates = (entry?.data?.startDate && entry?.data?.endDate)
    ? {start: entry.data.startDate, end: entry.data.endDate}
    : (targets.find(e=>e.state==='on')?.data?.startDate
      ? {start: targets.find(e=>e.state==='on').data.startDate, end: targets.find(e=>e.state==='on').data.endDate}
      : {start: date(1-days), end: date(0)});
  useEffect(()=>{document.title=title+' | BUDDY×BOARD'},[title]);

  return <><Sidebar page={page} open={open} close={()=>setOpen(false)} isReal={isRealBrand}/><div className="workspace" inert={open?'':undefined}>
    <header className={'topbar'+(isCatalog?' catalog-topbar':'')}><div className="top-left"><button className="menu-btn" aria-label="メニューを開く" aria-controls="main-menu" aria-expanded={open} onClick={()=>setOpen(true)}><Icon name="menu"/></button>{!isCatalog && <><span className="brand-label">ブランド</span>
      <SelectBox label="ブランドを切り替える" icon="brand" value={brand} onChange={v=>{setBrand(v);setNotice(null)}}>{brandList.map(b=><option key={b.id} value={b.id}>{b.name}</option>)}</SelectBox>
      {entry && <div className="account-row">{entry.options.length>1?<SelectBox label="アカウントを切り替える" value={entry.selected} onChange={v=>{setChoices({...choices,[entry.group]:Number(v)});setNotice(null)}}>{entry.options.map((a,i)=><option key={a.handle} value={i}>{a.handle}（{a.title}）</option>)}</SelectBox>:<span>{entry.state==='off'?'アカウント未連携':entry.handle}</span>}</div>}
      </>}</div>
      {!isCatalog && <div className="header-update"><span className="time-label" title="対象のアカウントのうち、最後に取得に成功した時刻（日本時間）"><Icon name="clock" size={14}/>最終更新 <time>{last?last.slice(5):'— '+(entry?.state==='expired'?'要再連携':'未連携')}</time></span>
        <RefreshButton primary busy={isBusy} disabled={isRealBrand || !targets.some(e=>e.state==='on')} action={()=>refresh(targets)}/></div>}</header>
    <main><div className="page-heading"><div><h1>{entry && <Mark m={entry.medium}/>} {title}</h1>
      {hasPeriod?<div className="date-range"><Icon name="calendar" size={15}/><span>{activeDates.start.replaceAll('-','/')}<em>–</em>{activeDates.end.replaceAll('-','/')}</span></div>:<p className="subtitle">{isCatalog?'公式ドキュメントの記載にもとづく一覧です。実際のアカウントでの取得では確かめていません（2026-11-19 調べ）':'媒体ごとにアカウントの連携状態と最終更新を確認できます。'}</p>}</div>
      {hasPeriod && <div className="periods" role="group" aria-label="集計期間">{[7,28,90].map(n=><button key={n} aria-pressed={days===n} onClick={()=>setDays(n)}>{n}日</button>)}</div>}</div>
      {page==='overview' && <Overview entries={entries} days={days}/>}
      {entry && <Channel key={brand+entry.handle+days} entry={entry} days={days} platform={platforms?.find(p=>p.id===page)} loadingCatalog={loadingCatalog}/>}
      {page==='connections' && <Connections entries={entries} refresh={refresh}/>}
      {isCatalog && (platforms?<Catalog platforms={platforms}/>:loadingCatalog)}
    </main></div>{notice && <div className={'toast '+(notice.error?'failed':'')} role="status"><Icon name={notice.error?'alert':'check'} size={17}/>{notice.text}<button aria-label="通知を閉じる" onClick={()=>setNotice(null)}><Icon name="close" size={15}/></button></div>}</>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
