/* =========================================================
   STRO 공통 UI 컴포넌트
   ========================================================= */
const {useState, useEffect, useRef, useMemo, useCallback, createContext, useContext, Fragment} = React;
const {api, sel, fmt, SEED, CFG} = window.STRO;
/* 실제 서비스(index.html)이면 true. 서버 연결 전 기능은 이 값으로 숨깁니다. */
const LIVE = !!window.STRO.LIVE;
const LIVE_PATHS = ['/adv/find','/settings','/inf/profile','/inf/conditions','/admin/profiles','/admin/verify'];

/* ---------- store hook ---------- */
function useStore(){ const [,set]=useState(0); useEffect(()=>api.subscribe(()=>set(x=>x+1)),[]); return window.STRO.state; }

/* ---------- router (hash) ---------- */
function parseHash(){ const h=(location.hash||'#/').slice(1)||'/'; const [path, qs]=h.split('?'); const q={}; (qs||'').split('&').filter(Boolean).forEach(p=>{const [k,v]=p.split('='); q[decodeURIComponent(k)]=decodeURIComponent(v||'');}); return {path, q, full:h}; }
function useRoute(){ const [r,setR]=useState(parseHash()); useEffect(()=>{ const f=()=>{ setR(parseHash()); document.querySelector('.main')?.scrollTo?.(0,0); window.scrollTo(0,0); }; window.addEventListener('hashchange',f); return ()=>window.removeEventListener('hashchange',f); },[]); return r; }
function go(path){ location.hash = '#'+path; }
function match(pattern, path){ const a=pattern.split('/'), b=path.split('/'); if(a.length!==b.length) return null; const p={}; for(let i=0;i<a.length;i++){ if(a[i].startsWith(':')) p[a[i].slice(1)]=decodeURIComponent(b[i]); else if(a[i]!==b[i]) return null; } return p; }
function setQuery(patch){ const r=parseHash(); const q={...r.q, ...patch}; Object.keys(q).forEach(k=>{ if(q[k]===''||q[k]==null) delete q[k]; }); const s=Object.entries(q).map(([k,v])=>`${k}=${encodeURIComponent(v)}`).join('&'); history.replaceState(null,'','#'+r.path+(s?'?'+s:'')); window.dispatchEvent(new HashChangeEvent('hashchange')); }

