/* =========================================================
   STRO 운영자: 프로필 관리 · 정보 확인·갱신 · 오류·신고 · 이용 현황
   - 운영자는 광고료를 확정하거나 광고비를 지급하지 않습니다.
   - 실제 서비스에서는 모든 /admin API를 서버에서 운영자 권한으로 검증해야 합니다.
   ========================================================= */
function AdminProfiles(){ useStore(); const st=window.STRO.state; const [f,setF]=useState('all'); const [q,setQ]=useState('');
  const groups={all:st.influencers, listed:st.influencers.filter(sel.isListed), draft:st.influencers.filter(i=>!sel.isListed(i)), stale:st.influencers.filter(sel.isStale), hint:st.influencers.filter(i=>sel.improveHints(i).length)};
  const list=groups[f].filter(i=>!q||(i.name+i.handle).includes(q));
  return <div className="page wide"><PageHead title="프로필 관리" desc="검색 노출 상태와 데이터 품질을 관리합니다."/>
    <div className="row wrap" style={{gap:8,marginBottom:12}}><Seg value={f} onChange={setF} options={[['all',`전체 ${groups.all.length}`],['listed',`노출 중 ${groups.listed.length}`],['draft',`미노출 ${groups.draft.length}`],['stale',`재확인 필요 ${groups.stale.length}`],['hint',`정보 보완 필요 ${groups.hint.length}`]]}/><div className="input-group" style={{width:240}}><Icon name="search" size={15}/><input value={q} onChange={e=>setQ(e.target.value)} placeholder="이름·핸들" aria-label="프로필 검색"/></div></div>
    <div className="card"><table className="table"><thead><tr><th>인플루언서</th><th>검색 노출</th><th>협업 상태</th><th>채널 소유 확인</th><th>보완 필요</th><th>프로필 갱신</th><th></th></tr></thead><tbody>{list.map(i=>{ const miss=sel.searchReadiness(i); return <tr key={i.id}>
      <td><div className="row" style={{gap:8}}><Avatar src={i.photo} name={i.name} size={30}/><div><b>{i.name}</b><div className="meta">{i.handle}</div></div></div></td>
      <td>{sel.isListed(i)?<span className="badge ok">노출 중</span>:<span className="badge plain" title={miss.join(', ')}>{i.visibility!=='public'?'비공개':'요건 부족'}</span>}{miss.length>0 && <div className="meta">{miss.join(', ')}</div>}</td>
      <td><StatusBadge inf={i} compact/></td>
      <td className="meta">{i.channels.map(c=><div key={c.type}>{sel.ch(c.type).short} {c.ownership?.verified?'확인 '+fmt.dateY(c.ownership.at):'미확인'}</div>)}</td>
      <td className="meta">{sel.improveHints(i).join(', ')||'—'}</td>
      <td className="meta">{fmt.dateY(i.profileUpdatedAt)}</td>
      <td><button className="btn sm" onClick={()=>go('/admin/verify?id='+i.id)}>확인·갱신</button></td></tr>; })}</tbody></table></div></div>; }

