/* =========================================================
   STRO 실제 서비스 전용 화면 조각 (index.html 에서만 사용)
   - 기존 디자인 클래스(card, btn, alert, empty, field …)만 사용합니다.
   ========================================================= */
const LIVE_ON = !!window.STRO.LIVE;
const LV = window.STRO.live;

/* 서버 연결 전 기능 안내 */
function LiveSoon({title}){ const s=window.STRO.state.session;
  return <div className="page narrow"><Empty icon="clock" title="준비 중인 기능입니다" desc={`${title||'이 기능'}은(는) 서버 연결 작업이 끝난 뒤 제공됩니다. 지금은 회원가입·로그인·프로필 등록과 인플루언서 검색·조건 비교를 이용할 수 있습니다.`}
    action={<button className="btn" onClick={()=>go(logoHome())}>{s?'내 화면으로':'처음으로'}</button>}/></div>; }

/* 시작할 때: 로그인 상태·공개 프로필 불러오기 */
function BootScreen(){ const L=window.STRO.state.live||{};
  if(L.boot==='error') return <div className="page narrow" style={{paddingTop:64}}><div style={{display:'flex',justifyContent:'center',marginBottom:12}}><Logo to="/"/></div><ErrorBox text={L.error||'서버에 연결하지 못했습니다.'} onRetry={()=>LV.boot()}/></div>;
  return <div className="page narrow" style={{paddingTop:96,textAlign:'center'}} aria-busy="true"><div style={{display:'flex',justifyContent:'center',marginBottom:20}}><Logo to="/"/></div><span className="spin" style={{width:22,height:22}}/><p className="muted" style={{marginTop:12}}>불러오는 중…</p></div>; }

/* 메일 링크 처리 결과 안내 (한 번만) */
function LiveNotice(){ useStore(); const L=window.STRO.state.live||{};
  useEffect(()=>{ if(L.notice){ const n=L.notice; L.notice=null; toast(n.text, {type:n.kind==='err'?'err':undefined, duration:6000}); } },[L.notice]);
  return null; }

/* 개발 서버 표시 (운영 서버에서는 표시 안 함) */
function LiveEnvBar(){ const E=window.STRO_ENV||{}; if(E.target==='prod') return null;
  return <div className="demo-clock env-badge no-print" role="note">{E.missing?'서버 연결 설정 없음':`${E.label||'개발'} 서버 · 테스트용 데이터`}</div>; }

/* 비동기 버튼 공통: 처리 중 표시 + 실패 문구 + 다시 시도 */
function useBusy(){ const [busy,setBusy]=useState(false); const [err,setErr]=useState(''); const lastRef=useRef(null);
  const exec=async(fn)=>{ if(busy) return null; lastRef.current=fn; setBusy(true); setErr(''); let r; try{ r=await fn(); }catch(e){ r={ok:false, error:LV?LV.errText(e):'요청을 처리하지 못했습니다.'}; } setBusy(false); if(r && r.ok===false && r.error) setErr(r.error); return r; };
  const retry=()=>lastRef.current && exec(lastRef.current);
  return {busy, err, setErr, exec, retry}; }
function SaveError({err, onRetry}){ if(!err) return null; return <Alert kind="err" action={onRetry && <button className="btn sm" onClick={onRetry}><Icon name="refresh" size={14}/>다시 시도</button>}>{err} 입력한 내용은 그대로 남아 있습니다.</Alert>; }