/* ---------- Icons (stroke, 24 grid) ---------- */
const ICONS = {
  home:'M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z',
  search:'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM21 21l-4.3-4.3',
  inbox:'M22 12h-6l-2 3h-4l-2-3H2M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z',
  send:'M22 2 11 13M22 2l-7 20-4-9-9-4z',
  list:'M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01',
  layers:'m12 2 10 5-10 5L2 7zM2 17l10 5 10-5M2 12l10 5 10-5',
  chat:'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z',
  wallet:'M20 7H5a2 2 0 0 1 0-4h13v4M3 5v14a2 2 0 0 0 2 2h15V7M16 14h.01',
  user:'M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z',
  users:'M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M9 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75',
  tag:'M20.59 13.41 13.42 20.58a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82zM7 7h.01',
  briefcase:'M20 7H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2zM16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16',
  heart:'M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z',
  bookmark:'M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z',
  settings:'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z',
  bell:'M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 0 1-3.46 0',
  plus:'M12 5v14M5 12h14', check:'M20 6 9 17l-5-5', x:'M18 6 6 18M6 6l12 12', chevR:'m9 18 6-6-6-6', chevL:'m15 18-6-6 6-6', chevD:'m6 9 6 6 6-6', arrowR:'M5 12h14M12 5l7 7-7 7', arrowL:'M19 12H5M12 19l-7-7 7-7',
  info:'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM12 16v-4M12 8h.01', alert:'M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0zM12 9v4M12 17h.01', alertC:'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM12 8v4M12 16h.01', checkC:'M22 11.08V12a10 10 0 1 1-5.93-9.14M22 4 12 14.01l-3-3',
  calendar:'M19 4H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM16 2v4M8 2v4M3 10h18', clock:'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM12 6v6l4 2',
  link:'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71', ext:'M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3',
  upload:'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12', file:'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6', image:'M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21',
  edit:'M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z', trash:'M3 6h18M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6M10 11v6M14 11v6M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2',
  eye:'M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', eyeOff:'M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19M1 1l22 22',
  lock:'M19 11H5a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2zM7 11V7a5 5 0 0 1 10 0v4', globe:'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z',
  filter:'M22 3H2l8 9.46V19l4 2v-8.54z', sort:'M3 6h18M6 12h12M10 18h4', grid:'M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z', columns:'M12 3v18M3 3h18v18H3z',
  refresh:'M23 4v6h-6M1 20v-6h6M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15', logout:'M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9',
  shield:'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z', sparkle:'M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8',
  play:'M5 3l14 9-14 9z', flag:'M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1zM4 22v-7', box:'M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16zM3.27 6.96 12 12.01l8.73-5.05M12 22.08V12',
  pin:'M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0zM12 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', note:'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M16 13H8M16 17H8M10 9H8', clip:'M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48', more:'M12 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2zM19 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2zM5 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2z',
  dash:'M3 3h7v9H3zM14 3h7v5h-7zM14 12h7v9h-7zM3 16h7v5H3z', store:'M3 9l1-5h16l1 5M3 9h18v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1zM3 9a3 3 0 0 0 6 0 3 3 0 0 0 6 0 3 3 0 0 0 6 0', megaphone:'M3 11v2a1 1 0 0 0 1 1h2l5 4V6L6 10H4a1 1 0 0 0-1 1zM15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13',
};
function Icon({name, size=18, stroke=1.8, style, className}){ const d0=ICONS[name]||ICONS.info; const d=d0[0]==='m'?'M'+d0.slice(1):d0; return <svg className={className} style={style} width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{d.split('M').filter(Boolean).map((p,i)=><path key={i} d={'M'+p}/>)}</svg>; }

/* ---------- toasts ---------- */
const toastBus = new Set();
function toast(text, opt={}){ toastBus.forEach(f=>f({id:Math.random(), text, ...opt})); }
function Toasts(){ const [list,setList]=useState([]); useEffect(()=>{ const f=t=>{ setList(l=>[...l,t]); setTimeout(()=>setList(l=>l.filter(x=>x.id!==t.id)), t.duration||3200); }; toastBus.add(f); return ()=>toastBus.delete(f); },[]);
  return <div className="toasts" role="status" aria-live="polite">{list.map(t=><div key={t.id} className={'toast '+(t.type||'')}><Icon name={t.type==='err'?'alertC':'checkC'} size={16}/>{t.text}{t.demo && <span className="demo">시연</span>}</div>)}</div>; }

/* ---------- modal ---------- */
function Modal({open, onClose, title, sub, children, foot, size, labelledBy}){
  const ref=useRef(); useEffect(()=>{ if(!open) return; const prev=document.activeElement; const k=e=>{ if(e.key==='Escape') onClose?.(); }; document.addEventListener('keydown',k); setTimeout(()=>{ const el=ref.current?.querySelector('input,textarea,select,button.primary,button'); el?.focus(); },30); return ()=>{ document.removeEventListener('keydown',k); prev?.focus?.(); }; },[open]);
  if(!open) return null;
  return <div className="overlay" onMouseDown={e=>{ if(e.target===e.currentTarget) onClose?.(); }}>
    <div className={'modal '+(size||'')} role="dialog" aria-modal="true" aria-label={typeof title==='string'?title:undefined} ref={ref}>
      <div className="modal-head"><div style={{flex:1}}><h2>{title}</h2>{sub && <p className="muted" style={{marginTop:4,fontSize:13}}>{sub}</p>}</div><button className="btn ghost sm icon" onClick={onClose} aria-label="닫기"><Icon name="x"/></button></div>
      <div className="modal-body">{children}</div>
      {foot && <div className="modal-foot">{foot}</div>}
    </div></div>;
}
/* confirm dialog via promise */
const confirmBus={f:null};
function confirmDialog(opts){ return new Promise(res=>confirmBus.f?.({...opts, res})); }
function ConfirmHost(){ const [o,setO]=useState(null); useEffect(()=>{ confirmBus.f=setO; },[]); if(!o) return null; const close=v=>{ o.res(v); setO(null); };
  return <Modal open title={o.title} onClose={()=>close(false)} foot={<><button className="btn" onClick={()=>close(false)}>{o.cancelText||'취소'}</button><button className={'btn '+(o.danger?'danger-solid':'primary')} onClick={()=>close(true)}>{o.okText||'확인'}</button></>}>
    <div className="pretty" style={{color:'var(--ink-2)'}}>{o.body}</div></Modal>; }