function AdminVerify(){ useStore(); const r=useRoute(); const st=window.STRO.state; const queue=st.influencers.filter(i=>i.channels.some(c=>!c.ownership?.verified)||sel.isStale(i)||sel.improveHints(i).length);
  const [cur,setCur]=useState(r.q.id||queue[0]?.id); const inf=sel.inf(cur); const [req,setReq]=useState([]); const [days,setDays]=useState(st.ops.staleDays);
  return <div className="page wide"><PageHead title="정보 확인·갱신" desc="확인한 항목에만 ‘운영자 확인’을 적용합니다. 채널 소유 확인과 수치 확인은 별도입니다."/>
    {!LIVE && <div className="card card-pad row" style={{gap:10,flexWrap:'wrap',marginBottom:16}}><b>운영 설정</b><span className="meta">협업 상태 재확인 기준</span><div className="input-group" style={{width:120}}><input type="number" min="7" value={days} onChange={e=>setDays(Number(e.target.value))} aria-label="재확인 기준 일수"/><span className="affix">일</span></div><button className="btn sm" onClick={()=>{ if(days<7){ toast('7일 이상으로 설정해 주세요.',{type:'err'}); return; } api.setOps({staleDays:days}); toast('재확인 기준을 변경했습니다.'); }}>적용</button><span className="meta">기준이 지나면 ‘재확인 필요’로 표시만 하며 계정을 삭제하지 않습니다.</span></div>}
    <div className="m1" style={{display:'grid',gridTemplateColumns:'280px minmax(0,1fr)',gap:16,alignItems:'start'}}>
      <div className="card">{queue.map(i=><button key={i.id} className="row" style={{width:'100%',padding:'10px 14px',border:0,borderBottom:'1px solid var(--line)',background:cur===i.id?'var(--bg-2)':'none',cursor:'pointer',textAlign:'left',gap:8}} onClick={()=>setCur(i.id)}><Avatar src={i.photo} name={i.name} size={30}/><div style={{flex:1,minWidth:0}}><b style={{fontSize:13}}>{i.name}</b><div className="meta">{[i.channels.some(c=>!c.ownership?.verified)&&'소유 미확인',sel.isStale(i)&&'재확인 필요',sel.improveHints(i).length&&'보완 필요'].filter(Boolean).join(' · ')}</div></div></button>)}{queue.length===0 && <Empty icon="checkC" title="확인 대기 없음"/>}</div>
      {inf && <div className="col gap-12">
        <div className="card"><div className="card-head"><h3>{inf.name} · 채널 확인</h3><StatusBadge inf={inf}/></div><table className="table"><thead><tr><th>채널</th><th>채널 소유</th><th>{'구독자·팔로워'}</th><th></th></tr></thead><tbody>{inf.channels.map(c=><tr key={c.type}><td><div className="row" style={{gap:6}}><ChannelIcon type={c.type} size={22}/><b>{c.name}</b></div><div className="meta">{c.url}</div></td>
          <td>{c.ownership?.verified?<span className="src"><Icon name="shield" size={11}/>확인 · {fmt.dateY(c.ownership.at)}</span>:<button className="btn sm" onClick={async()=>{ const r=await Promise.resolve(api.opsVerify(inf.id,c.type,'ownership')); if(r && r.ok===false){ toast(r.error,{type:'err'}); return; } toast('채널 소유를 확인으로 기록했습니다.'); }}>소유 확인 기록</button>}</td>
          <td><span className="num">{fmt.num(c.followers)}</span> <SourceTag source={c.followersSource} at={c.followersAsOf}/></td>
          <td>{c.followersSource!=='ops' && <button className="btn sm" onClick={async()=>{ const r=await Promise.resolve(api.opsVerify(inf.id,c.type,'followers')); if(r && r.ok===false){ toast(r.error,{type:'err'}); return; } toast('수치를 운영자 확인으로 기록했습니다.'); }}>수치 확인 기록</button>}</td></tr>)}</tbody></table>
          <p className="meta" style={{padding:'8px 16px'}}>{LIVE?'제출된 캡처·인증 절차를 확인한 뒤 기록해 주세요. 수치 확인은 현재 입력된 숫자를 그대로 기록하며, 인플루언서가 숫자를 바꾸면 다시 ‘본인 입력’으로 표시됩니다. 콘텐츠 품질·광고 성과를 인증하지 않습니다.':'시연: 실제로는 제출된 캡처·인증 절차를 확인한 뒤 기록합니다. 콘텐츠 품질·광고 성과를 인증하지 않습니다.'}</p></div>
        {!LIVE && <div className="card card-pad col gap-8"><b>본인 정보 갱신 요청</b><div className="chips">{['협업 상태','희망 단가','2차 활용 조건','채널 수치','부가세 포함 여부','대표 콘텐츠'].map(x=><button key={x} className={'chip sm '+(req.includes(x)?'on':'')} aria-pressed={req.includes(x)} onClick={()=>setReq(req.includes(x)?req.filter(y=>y!==x):[...req,x])}>{x}</button>)}</div><div><button className="btn primary sm" disabled={!req.length} onClick={()=>{ api.requestUpdate(inf.id,req); setReq([]); toast('갱신 요청을 보냈습니다. (앱 내 알림 · 이메일 미발송)'); }}>갱신 요청 보내기</button></div>
          <p className="meta">운영자는 인플루언서의 광고료를 대신 정하거나 수정하지 않습니다.</p></div>}
        <div className="card card-pad"><b>검색 노출 상태</b><p className="meta" style={{marginTop:4}}>{sel.isListed(inf)?'광고주 검색에 노출 중':`미노출 — ${inf.visibility!=='public'?'본인 비공개 설정':'요건 부족: '+sel.searchReadiness(inf).join(', ')}`}</p></div>
      </div>}
    </div></div>; }