/* 새 비밀번호 설정 (재설정 메일 링크로 들어온 경우) */
function NewPasswordPage(){ useStore(); const st=window.STRO.state; const [pw,setPw]=useState(''); const [pw2,setPw2]=useState(''); const [fe,setFe]=useState({}); const b=useBusy(); const [done,setDone]=useState(false);
  const can = st.session && st.live?.recovery;
  const submit=async e=>{ e.preventDefault(); const x={}; if(pw.length<8) x.pw='비밀번호는 8자 이상이어야 합니다.'; if(pw!==pw2) x.pw2='비밀번호가 일치하지 않습니다.'; setFe(x); if(Object.keys(x).length) return;
    const r=await b.exec(()=>LV.updatePassword(pw)); if(r&&r.ok){ setDone(true); toast('비밀번호를 변경했습니다.'); } };
  return <AuthLayout side={<div/>}><div className="col gap-16">
    <div><h1 style={{fontSize:24,fontWeight:700}}>새 비밀번호 설정</h1><p className="muted" style={{marginTop:4}}>앞으로 로그인할 때 사용할 비밀번호를 입력해 주세요.</p></div>
    {done ? <><Alert kind="ok" title="비밀번호를 변경했습니다">새 비밀번호로 로그인된 상태입니다.</Alert><button className="btn primary lg" onClick={()=>go(LV.homeOf(st.session))}>내 화면으로 이동</button></>
    : !can ? <><Alert kind="warn" title="재설정 링크로 들어와 주세요">비밀번호 재설정 메일의 링크를 눌러야 이 화면을 사용할 수 있습니다. 링크가 만료되었다면 다시 요청해 주세요.</Alert><button className="btn lg" onClick={()=>go('/reset')}>재설정 메일 다시 받기</button></>
    : <form className="col gap-16" onSubmit={submit} noValidate>
      <Field label="새 비밀번호" req error={fe.pw} hint="8자 이상" htmlFor="np-pw"><input id="np-pw" className={'input '+(fe.pw?'invalid':'')} type="password" autoComplete="new-password" value={pw} onChange={e=>setPw(e.target.value)}/></Field>
      <Field label="새 비밀번호 확인" req error={fe.pw2} htmlFor="np-pw2"><input id="np-pw2" className={'input '+(fe.pw2?'invalid':'')} type="password" autoComplete="new-password" value={pw2} onChange={e=>setPw2(e.target.value)}/></Field>
      {b.err && <Alert kind="err">{b.err}</Alert>}
      <button className="btn primary lg block" disabled={b.busy}>{b.busy?<><span className="spin"/>변경 중</>:'비밀번호 변경'}</button></form>}
  </div></AuthLayout>; }

/* 가입 후 인증 메일 안내 */
function CheckEmailPanel({email}){ const b=useBusy(); const [sent,setSent]=useState(false);
  return <div className="col gap-16"><div className="empty" style={{padding:0,alignItems:'flex-start',textAlign:'left'}}><div className="ico" style={{background:'var(--accent-weak)',color:'var(--accent)'}}><Icon name="send" size={22}/></div></div>
    <h1 style={{fontSize:24,fontWeight:700}}>인증 메일을 보냈습니다</h1>
    <p className="muted pretty"><b style={{color:'var(--ink)'}}>{email}</b> 주소로 보낸 메일의 <b style={{color:'var(--ink)'}}>인증 링크</b>를 누르면 가입이 완료됩니다.</p>
    <ul className="col gap-6 meta" style={{margin:0,paddingLeft:18}}><li>메일이 보이지 않으면 스팸함·프로모션함을 확인해 주세요.</li><li>가입한 이 브라우저에서 링크를 열면 바로 로그인됩니다.</li><li>링크는 일정 시간이 지나면 만료됩니다.</li></ul>
    {sent && <Alert kind="ok">인증 메일을 다시 보냈습니다.</Alert>}{b.err && <Alert kind="err">{b.err}</Alert>}
    <div className="row wrap" style={{gap:8}}><button className="btn" disabled={b.busy} onClick={async()=>{ setSent(false); const r=await b.exec(()=>LV.resendConfirm(email)); if(r&&r.ok) setSent(true); }}>{b.busy?<><span className="spin"/>보내는 중</>:'인증 메일 다시 보내기'}</button><button className="btn ghost" onClick={()=>go('/login')}>로그인 화면으로</button></div></div>; }

/* 프로필 사진: 올리기·바꾸기·삭제 (본인만, 서버 권한으로 한 번 더 검사) */
function PhotoField({inf}){ const ref=useRef(); const b=useBusy();
  const pick=async e=>{ const f=e.target.files&&e.target.files[0]; e.target.value=''; if(!f) return; const bad=LV.checkImage(f); if(bad){ b.setErr(bad); return; } const r=await b.exec(()=>LV.setProfilePhoto(f)); if(r&&r.ok) toast('프로필 사진을 저장했습니다.'); };
  return <div className="col gap-8"><div className="row" style={{gap:12,flexWrap:'wrap'}}>
    <img src={inf.photo} alt="" style={{width:64,height:64,borderRadius:12,objectFit:'cover',background:'var(--bg-3)'}}/>
    <input ref={ref} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={pick} aria-label="프로필 사진 파일"/>
    <button type="button" className="btn sm" disabled={b.busy} onClick={()=>ref.current.click()}>{b.busy?<><span className="spin"/>올리는 중</>:inf.hasPhoto?'사진 바꾸기':'사진 올리기'}</button>
    {inf.hasPhoto && <button type="button" className="btn sm ghost danger" disabled={b.busy} onClick={async()=>{ if(!(await confirmDialog({title:'프로필 사진을 삭제할까요?', body:'삭제하면 기본 이미지가 표시됩니다.', okText:'삭제', danger:true}))) return; const r=await b.exec(()=>LV.removeProfilePhoto()); if(r&&r.ok) toast('프로필 사진을 삭제했습니다.'); }}>삭제</button>}
    <span className="meta">JPG·PNG·WEBP · 10MB 이하 (자동으로 줄여 저장)</span></div>
    {b.err && <Alert kind="err">{b.err}</Alert>}</div>; }