/* ---------- small primitives ---------- */
function Badge({kind, map, children}){ if(map==='proposal'){ const [t,c]=CFG.PROPOSAL_STATUS[kind]||[kind,'']; return <span className={'badge '+c}>{t}</span>; } return <span className={'badge '+(kind||'')}>{children}</span>; }
/* 협업 상태 + 갱신일 + 재확인 필요 */
function StatusBadge({inf, compact}){ const v=sel.statusView(inf); return <span className="row" style={{gap:6,flexWrap:'wrap'}}><span className={'badge '+v.kind}>{v.label}</span>{v.stale && <span className="badge warn plain" title={`상태 갱신 후 ${window.STRO.state.ops.staleDays}일이 지났습니다`}>재확인 필요</span>}{!compact && <span className="meta">상태 갱신 {fmt.dateY(v.updated)}</span>}</span>; }
function DemoTag({children='시연 데이터'}){ return <span className="demo-chip" title="프로토타입 시연용 가상 데이터">{children}</span>; }
function Avatar({src, name, size=40}){ if(src) return <img className="avatar" src={src} alt="" width={size} height={size} style={{width:size,height:size}}/>; return <div className="avatar" style={{width:size,height:size,display:'flex',alignItems:'center',justifyContent:'center',fontWeight:700,color:'var(--ink-3)',fontSize:size*.38}}>{(name||'?').slice(0,1)}</div>; }
function BrandLogo({brand, size=40}){ if(!brand) return null; return <div className="mono-logo" style={{width:size,height:size,background:brand.color||'#EEE',color:brand.ink||'#333',fontSize:size*(brand.initials?.length>2?.26:.32)}}>{brand.initials||brand.name?.slice(0,2)}</div>; }
function ChannelIcon({type, size=26}){ const c=sel.ch(type); return <span className="channel-ico" style={{background:c.color,width:size,height:size,fontSize:size*.38}} title={c.label} aria-label={c.label}>{c.short}</span>; }
function SourceTag({source, at}){ const map={self:['본인 입력','edit'], ops:['운영자 확인','shield'], linked:['외부 연동','link']}; const [t,i]=map[source]||map.self; return <span className="src" title={source==='self'?'인플루언서가 직접 입력한 정보입니다.':source==='ops'?'STRO 운영자가 해당 항목만 확인했습니다. 콘텐츠 품질·성과를 보증하지 않습니다.':'외부 서비스 연동으로 받은 정보입니다. (시연 데이터)'}><Icon name={i} size={11}/>{t}{at?' · '+fmt.dateY(at):''}</span>; }
function Field({label, req, optional, hint, error, children, className, htmlFor}){ return <div className={'field '+(className||'')}>{label && <label htmlFor={htmlFor}>{label}{req && <span className="req" aria-label="필수">*</span>}{optional && <span className="opt">선택</span>}</label>}{children}{error ? <div className="err-msg" role="alert"><Icon name="alertC" size={13}/>{error}</div> : hint ? <div className="hint">{hint}</div> : null}</div>; }
function Chips({options, value=[], onChange, max, single, size, labels, disabled}){
  const toggle=o=>{ if(single){ onChange(value===o?'':o); return; } const on=value.includes(o); if(on) onChange(value.filter(x=>x!==o)); else { if(max && value.length>=max){ toast(`최대 ${max}개까지 선택할 수 있어요.`, {type:'err'}); return; } onChange([...value,o]); } };
  return <div className="chips" role="group">{options.map(o=>{ const on= single? value===o : value.includes(o); return <button type="button" key={o} className={'chip '+(on?'on ':'')+(size||'')} aria-pressed={on} onClick={()=>toggle(o)} disabled={disabled}>{on && <Icon name="check" size={13} stroke={2.4}/>}{labels?labels[o]:o}</button>; })}</div>;
}
function ChipsWithCustom({options, value=[], onChange, max, placeholder='직접 입력 후 Enter'}){
  const [t,setT]=useState(''); const extra=value.filter(v=>!options.includes(v));
  const add=()=>{ const v=t.trim(); if(!v) return; if(value.includes(v)){ setT(''); return; } if(max && value.length>=max){ toast(`최대 ${max}개까지 선택할 수 있어요.`, {type:'err'}); return; } onChange([...value, v]); setT(''); };
  return <div className="col gap-12"><Chips options={[...options, ...extra]} value={value} onChange={onChange} max={max}/>
    <div className="row" style={{maxWidth:360}}><input className="input" value={t} onChange={e=>setT(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter'){ e.preventDefault(); add(); } }} placeholder={placeholder} aria-label="직접 입력"/><button type="button" className="btn" onClick={add}>추가</button></div></div>;
}
function Switch({checked, onChange, label}){ return <button type="button" role="switch" aria-checked={!!checked} aria-label={label} className="switch" onClick={()=>onChange(!checked)}/>; }
function Seg({options, value, onChange}){ return <div className="seg" role="group">{options.map(([v,l])=><button key={v} type="button" aria-pressed={value===v} onClick={()=>onChange(v)}>{l}</button>)}</div>; }
function Tabs({tabs, value, onChange}){ return <div className="tabs" role="tablist">{tabs.map(t=><button key={t.id} role="tab" className="tab" aria-selected={value===t.id} onClick={()=>onChange(t.id)}>{t.label}{t.n!==undefined && <span className="n">{t.n}</span>}</button>)}</div>; }
/* 모바일에서는 탭 대신 선택 메뉴 */
function TabsR(props){ const m=useMobile(); if(!m) return <Tabs {...props}/>; const {tabs,value,onChange}=props; return <div style={{marginBottom:16}}><label className="sr-only" htmlFor="tabsel">보기 선택</label><select id="tabsel" className="select" value={value} onChange={e=>onChange(e.target.value)} style={{fontWeight:600}}>{tabs.map(t=><option key={t.id} value={t.id}>{t.label}{t.n!==undefined?` (${t.n})`:''}</option>)}</select></div>; }
function Empty({icon='inbox', title, desc, action}){ return <div className="empty"><div className="ico"><Icon name={icon} size={24}/></div><h3>{title}</h3>{desc && <p className="pretty">{desc}</p>}{action && <div style={{marginTop:8}}>{action}</div>}</div>; }
function Skeleton({rows=3, h=64}){ return <div className="col gap-12" aria-busy="true" aria-label="불러오는 중">{Array.from({length:rows}).map((_,i)=><div key={i} className="skel" style={{height:h}}/>)}</div>; }
function ErrorBox({onRetry, text='데이터를 불러오지 못했습니다.'}){ return <div className="empty"><div className="ico" style={{background:'var(--err-bg)',color:'var(--err)'}}><Icon name="alertC" size={24}/></div><h3>{text}</h3><p>네트워크 상태를 확인한 뒤 다시 시도해 주세요. 문제가 계속되면 고객지원으로 문의해 주세요.</p><button className="btn" onClick={onRetry}><Icon name="refresh" size={15}/>다시 시도</button></div>; }
function Alert({kind='info', icon, title, children, action}){ return <div className={'alert '+kind} role={kind==='err'?'alert':undefined}><Icon name={icon||(kind==='err'?'alertC':kind==='warn'?'alert':kind==='ok'?'checkC':'info')} size={16}/><div style={{flex:1}}>{title && <b style={{display:'block',marginBottom:2}}>{title}</b>}{children}</div>{action}</div>; }
function SaveState({state, at}){ if(state==='saving') return <span className="save-state"><span className="spin"/>저장 중…</span>; if(state==='saved') return <span className="save-state" style={{color:'var(--ok)'}}><Icon name="check" size={13}/>임시저장됨 {at?at.slice(11):''}</span>; if(at) return <span className="save-state">마지막 저장 {at.slice(5).replace('-','/')}</span>; return <span className="save-state">저장 전</span>; }

/* simulated async loader: shows skeleton then content; ?fail=1 in hash simulates failure */
function useAsync(deps=[], ms=380){ const [st,setSt]=useState('loading'); const [n,setN]=useState(0); useEffect(()=>{ setSt('loading'); const fail=parseHash().q.fail==='1' && n===0; const t=setTimeout(()=>setSt(fail?'error':'ready'), ms); return ()=>clearTimeout(t); }, [...deps, n]); return {status:st, retry:()=>{ setQuery({fail:''}); setN(x=>x+1); }}; }

/* ---------- page head ---------- */
function PageHead({title, desc, crumbs, actions, eyebrow}){ return <div style={{marginBottom:24}}>
  {crumbs && <nav className="crumbs" aria-label="경로">{crumbs.map((c,i)=><span key={i} className="row" style={{gap:6}}>{i>0 && <Icon name="chevR" size={13}/>}{c.to ? <button onClick={()=>go(c.to)}>{c.label}</button> : <span>{c.label}</span>}</span>)}</nav>}
  <div className="page-head" style={{marginBottom:0}}><div>{eyebrow && <div className="eyebrow" style={{marginBottom:6}}>{eyebrow}</div>}<h1>{title}</h1>{desc && <p className="pretty">{desc}</p>}</div>{actions && <div className="row">{actions}</div>}</div></div>; }

/* ---------- Shell ---------- */
const NAV = {
  influencer:[
    ['/inf/profile','내 프로필','user'],['/inf/conditions','협업 조건·일정','calendar'],['/inf/proposals','받은 제안','inbox','props'],['/messages','메시지','chat','msgs'],['/inf/stats','노출·제안 통계','layers'],['/settings','계정 설정','settings'],
  ],
  advertiser:[
    ['/adv/find','인플루언서 찾기','search'],['/adv/boards','후보 보드','columns'],['/adv/proposals','보낸 제안','send','replies'],['/messages','메시지','chat','msgs'],['/adv/searches','저장한 검색','bookmark'],['/adv/plan','이용권','tag'],['/settings','브랜드·계정 설정','settings'],
  ],
  admin:[
    ['/admin/profiles','프로필 관리','users'],['/admin/verify','정보 확인·갱신','shield','verify'],['/admin/reports','오류·신고','flag','reports'],['/admin/usage','이용 현황','dash'],
  ],
};
function navCounts(role){ const s=window.STRO.state, ss=s.session; if(!ss) return {};
  const msgs = window.STRO.msg ? window.STRO.msg.totalUnread() : 0;
  if(role==='influencer') return {props: sel.propsOfInf(ss.profileId).filter(p=>p.status==='sent').length, msgs};
  if(role==='advertiser') return {replies: sel.propsOfAcc(ss.accountId).filter(p=>['available','accepted','counter','declined'].includes(p.status) && !p.seenByAdv).length, msgs};
  if(role==='admin') return {verify: s.influencers.filter(i=>i.channels.some(c=>!c.ownership?.verified)||sel.isStale(i)).length, reports: s.reports.filter(r=>r.status==='open').length};
  return {}; }

function NotifBell(){ useStore(); const [open,setOpen]=useState(false); const list=sel.notifs(); const unread=list.filter(n=>!n.read).length; const ref=useRef();
  useEffect(()=>{ const f=e=>{ if(ref.current && !ref.current.contains(e.target)) setOpen(false); }; document.addEventListener('mousedown',f); return ()=>document.removeEventListener('mousedown',f); },[]);
  return <div style={{position:'relative'}} ref={ref}><button className="btn ghost icon" aria-label={`알림 ${unread}개 읽지 않음`} onClick={()=>setOpen(o=>!o)} style={{position:'relative'}}><Icon name="bell" size={19}/>{unread>0 && <span style={{position:'absolute',top:6,right:7,width:8,height:8,borderRadius:'50%',background:'var(--accent)',border:'2px solid #fff'}}/>}</button>
    {open && <div className="dropdown notif-dd" style={{width:360,padding:0}}><div className="row" style={{padding:'12px 14px',borderBottom:'1px solid var(--line)'}}><b>알림</b><span className="spacer"/><button className="link muted" style={{fontSize:12}} onClick={()=>api.markAllRead()}>모두 읽음</button></div>
      <div style={{maxHeight:380,overflow:'auto'}}>{list.length===0 ? <div className="empty" style={{padding:28}}><p>새 알림이 없습니다.</p></div> : list.map(n=><button key={n.id} className="menu-item" style={{borderRadius:0,padding:'12px 14px',alignItems:'flex-start',borderBottom:'1px solid var(--line)'}} onClick={()=>{ api.markRead(n.id); setOpen(false); go(n.link); }}>
        <span style={{width:7,height:7,borderRadius:'50%',background:n.read?'transparent':'var(--accent)',marginTop:7,flex:'none'}}/><span style={{flex:1}}><span style={{display:'block',color:n.read?'var(--ink-3)':'var(--ink)'}}>{n.text}</span><span className="meta">{n.at.slice(5)}</span></span></button>)}</div>
      <div className="meta" style={{padding:'8px 14px'}}>실제 서비스에서는 이메일·푸시 알림이 함께 발송됩니다. (현재 미연동)</div></div>}
  </div>; }

function UserMenu(){ const s=window.STRO.state.session; const me=sel.me(); const [open,setOpen]=useState(false); const ref=useRef();
  useEffect(()=>{ const f=e=>{ if(ref.current && !ref.current.contains(e.target)) setOpen(false); }; document.addEventListener('mousedown',f); return ()=>document.removeEventListener('mousedown',f); },[]);
  let name=me?.name, sub='', photo='';
  if(s.role==='influencer'){ const p=sel.inf(s.profileId); name=p?.name||me?.name; photo=p?.photo; sub='인플루언서'; }
  if(s.role==='advertiser'){ const a=sel.acc(s.accountId); name=a?.contactName; sub=a?.company||'광고주'; }
  if(s.role==='admin'){ sub='STRO 운영자'; }
  return <div style={{position:'relative'}} ref={ref}><button className="row" style={{border:0,background:'none',cursor:'pointer',padding:'4px 6px',borderRadius:8}} onClick={()=>setOpen(o=>!o)} aria-haspopup="menu" aria-expanded={open}>
      <Avatar src={photo} name={name} size={32}/><span className="col hide-mobile" style={{textAlign:'left',lineHeight:1.3}}><b style={{fontSize:13}}>{name||'이름 미입력'}</b><span className="meta" style={{fontSize:11}}>{sub}</span></span><Icon name="chevD" size={14} className="hide-mobile"/></button>
    {open && <div className="dropdown" role="menu">
      {s.role!=='admin' && <button className="menu-item" onClick={()=>{setOpen(false);go('/settings');}}><Icon name="settings" size={16}/>{s.role==='advertiser'?'브랜드·계정 설정':'계정 설정'}</button>}
      <button className="menu-item" onClick={()=>{setOpen(false);go('/help');}}><Icon name="info" size={16}/>이용안내</button>
      <div className="divider" style={{margin:'6px 0'}}/>
      <button className="menu-item" onClick={async()=>{ setOpen(false); await api.logout(); go('/'); }}><Icon name="logout" size={16}/>로그아웃</button></div>}
  </div>; }

/* ---------- 공식 로고 ---------- */
function logoHome(){ const s=window.STRO.state.session; if(!s) return '/'; return s.role==='influencer'?'/inf/profile':s.role==='advertiser'?'/adv/find':'/admin/profiles'; }
function Logo({height, onClick, className, to}){
  const click = onClick || (()=>go(to||logoHome()));
  return <button className={'logo '+(className||'')} onClick={click} aria-label="STRO 스트로 홈으로"><img className="logo-img" src="assets/brand/stro-logo-h.png?v=4" alt="STRO 스트로" style={height?{height}:undefined}/></button>;
}
/* ---------- media query hook ---------- */
function useMedia(q){ const [m,setM]=useState(()=>window.matchMedia(q).matches); useEffect(()=>{ const mq=window.matchMedia(q); const f=()=>setM(mq.matches); mq.addEventListener('change',f); f(); return ()=>mq.removeEventListener('change',f); },[q]); return m; }
const useMobile = () => useMedia('(max-width: 767px)');
const useNarrow = () => useMedia('(max-width: 1023px)');

function NavList({role, onPick}){ const r=useRoute(); const guest=!window.STRO.state.session; const items=(guest?NAV.advertiser.filter(x=>x[0]==='/adv/find'||x[0]==='/adv/plan'):NAV[role]).filter(x=>!LIVE||LIVE_PATHS.includes(x[0])); const counts=navCounts(role);
  const active = p => r.path===p || (p!=='/admin' && r.path.startsWith(p+'/'));
  return <>{items.map(([p,l,ic,ck])=><button key={p} className={'nav-item '+(active(p)?'active':'')} onClick={()=>{ go(p); onPick&&onPick(); }} aria-current={active(p)?'page':undefined}><Icon name={ic} size={18}/>{l}{ck && counts[ck]>0 && <span className="count" aria-label={counts[ck]+'건'}>{counts[ck]}</span>}</button>)}</>; }

function Shell({children, role}){ useStore(); const guest=!window.STRO.state.session; const r=useRoute(); const narrow=useNarrow(); const [drawer,setDrawer]=useState(false); const counts=navCounts(role); const totalCount=Object.values(counts).reduce((a,b)=>a+b,0);
  useEffect(()=>{ setDrawer(false); },[r.path]);
  useEffect(()=>{ if(!narrow) setDrawer(false); },[narrow]);
  useEffect(()=>{ if(!drawer) return; const k=e=>{ if(e.key==='Escape') setDrawer(false); }; document.addEventListener('keydown',k); document.body.style.overflow='hidden'; return ()=>{ document.removeEventListener('keydown',k); document.body.style.overflow=''; }; },[drawer]);
  const help = <div className="card" style={{padding:12,fontSize:12,color:'var(--ink-3)',background:'var(--surface-2)',marginTop:16}}>
    <div className="row" style={{marginBottom:4}}><Icon name="info" size={14}/><b style={{color:'var(--ink-2)'}}>도움이 필요하신가요?</b></div>
    STRO는 제안 전달과 이력 관리를 지원합니다. 광고비·제작·승인·지급은 당사자가 합의합니다.<div style={{marginTop:8}}><button className="link" style={{fontSize:12}} onClick={()=>go('/help?s=support')}>오류·신고 접수 →</button></div></div>;
  return <div className="shell">
    <header className="topbar">
      {narrow && <button className="btn ghost icon hamburger" aria-label={'메뉴 열기'+(totalCount?` (확인할 항목 ${totalCount}건)`:'')} aria-expanded={drawer} aria-controls="drawer-nav" onClick={()=>setDrawer(true)} style={{position:'relative'}}><Icon name="list" size={20}/>{totalCount>0 && <span className="dot-badge"/>}</button>}
      <Logo/>
      {role==='admin' && <span className="badge dark plain">운영자</span>}
      {!narrow && <div style={{width:1,height:22,background:'var(--line)',margin:'0 4px'}}/>}
{!narrow && role==='advertiser' && !guest && !LIVE && <PlanChip/>}
      <span className="spacer"/>
      {guest ? <><span className="badge plain hide-mobile">둘러보기 · 비회원</span><button className="btn ghost sm" onClick={()=>go('/login')}>로그인</button><button className="btn primary sm" onClick={()=>go('/signup/advertiser')}>광고주 가입</button></> : <>{!LIVE && <MsgNavButton/>}{!LIVE && <NotifBell/>}<UserMenu/></>}
    </header>
    {!narrow && <nav className="sidebar" aria-label="주 메뉴"><NavList role={role}/><span className="spacer"/>{help}</nav>}
    {narrow && drawer && <div className="drawer-overlay" onMouseDown={e=>{ if(e.target===e.currentTarget) setDrawer(false); }}>
      <nav id="drawer-nav" className="drawer-nav" aria-label="주 메뉴" role="dialog" aria-modal="true">
        <div className="row" style={{padding:'10px 12px 10px 16px',borderBottom:'1px solid var(--line)'}}><b style={{fontSize:15}}>메뉴</b><span className="spacer"/><button className="btn ghost icon" aria-label="메뉴 닫기" onClick={()=>setDrawer(false)}><Icon name="x" size={20}/></button></div>
        <div style={{padding:12,display:'flex',flexDirection:'column',gap:2,overflow:'auto',flex:1}}>
          <NavList role={role} onPick={()=>setDrawer(false)}/>
          {help}
        </div></nav></div>}
    <main className="main" id="main">{children}</main>
  </div>; }

function PlanChip(){ useStore(); const p=sel.plan(); return <button className={'badge '+(p.effective==='pro'?'accent':'plain')} style={{border:0,cursor:'pointer',height:26}} onClick={()=>go('/adv/plan')} title="이용권">{p.effective==='pro'?`Pro 시연 · ${fmt.date(p.proUntil)}까지`:'Free 이용 중'}</button>; }
/* Pro 기능 잠금 안내 */
function ProGate({feature, children, title}){ if(sel.can(feature)) return children; return <div className="pro-gate"><div className="row" style={{gap:8}}><span className="badge accent plain">Pro</span><b style={{fontSize:13}}>{title||'Pro 이용권 기능입니다'}</b></div><p className="meta" style={{marginTop:4}}>가격은 검토 중입니다. 시연용 Pro 30일 이용권을 켜서 기능을 미리 써볼 수 있습니다. 실제 결제는 발생하지 않습니다.</p><div className="row" style={{marginTop:8}}><button className="btn sm" onClick={()=>go('/adv/plan')}>이용권 보기</button></div></div>; }
/* 만원 단위 금액 입력: 화면은 만원, 저장값은 원 */
function ManwonInput({value, onChange, disabled, label, invalid, width}){ const toMan=v=> (v===''||v===null||v===undefined)?'':String(Math.round(Number(v)/10000*10)/10);
  return <div className="input-group" style={{width, flex:width?'none':'1 1 0', minWidth:0, borderColor:invalid?'var(--err)':undefined}}><input type="number" inputMode="decimal" min="0" step="1" value={toMan(value)} disabled={disabled} aria-label={label} aria-invalid={invalid} onChange={e=>{ const v=e.target.value; onChange(v===''?'':Math.round(Number(v)*10000)); }}/><span className="affix">만원</span></div>; }
Object.assign(window, {LIVE, LIVE_PATHS, StatusBadge, PlanChip, ProGate, TabsR, Logo, logoHome, useMedia, useMobile, useNarrow, ManwonInput, useStore, useRoute, go, match, setQuery, parseHash, Icon, toast, Toasts, Modal, confirmDialog, ConfirmHost, Badge, DemoTag, Avatar, BrandLogo, ChannelIcon, SourceTag, Field, Chips, ChipsWithCustom, Switch, Seg, Tabs, Empty, Skeleton, ErrorBox, Alert, SaveState, useAsync, PageHead, Shell});