function AdminReports(){ useStore(); const st=window.STRO.state; const [f,setF]=useState('open');
  const list=st.reports.filter(r=>f==='all'||r.status===f).sort((a,b)=>b.at.localeCompare(a.at));
  return <div className="page"><PageHead title="오류·신고" desc="플랫폼 오류, 잘못된 정보 신고, 본인 정보 확인 요청을 처리합니다."/>
    <div className="row" style={{marginBottom:12}}><Seg value={f} onChange={setF} options={[['open','처리 대기'],['done','처리 완료'],['all','전체']]}/></div>
    <div className="card">{list.length===0?<Empty icon="checkC" title="해당하는 접수 건이 없습니다"/>:<table className="table"><thead><tr><th>유형</th><th>대상</th><th>내용</th><th>접수</th><th>상태</th><th></th></tr></thead><tbody>{list.map(r=><tr key={r.id}><td><span className="badge plain">{r.type==='bug'?'플랫폼 오류':r.type==='update'?'정보 확인 요청':'정보 신고'}</span></td><td>{r.targetId?<button className="link" onClick={()=>go('/admin/verify?id='+r.targetId)}>{sel.inf(r.targetId)?.name}</button>:'—'}</td><td><b style={{fontSize:13}}>{r.reason}</b><div className="meta">{r.detail}</div><div className="meta">{r.from}</div></td><td className="meta">{fmt.dateY(r.at)}</td><td>{r.status==='open'?<span className="badge warn">대기</span>:<span className="badge ok">완료</span>}</td><td>{r.status==='open' && <button className="btn sm" onClick={()=>{ api.resolveReport(r.id,'done'); toast('처리 완료로 기록했습니다.'); }}>처리 완료</button>}</td></tr>)}</tbody></table>}</div></div>; }

function AdminUsage(){ useStore(); const st=window.STRO.state;
  const k=[['공개 프로필',st.influencers.filter(sel.isListed).length],['미노출 프로필',st.influencers.filter(i=>!sel.isListed(i)).length],['광고주 계정',st.accounts.length],['후보 보드',st.boards.length],['저장 검색',st.savedSearches.length],['제안',st.proposals.length],['Pro 시연 중',Object.values(st.plan).filter(p=>p.id==='pro').length],['이용 의향 등록',st.proInterest.length]];
  return <div className="page"><PageHead title="이용 현황" desc="이 브라우저의 시연 데이터 기준입니다. 실제 서비스 지표가 아닙니다."/><DemoBanner/>
    <div className="card kpis sec" style={{gridTemplateColumns:'repeat(4,1fr)'}}>{k.map(([l,v])=><div key={l} className="stat" style={{cursor:'default'}}><span className="l">{l}</span><span className="v">{v}</span></div>)}</div>
    {st.proInterest.length>0 && <div className="card sec"><div className="card-head"><h3>Pro 이용 의향</h3></div><table className="table"><thead><tr><th>계정</th><th>인원</th><th>빈도</th><th>희망 가격</th><th>메모</th></tr></thead><tbody>{st.proInterest.map((x,i)=><tr key={i}><td>{x.accountId}</td><td>{x.team}</td><td>{x.freq}</td><td>{x.price?fmt.won(x.price):'—'}</td><td className="meta">{x.note||'—'}</td></tr>)}</tbody></table></div>}</div>; }

Object.assign(window, {AdminProfiles, AdminVerify, AdminReports, AdminUsage});