/* 대표 콘텐츠 썸네일 올리기 */
function ThumbUpload({item, onChange}){ const ref=useRef(); const b=useBusy();
  const pick=async e=>{ const f=e.target.files&&e.target.files[0]; e.target.value=''; if(!f) return; const bad=LV.checkImage(f); if(bad){ toast(bad,{type:'err'}); return; } const r=await b.exec(()=>LV.uploadImage(f,'portfolio')); if(r&&r.ok) onChange({...item, thumbPath:r.path, thumb:r.url}); else if(r&&r.error) toast(r.error,{type:'err'}); };
  return <><input ref={ref} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={pick} aria-label="대표 콘텐츠 썸네일 파일"/>
    <button className="btn" style={{height:'auto',padding:0,overflow:'hidden',aspectRatio:'4/3'}} disabled={b.busy} onClick={()=>ref.current.click()} aria-label="썸네일 올리기">{b.busy?<span className="spin"/>:item.thumb?<img src={item.thumb} alt="" style={{width:'100%',height:'100%',objectFit:'cover'}}/>:<span className="meta">썸네일 올리기</span>}</button></>; }

/* 회원 탈퇴 (즉시 완전 삭제) */
function DeleteAccountSection(){ const s=window.STRO.state.session; const [open,setOpen]=useState(false); const [pw,setPw]=useState(''); const [ok,setOk]=useState(false); const b=useBusy();
  if(!s || s.role==='admin') return null;
  const items = s.role==='influencer' ? ['로그인 계정과 이메일','공개·비공개 프로필과 협업 조건','올린 프로필 사진·대표 콘텐츠 사진','운영자 확인 기록'] : ['로그인 계정과 이메일','회사 정보와 등록한 브랜드'];
  const close=()=>{ if(b.busy) return; setOpen(false); setPw(''); setOk(false); b.setErr(''); };
  return <section className="card sec"><div className="card-head"><h3>회원 탈퇴</h3></div><div className="card-body col gap-8">
    <p className="meta">탈퇴하면 계정과 관련 정보가 <b>즉시 완전히 삭제</b>되며 되돌릴 수 없습니다.</p>
    <div><button className="btn ghost danger" onClick={()=>setOpen(true)}>회원 탈퇴</button></div></div>
    <Modal open={open} onClose={close} title="정말 탈퇴할까요?" foot={<><button className="btn" onClick={close} disabled={b.busy}>취소</button><button className="btn danger-solid" disabled={!ok||!pw||b.busy} onClick={async()=>{ const r=await b.exec(()=>LV.deleteAccount(pw)); if(r&&r.ok){ setOpen(false); go('/'); toast('탈퇴가 완료되었습니다. 이용해 주셔서 감사합니다.'); } }}>{b.busy?<><span className="spin"/>삭제 중</>:'즉시 탈퇴'}</button></>}>
      <div className="col gap-12"><Alert kind="warn" title="아래 정보가 즉시 삭제되며 복구할 수 없습니다"><ul style={{margin:'4px 0 0',paddingLeft:18}}>{items.map(x=><li key={x}>{x}</li>)}</ul></Alert>
        <Field label="비밀번호 확인" req htmlFor="del-pw"><input id="del-pw" className="input" type="password" autoComplete="current-password" value={pw} onChange={e=>setPw(e.target.value)}/></Field>
        <label className="check"><input type="checkbox" checked={ok} onChange={e=>setOk(e.target.checked)}/>삭제된 정보는 되돌릴 수 없다는 것을 확인했습니다.</label>
        {b.err && <Alert kind="err">{b.err}</Alert>}</div></Modal></section>; }

Object.assign(window, {LIVE_ON, LiveSoon, BootScreen, LiveNotice, LiveEnvBar, useBusy, SaveError, NewPasswordPage, CheckEmailPanel, PhotoField, ThumbUpload, DeleteAccountSection});
