// 서비스 선택 온보딩 — Q(스크린) / QR(연습장·아카데미)

function OnboardingScreen({ onSelect }){
  return (
    <div className="screen" style={{background:"#0D1410"}}>
      <StatusBar onNavy={true}/>
      <div style={{
        flex:1,
        display:"flex",flexDirection:"column",justifyContent:"flex-start",
        padding:"80px 20px 44px",gap:16
      }}>

        {/* Brand + heading */}
        <div style={{marginBottom:8}}>
          <div style={{
            fontSize:11,letterSpacing:".2em",fontFamily:"DM Mono,monospace",
            fontWeight:700,color:"rgba(255,255,255,.4)",marginBottom:10
          }}>FRIENDS SCREEN</div>
          <div style={{fontSize:26,fontWeight:900,color:"#fff",letterSpacing:"-.02em",lineHeight:1.25}}>
            어떤 서비스를<br/>이용하실 건가요?
          </div>
          <div style={{fontSize:13,color:"rgba(255,255,255,.38)",marginTop:8,lineHeight:1.55}}>
            선택 후 바로 시작합니다.<br/>메뉴에서 언제든 변경할 수 있어요.
          </div>
        </div>

        {/* Q — 스크린 골프 */}
        <button onClick={()=>onSelect("screen")} style={{
          width:"100%",padding:"22px 20px",borderRadius:16,
          background:"linear-gradient(145deg,#162416,#1c3220)",
          border:"1px solid rgba(34,197,94,.22)",
          textAlign:"left",position:"relative",overflow:"hidden",
          boxShadow:"0 2px 20px rgba(0,0,0,.32)"
        }}>
          <div style={{
            position:"absolute",top:10,right:14,fontSize:60,fontWeight:900,
            color:"rgba(34,197,94,.07)",fontFamily:"DM Mono,monospace",
            letterSpacing:"-.04em",lineHeight:1,pointerEvents:"none"
          }}>Q</div>

          <div style={{
            width:42,height:42,borderRadius:11,background:"#22C55E",
            display:"flex",alignItems:"center",justifyContent:"center",marginBottom:14
          }}>
            <svg viewBox="0 0 24 24" width="21" height="21" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round">
              <rect x="2" y="4" width="20" height="13" rx="2"/>
              <path d="M8 21h8M12 17v4"/>
            </svg>
          </div>

          <div style={{fontSize:11,letterSpacing:".1em",color:"#86EFAC",
            fontFamily:"DM Mono,monospace",fontWeight:700,marginBottom:4}}>
            Q · QUANTUM
          </div>
          <div style={{fontSize:19,fontWeight:800,color:"#fff",letterSpacing:"-.01em"}}>스크린 골프</div>
          <div style={{fontSize:12.5,color:"rgba(255,255,255,.42)",marginTop:5}}>
            타석 예약 · 스코어카드 · 클럽측정
          </div>

          <div style={{
            position:"absolute",bottom:18,right:18,
            width:30,height:30,borderRadius:"50%",
            background:"rgba(34,197,94,.14)",
            display:"flex",alignItems:"center",justifyContent:"center"
          }}>
            <svg viewBox="0 0 16 16" width="14" height="14" fill="none"
              stroke="#22C55E" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M3 8h10M9 4l4 4-4 4"/>
            </svg>
          </div>
        </button>

        {/* QR — 연습장·아카데미 */}
        <button onClick={()=>onSelect("academy")} style={{
          width:"100%",padding:"22px 20px",borderRadius:16,
          background:"linear-gradient(145deg,#141a2a,#192234)",
          border:"1px solid rgba(92,200,255,.18)",
          textAlign:"left",position:"relative",overflow:"hidden",
          boxShadow:"0 2px 20px rgba(0,0,0,.32)"
        }}>
          <div style={{
            position:"absolute",top:10,right:14,fontSize:44,fontWeight:900,
            color:"rgba(92,200,255,.07)",fontFamily:"DM Mono,monospace",
            letterSpacing:"-.04em",lineHeight:1,pointerEvents:"none"
          }}>QR</div>

          <div style={{
            width:42,height:42,borderRadius:11,background:"#3B82F6",
            display:"flex",alignItems:"center",justifyContent:"center",marginBottom:14
          }}>
            <svg viewBox="0 0 24 24" width="21" height="21" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round">
              <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z"/>
              <circle cx="12" cy="9" r="2.5"/>
            </svg>
          </div>

          <div style={{fontSize:11,letterSpacing:".1em",color:"#93C5FD",
            fontFamily:"DM Mono,monospace",fontWeight:700,marginBottom:4}}>
            QR · QUANTUM RANGE
          </div>
          <div style={{fontSize:19,fontWeight:800,color:"#fff",letterSpacing:"-.01em"}}>연습장 · 아카데미</div>
          <div style={{fontSize:12.5,color:"rgba(255,255,255,.42)",marginTop:5}}>
            이용권 · 레슨 · 트레이닝
          </div>

          <div style={{
            position:"absolute",bottom:18,right:18,
            width:30,height:30,borderRadius:"50%",
            background:"rgba(92,200,255,.12)",
            display:"flex",alignItems:"center",justifyContent:"center"
          }}>
            <svg viewBox="0 0 16 16" width="14" height="14" fill="none"
              stroke="#5CC8FF" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M3 8h10M9 4l4 4-4 4"/>
            </svg>
          </div>
        </button>

      </div>
    </div>
  );
}

window.OnboardingScreen = OnboardingScreen;


// 로그인 — 서비스 선택(온보딩) 이전 진입 화면 (카카오 / 직접입력(TID) / 회원가입)
function LoginScreen({ onKakao, onManual, onSignup }){
  return (
    <div className="screen" style={{background:"#000",color:"#fff"}}>
      <StatusBar onNavy={true}/>

      {/* 로고 (중앙) — FRIENDS SCREEN (공식 마크 에셋) */}
      <div style={{flex:1,display:"flex",alignItems:"center",justifyContent:"center"}}>
        <div style={{display:"flex",alignItems:"center",gap:10}}>
          <img src="assets/logo-mark.png" alt="" style={{height:34,flexShrink:0}}/>
          <div style={{fontWeight:900,fontSize:23,letterSpacing:"-.01em",color:"#fff"}}>FRIENDS SCREEN</div>
        </div>
      </div>

      {/* 로그인 버튼 영역 */}
      <div style={{padding:"0 24px 34px",display:"flex",flexDirection:"column",gap:12}}>
        <button onClick={onKakao} style={{height:56,borderRadius:12,background:"#FFDC00",color:"#1A1C1F",fontSize:16,fontWeight:800,border:"none"}}>
          카카오계정으로 로그인
        </button>
        <button onClick={onManual} style={{height:56,borderRadius:12,background:"#fff",color:"#1A1C1F",fontSize:16,fontWeight:800,border:"none"}}>
          직접 입력하여 로그인
        </button>
        <button onClick={onSignup} style={{marginTop:8,background:"transparent",color:"rgba(255,255,255,.85)",fontSize:14,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center",gap:4}}>
          회원가입 <Icon name="chev-r" size={14}/>
        </button>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;


// ===== 인증(로그인·회원가입) 공용 =====
const AUTH_INPUT = {width:"100%",height:52,border:"1.5px solid var(--line-strong)",borderRadius:10,padding:"0 14px",fontSize:15,outline:"none",background:"#fff",color:"var(--text)"};
const FieldLabel = ({ children })=> <div style={{fontSize:12.5,fontWeight:700,color:"var(--text-sub)",marginBottom:7}}>{children}</div>;
const AuthCheck = ({ on })=>(
  <div style={{width:22,height:22,borderRadius:"50%",background:on?"var(--primary)":"#fff",border:on?"none":"1.5px solid var(--line-strong)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
    {on && <Icon name="check" size={13} stroke={3} style={{color:"#fff"}}/>}
  </div>
);

// SMS 본인인증 공용 훅 — 인증번호 요청 토스트 + 3분 유효 타이머 (로그인·회원가입·찾기·휴면 공용)
const AUTH_TTL = 180;
function useSmsAuth(){
  const [phone, setPhone] = React.useState("");
  const [code, setCode] = React.useState("");
  const [codeSent, setCodeSent] = React.useState(false);
  const [authed, setAuthed] = React.useState(false);
  const [left, setLeft] = React.useState(0);
  const [tick, setTick] = React.useState(0);
  const [toast, setToast] = React.useState(null);
  const toastRef = React.useRef();
  React.useEffect(()=>{ if(!codeSent) return; const t=window.setInterval(()=>setLeft(s=>{ if(s<=1){ window.clearInterval(t); return 0; } return s-1; }),1000); return ()=>window.clearInterval(t); }, [tick, codeSent]);
  const showToast = (m)=>{ setToast(m); window.clearTimeout(toastRef.current); toastRef.current=window.setTimeout(()=>setToast(null),2000); };
  const onPhone = (v)=>{ setPhone(v.replace(/[^0-9]/g,"").slice(0,11)); setCodeSent(false); setAuthed(false); setCode(""); };
  const onCode = (v)=>{ setCode(v.replace(/[^0-9]/g,"").slice(0,6)); setAuthed(false); };
  const send = ()=>{ if(phone.length<10) return; setCodeSent(true); setAuthed(false); setCode(""); setLeft(AUTH_TTL); setTick(x=>x+1); showToast("인증번호를 요청했습니다."); };
  const verify = ()=>{ if(code.length===6 && left>0) setAuthed(true); };
  const reset = ()=>{ setPhone(""); setCode(""); setCodeSent(false); setAuthed(false); setLeft(0); };
  const fmt = (s)=>`${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;
  return { phone, onPhone, code, onCode, codeSent, authed, left, send, verify, reset, fmt, toast };
}
// 휴대폰 번호 + 인증번호 입력 필드 (함수 호출로 렌더 — 포커스 유지)
function smsFields(a){
  return (
    <div>
      <FieldLabel>휴대폰 번호</FieldLabel>
      <div style={{display:"flex",gap:8}}>
        <input value={a.phone} onChange={e=>a.onPhone(e.target.value)} placeholder="숫자만 입력" inputMode="numeric" style={{...AUTH_INPUT,flex:1}}/>
        <button onClick={a.send} className={"btn "+(a.phone.length>=10?"btn-soft":"btn-disabled")} style={{width:118,height:52,fontSize:14,flexShrink:0}}>{a.codeSent?"재전송":"인증번호 받기"}</button>
      </div>
      {a.codeSent && (
        <div style={{marginTop:14}}>
          <FieldLabel>인증번호</FieldLabel>
          <div style={{display:"flex",gap:8}}>
            <div style={{position:"relative",flex:1}}>
              <input value={a.code} onChange={e=>a.onCode(e.target.value)} placeholder="6자리 입력" inputMode="numeric" style={{...AUTH_INPUT,width:"100%",paddingRight:58}}/>
              {!a.authed && a.left>0 && <span style={{position:"absolute",right:14,top:0,height:52,display:"flex",alignItems:"center",fontSize:13,fontWeight:700,color:"var(--danger)",fontVariantNumeric:"tabular-nums"}}>{a.fmt(a.left)}</span>}
            </div>
            <button onClick={a.verify} className={"btn "+((a.code.length===6&&a.left>0)?"btn-primary":"btn-disabled")} style={{width:118,height:52,fontSize:14,flexShrink:0}}>확인</button>
          </div>
          <div style={{fontSize:12,marginTop:8,fontWeight:600,color:a.authed?"var(--primary)":(a.left>0?"var(--text-mute)":"var(--danger)")}}>
            {a.authed ? "인증이 완료되었어요." : a.left>0 ? "데모: 아무 6자리나 입력하면 인증됩니다." : "인증 시간이 만료되었어요. 재전송해 주세요."}
          </div>
        </div>
      )}
    </div>
  );
}


// 직접 입력(TID) 로그인 — 아이디/비밀번호 + 아이디·비번 찾기 + 휴면 해제 (FS 수동 로그인 참고)
function LoginManualScreen({ onBack, onLogin, onFind, onDormant }){
  const [id, setId] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [err, setErr] = React.useState(null);
  const [dormant, setDormant] = React.useState(false);
  const canLogin = id.trim() && pw.trim();
  const submit = ()=>{
    setDormant(false);
    if(!canLogin){ setErr("아이디와 비밀번호를 입력해 주세요."); return; }
    // 데모: 아이디 'sleep' → 휴면 계정 재현(정책 §12 366일 휴면) → 휴면 해제 안내, 그 외 성공
    if(id.trim().toLowerCase()==="sleep"){ setErr("휴면 상태의 계정이에요. 본인인증 후 해제할 수 있어요."); setDormant(true); return; }
    onLogin();
  };
  return (
    <div className="screen" style={{background:"#fff"}}>
      <StatusBar/>
      <Appbar title="로그인" onBack={onBack}/>
      <div className="scroll" style={{padding:"22px 20px 40px"}}>
        <div style={{fontSize:21,fontWeight:800,letterSpacing:"-.02em",marginBottom:24}}>아이디로 로그인</div>
        <FieldLabel>아이디</FieldLabel>
        <input value={id} onChange={e=>{ setId(e.target.value); setErr(null); setDormant(false); }} placeholder="아이디" style={AUTH_INPUT}/>
        <div style={{height:16}}/>
        <FieldLabel>비밀번호</FieldLabel>
        <input type="password" value={pw} onChange={e=>{ setPw(e.target.value); setErr(null); }} placeholder="비밀번호" style={AUTH_INPUT}/>
        {err && <div style={{fontSize:12.5,color:"var(--danger)",fontWeight:600,marginTop:12}}>{err}</div>}
        <button className={"btn "+(canLogin?"btn-primary":"btn-disabled")} style={{width:"100%",marginTop:24}} onClick={canLogin?submit:null}>로그인</button>
        {dormant && <button onClick={()=>onDormant && onDormant()} className="btn btn-outline" style={{width:"100%",marginTop:10}}>휴면 해제하기</button>}
        <div style={{display:"flex",alignItems:"center",justifyContent:"center",gap:14,marginTop:20,fontSize:13,fontWeight:600}}>
          <button onClick={()=>onFind && onFind("id")} style={{background:"none",color:"var(--text-sub)"}}>아이디 찾기</button>
          <span style={{width:1,height:12,background:"var(--line-strong)"}}/>
          <button onClick={()=>onFind && onFind("pw")} style={{background:"none",color:"var(--text-sub)"}}>비밀번호 찾기</button>
        </div>
      </div>
    </div>
  );
}


// 회원가입 — 카카오 계정 기반 (FS 방식) · 약관→닉네임→성별→본인인증→생년월일→선택항목→완료
function SignUpFlow({ onBack, onDone }){
  const keys = ["agree","nick","gender","phone","birth","optional","done"];
  const [i, setI] = React.useState(0);
  const key = keys[i];
  const next = ()=> setI(v => Math.min(keys.length-1, v+1));
  const back = ()=> i===0 ? onBack() : setI(v => v-1);

  // 약관 (FS: [필수] 통합이용약관·개인정보수집·위치정보 / [선택] 제3자·마케팅·카카오프로필)
  const AGREE_ROWS = [
    ["tos","통합 이용 약관", true],
    ["privacy","개인정보 수집·이용 내역", true],
    ["location","위치정보 이용약관", true],
    ["third","개인정보 제3자 제공", false],
    ["mkt","마케팅 광고 활용", false],
    ["kakao","카카오 프로필 사진 사용", false],
  ];
  const [agree, setAgree] = React.useState({tos:false,privacy:false,location:false,third:false,mkt:false,kakao:false});
  const reqAgreed = agree.tos && agree.privacy && agree.location;
  const allAgreed = AGREE_ROWS.every(([k])=>agree[k]);
  const toggleAll = ()=>{ const nv=!allAgreed; const o={}; AGREE_ROWS.forEach(([k])=>o[k]=nv); setAgree(o); };
  // 닉네임 · 성별 · 본인인증 · 생년월일
  const [nick, setNick] = React.useState("");
  const [nickOk, setNickOk] = React.useState(false);
  const [gender, setGender] = React.useState(null);
  const sms = useSmsAuth();
  const [by, setBy] = React.useState(null);
  const [bm, setBm] = React.useState(null);
  const [bd, setBd] = React.useState(null);
  const [pickOpen, setPickOpen] = React.useState(false);

  // 상단 5분할 진행 인디케이터 (FS G_indicator_type 5) · 스텝 공용 레이아웃(함수 호출 — 포커스 유지)
  const SEG = {agree:1, nick:2, gender:3, phone:4, birth:5, optional:5};
  const stepScreen = ({ title, sub, children, canNext, nextLabel })=>(
    <div className="screen" style={{background:"#fff"}}>
      <StatusBar/>
      <Appbar title="회원가입" onBack={back}/>
      <div style={{display:"flex",gap:5,padding:"6px 20px 10px"}}>
        {[0,1,2,3,4].map(n=>(<div key={n} style={{flex:1,height:4,borderRadius:2,background:n<(SEG[key]||0)?"var(--primary)":"var(--line)"}}/>))}
      </div>
      <div className="scroll" style={{padding:"18px 20px 100px"}}>
        <div style={{fontSize:21,fontWeight:800,letterSpacing:"-.02em",lineHeight:1.4,whiteSpace:"pre-line"}}>{title}</div>
        {sub && <div style={{fontSize:13,color:"var(--text-sub)",marginTop:8,lineHeight:1.55}}>{sub}</div>}
        <div style={{marginTop:24}}>{children}</div>
      </div>
      <div style={{position:"absolute",bottom:0,left:0,right:0,padding:"12px 20px 24px",background:"#fff"}}>
        <button className={"btn "+(canNext?"btn-primary":"btn-disabled")} style={{width:"100%"}} onClick={canNext?next:null}>{nextLabel||"다음"}</button>
      </div>
      {sms.toast && <div className="toast"><span>{sms.toast}</span></div>}
    </div>
  );

  if (key==="agree") return stepScreen({
    title:"약관을 읽어보시고\n동의해주세요.", canNext:reqAgreed,
    children:(
      <div>
        <button onClick={toggleAll} style={{width:"100%",display:"flex",alignItems:"center",gap:12,padding:"16px 16px",borderRadius:12,border:"1px solid var(--line-strong)",background:"none",marginBottom:8}}>
          <AuthCheck on={allAgreed}/>
          <span style={{fontSize:15,fontWeight:800}}>모두 동의</span>
        </button>
        <div>
          {AGREE_ROWS.map(([k,label,req])=>(
            <div key={k} style={{display:"flex",alignItems:"center",gap:12,padding:"12px 6px"}}>
              <button onClick={()=>setAgree(a=>({...a,[k]:!a[k]}))} style={{background:"none",display:"flex"}}><AuthCheck on={agree[k]}/></button>
              <span onClick={()=>setAgree(a=>({...a,[k]:!a[k]}))} style={{flex:1,fontSize:13.5,color:"var(--text)",fontWeight:500,cursor:"pointer"}}>
                <b style={{color:req?"var(--text)":"var(--text-mute)",fontWeight:700}}>[{req?"필수":"선택"}]</b> {label}
              </span>
              <button style={{background:"none",color:"var(--text-mute)"}}><Icon name="chev-r" size={16}/></button>
            </div>
          ))}
        </div>
      </div>
    )
  });

  if (key==="nick") return stepScreen({
    title:"대회나 게임에서 사용할\n닉네임을 만들어보세요.", canNext:nickOk,
    children:(
      <div>
        <div style={{display:"flex",gap:8}}>
          <input value={nick} onChange={e=>{ setNick(e.target.value.replace(/[^가-힣a-zA-Z0-9]/g,"").slice(0,12)); setNickOk(false); }} placeholder="닉네임 (2~12자)" style={{...AUTH_INPUT,flex:1}}/>
          <button onClick={()=>{ if(nick.length>=2) setNickOk(true); }} className={"btn "+(nick.length>=2?"btn-soft":"btn-disabled")} style={{width:118,height:52,fontSize:14,flexShrink:0}}>중복확인</button>
        </div>
        {nickOk
          ? <div style={{fontSize:12,marginTop:8,color:"var(--primary)",fontWeight:600}}>사용할 수 있는 닉네임이에요.</div>
          : <div style={{fontSize:12,marginTop:8,color:"var(--text-mute)"}}>한글·영문·숫자만 사용할 수 있어요. (특수문자·이모지·띄어쓰기 불가)</div>}
      </div>
    )
  });

  if (key==="gender") return stepScreen({
    title:"성별을 선택해주시면\n동급비교 데이터를 제공합니다.", canNext:!!gender,
    children:(
      <div style={{display:"flex",gap:12}}>
        {[["male","남성"],["female","여성"]].map(([g,label])=>(
          <button key={g} onClick={()=>setGender(g)} style={{flex:1,height:100,borderRadius:12,border:"1.5px solid "+(gender===g?"var(--primary)":"var(--line-strong)"),background:gender===g?"var(--primary-tint)":"#fff",color:gender===g?"var(--primary)":"var(--text-sub)",fontSize:16,fontWeight:800}}>{label}</button>
        ))}
      </div>
    )
  });

  if (key==="phone") return stepScreen({
    title:"휴대폰 번호를 입력하시면\n문자를 발송합니다.", canNext:sms.authed,
    children: smsFields(sms)
  });

  if (key==="birth") return (
    <>
      {stepScreen({
        title:"생년월일을 입력해주세요.", canNext:!!(by&&bm&&bd),
        children:(
          <div style={{display:"flex",gap:10}}>
            {[[by,"년"],[bm,"월"],[bd,"일"]].map(([val,suf],idx)=>(
              <button key={suf} onClick={()=>setPickOpen(true)} style={{flex:1,display:"flex",alignItems:"baseline",justifyContent:"space-between",padding:"10px 4px",borderBottom:"1.5px solid var(--line-strong)",background:"none"}}>
                <span style={{fontSize:18,fontWeight:800,color:val?"var(--text)":"var(--text-mute)"}}>{val||(idx===0?"----":"--")}</span>
                <span style={{fontSize:13,color:"var(--text-sub)"}}>{suf}</span>
              </button>
            ))}
          </div>
        )
      })}
      {pickOpen && (
        <>
          <div onClick={()=>setPickOpen(false)} style={{position:"absolute",inset:0,background:"rgba(34,28,28,.45)",zIndex:150}}/>
          <div style={{position:"absolute",left:0,right:0,bottom:0,background:"#fff",borderRadius:"18px 18px 0 0",zIndex:160,padding:"14px 16px 24px",boxShadow:"0 -8px 30px rgba(0,0,0,.2)"}}>
            <div style={{textAlign:"center",fontSize:15,fontWeight:800,marginBottom:10}}>생년월일</div>
            <div style={{display:"flex",gap:8}}>
              {[["년", Array.from({length:81},(_,n)=>1930+n), by, setBy],["월", Array.from({length:12},(_,n)=>n+1), bm, setBm],["일", Array.from({length:31},(_,n)=>n+1), bd, setBd]].map(([suf,items,val,set])=>(
                <div key={suf} className="scroll" style={{flex:1,height:180,overflowY:"auto",background:"var(--bg-soft)",borderRadius:10}}>
                  <div style={{padding:"76px 0"}}>
                    {items.map(it=>(
                      <button key={it} onClick={()=>set(it)} style={{display:"block",width:"100%",padding:"7px 0",fontSize:val===it?17:14,fontWeight:val===it?800:500,color:val===it?"var(--primary)":"var(--text-mute)",background:"none"}}>{it}{suf}</button>
                    ))}
                  </div>
                </div>
              ))}
            </div>
            <button className="btn btn-primary" style={{width:"100%",marginTop:14}} onClick={()=>setPickOpen(false)}>확인</button>
          </div>
        </>
      )}
    </>
  );

  if (key==="optional") return stepScreen({
    title:"선택 항목도\n확인해주세요.", canNext:true, nextLabel:"가입 완료",
    children:(
      <div>
        {[["mkt","마케팅 광고 활용","이벤트·혜택 소식을 받아볼 수 있어요."],["kakao","카카오 프로필 사진 사용","프로필에 카카오 사진을 사용해요."]].map(([k,label,desc])=>(
          <div key={k} style={{display:"flex",alignItems:"center",gap:12,padding:"14px 4px",borderBottom:"1px solid var(--line)"}}>
            <button onClick={()=>setAgree(a=>({...a,[k]:!a[k]}))} style={{background:"none",display:"flex"}}><AuthCheck on={agree[k]}/></button>
            <div style={{flex:1,cursor:"pointer"}} onClick={()=>setAgree(a=>({...a,[k]:!a[k]}))}>
              <div style={{fontSize:14,fontWeight:700}}>[선택] {label}</div>
              <div style={{fontSize:12,color:"var(--text-sub)",marginTop:2}}>{desc}</div>
            </div>
          </div>
        ))}
      </div>
    )
  });

  // done — 가입 완료 (FS: 캐릭터 + 축하 문구)
  return (
    <div className="screen" style={{background:"#fff"}}>
      <StatusBar/>
      <div style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"0 28px",textAlign:"center"}}>
        <div style={{fontSize:20,fontWeight:800,lineHeight:1.45}}>{(nick||"회원")}님의<br/>회원 가입이 완료되었습니다.</div>
        {/* 캐릭터 — 공식 춘식이 영상 에셋 */}
        <video src="assets/char-choonsik.mp4" autoPlay loop muted playsInline style={{width:260,height:260,objectFit:"contain",marginTop:20}}/>
      </div>
      <div style={{position:"absolute",bottom:0,left:0,right:0,padding:"12px 20px 24px",background:"#fff"}}>
        <button className="btn btn-primary" style={{width:"100%"}} onClick={onDone}>시작하기</button>
      </div>
    </div>
  );
}


// 접근 권한 허용 온보딩 (FS: 로그인 후 · 서비스 선택 앞단)
function PermissionOnboarding({ onAgree }){
  const perms = [
    ["위치","필수","주위에 가까운 매장을 찾기 위해 위치 정보를 사용합니다."],
    ["저장공간","필수","동영상을 빠르게 재생하기 위해 휴대폰 저장공간에 파일을 캐싱합니다."],
    ["카메라 사용","필수","QR 로그인 서비스를 제공하기 위해 카메라를 사용합니다."],
    ["알림 APP PUSH 전송","선택","경고, 사운드 및 아이콘 배지가 알람에 포함될 수 있습니다."],
    ["전화","선택","앱 내에서 원하는 매장 선택 후, 전화 연결 시 사용합니다."],
  ];
  return (
    <div className="screen" style={{background:"#fff"}}>
      <StatusBar/>
      <div className="scroll" style={{padding:"44px 24px 100px"}}>
        <div style={{fontSize:21,fontWeight:800,letterSpacing:"-.02em",lineHeight:1.45}}>편리한 서비스 이용을 위해<br/>접근 권한 허용이 필요합니다.</div>
        <div style={{marginTop:30,display:"flex",flexDirection:"column",gap:22}}>
          {perms.map(([name,req,desc])=>(
            <div key={name}>
              <div style={{display:"flex",alignItems:"center",gap:7}}>
                <span style={{width:4,height:4,borderRadius:"50%",background:"var(--text)"}}/>
                <span style={{fontSize:15,fontWeight:800}}>{name}</span>
                <span style={{fontSize:10.5,fontWeight:700,padding:"2px 8px",borderRadius:6,background:"var(--bg-soft)",color:"var(--text-sub)"}}>{req}</span>
              </div>
              <div style={{fontSize:12.5,color:"var(--text-sub)",lineHeight:1.6,marginTop:6,paddingLeft:11}}>{desc}</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{position:"absolute",bottom:0,left:0,right:0,padding:"12px 20px 24px",background:"#fff"}}>
        <button className="btn btn-primary" style={{width:"100%"}} onClick={onAgree}>동의합니다.</button>
      </div>
    </div>
  );
}

// 아이디·비밀번호 찾기 — 탭 전환 · 휴대폰 본인인증 후 결과/재설정 (FS는 WebView → 네이티브로 개선)
function FindAccountFlow({ initialTab, onBack, onGoLogin }){
  const [tab, setTab] = React.useState(initialTab==="pw" ? "pw" : "id"); // id | pw
  const [step, setStep] = React.useState("verify"); // id: verify→result / pw: verify→newpw→done
  const [name, setName] = React.useState("");
  const [loginId, setLoginId] = React.useState("");
  const sms = useSmsAuth();
  const [pw1, setPw1] = React.useState("");
  const [pw2, setPw2] = React.useState("");
  const resetAll = ()=>{ setStep("verify"); setName(""); setLoginId(""); sms.reset(); setPw1(""); setPw2(""); };
  const switchTab = (t)=>{ setTab(t); resetAll(); };

  let content, canNext, nextLabel, onNext;
  if (tab==="id"){
    if (step==="verify"){
      canNext = sms.authed && name.trim(); nextLabel = "아이디 찾기"; onNext = ()=> setStep("result");
      content = (<div><FieldLabel>이름</FieldLabel><input value={name} onChange={e=>setName(e.target.value)} placeholder="이름" style={AUTH_INPUT}/><div style={{height:16}}/>{smsFields(sms)}</div>);
    } else {
      canNext = true; nextLabel = "로그인하기"; onNext = onGoLogin;
      content = (<div style={{padding:"8px 0"}}><div style={{padding:20,borderRadius:12,background:"var(--bg-soft)",textAlign:"center"}}>
        <div style={{fontSize:13,color:"var(--text-sub)",marginBottom:8}}>회원님의 아이디예요</div>
        <div style={{fontSize:20,fontWeight:800,letterSpacing:"-.01em"}}>so****e</div>
        <div style={{fontSize:12,color:"var(--text-mute)",marginTop:8}}>가입일 2023.05.14</div>
      </div></div>);
    }
  } else {
    if (step==="verify"){
      canNext = sms.authed && loginId.trim(); nextLabel = "다음"; onNext = ()=> setStep("newpw");
      content = (<div><FieldLabel>아이디</FieldLabel><input value={loginId} onChange={e=>setLoginId(e.target.value)} placeholder="아이디" style={AUTH_INPUT}/><div style={{height:16}}/>{smsFields(sms)}</div>);
    } else if (step==="newpw"){
      const valid = pw1.length>=8 && pw1===pw2;
      canNext = valid; nextLabel = "비밀번호 변경"; onNext = ()=> setStep("done");
      content = (<div>
        <FieldLabel>새 비밀번호</FieldLabel>
        <input type="password" value={pw1} onChange={e=>setPw1(e.target.value)} placeholder="8자 이상" style={AUTH_INPUT}/>
        <div style={{height:16}}/>
        <FieldLabel>새 비밀번호 확인</FieldLabel>
        <input type="password" value={pw2} onChange={e=>setPw2(e.target.value)} placeholder="비밀번호 재입력" style={AUTH_INPUT}/>
        {pw2 && pw1!==pw2 && <div style={{fontSize:12,color:"var(--danger)",fontWeight:600,marginTop:8}}>비밀번호가 일치하지 않아요.</div>}
      </div>);
    } else {
      canNext = true; nextLabel = "로그인하기"; onNext = onGoLogin;
      content = (<div style={{padding:"24px 0",textAlign:"center"}}>
        <div className="circle-ok"><Icon name="check" size={44} stroke={2.4}/></div>
        <div style={{fontSize:19,fontWeight:800,marginTop:18}}>비밀번호가 변경되었어요</div>
        <div style={{fontSize:13,color:"var(--text-sub)",marginTop:8}}>새 비밀번호로 로그인해 주세요.</div>
      </div>);
    }
  }

  return (
    <div className="screen" style={{background:"#fff"}}>
      <StatusBar/>
      <Appbar title="아이디·비밀번호 찾기" onBack={onBack}/>
      <div style={{display:"flex",padding:"0 20px",borderBottom:"1px solid var(--line)"}}>
        {[["id","아이디 찾기"],["pw","비밀번호 찾기"]].map(([t,label])=>(
          <button key={t} onClick={()=>switchTab(t)} style={{flex:1,padding:"14px 0",fontSize:14,fontWeight:700,color:tab===t?"var(--text)":"var(--text-mute)",borderBottom:"2px solid "+(tab===t?"var(--primary)":"transparent"),background:"none"}}>{label}</button>
        ))}
      </div>
      <div className="scroll" style={{padding:"22px 20px 100px"}}>{content}</div>
      <div style={{position:"absolute",bottom:0,left:0,right:0,padding:"12px 20px 24px",background:"#fff"}}>
        <button className={"btn "+(canNext?"btn-primary":"btn-disabled")} style={{width:"100%"}} onClick={canNext?onNext:null}>{nextLabel}</button>
      </div>
      {sms.toast && <div className="toast"><span>{sms.toast}</span></div>}
    </div>
  );
}


// 휴면 해제 — 본인인증 후 계정 복구 (정책 §12 366일 휴면 · FS는 외부 위임 → 네이티브로 개선)
function DormantReleaseScreen({ onBack, onDone }){
  const [name, setName] = React.useState("");
  const sms = useSmsAuth();
  const [done, setDone] = React.useState(false);

  if (done) return (
    <div className="screen" style={{background:"#fff"}}>
      <StatusBar/>
      <Appbar title="휴면 계정 해제"/>
      <div style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"0 28px",textAlign:"center"}}>
        <div className="circle-ok"><Icon name="check" size={44} stroke={2.4}/></div>
        <div style={{fontSize:22,fontWeight:800,marginTop:22}}>휴면이 해제되었어요</div>
        <div style={{fontSize:14,color:"var(--text-sub)",marginTop:10,lineHeight:1.6}}>이용권·기록은 그대로 복구됐어요.<br/>이제 정상적으로 이용할 수 있어요.</div>
      </div>
      <div style={{position:"absolute",bottom:0,left:0,right:0,padding:"12px 20px 24px",background:"#fff"}}>
        <button className="btn btn-primary" style={{width:"100%"}} onClick={onDone}>시작하기</button>
      </div>
    </div>
  );

  return (
    <div className="screen" style={{background:"#fff"}}>
      <StatusBar/>
      <Appbar title="휴면 계정 해제" onBack={onBack}/>
      <div className="scroll" style={{padding:"22px 20px 100px"}}>
        <div style={{fontSize:21,fontWeight:800,letterSpacing:"-.02em",lineHeight:1.35}}>휴면 계정을 해제할게요</div>
        <div style={{margin:"12px 0 22px",padding:"12px 14px",borderRadius:10,background:"var(--bg-soft)",fontSize:12.5,color:"var(--text-sub)",lineHeight:1.6}}>
          366일 이상 미접속으로 휴면 전환된 계정이에요. 본인인증 후 해제하면 이용권·기록은 그대로 복구됩니다.
        </div>
        <FieldLabel>이름</FieldLabel>
        <input value={name} onChange={e=>setName(e.target.value)} placeholder="이름" style={AUTH_INPUT}/>
        <div style={{height:16}}/>
        {smsFields(sms)}
      </div>
      {sms.toast && <div className="toast"><span>{sms.toast}</span></div>}
      <div style={{position:"absolute",bottom:0,left:0,right:0,padding:"12px 20px 24px",background:"#fff"}}>
        <button className={"btn "+(sms.authed?"btn-primary":"btn-disabled")} style={{width:"100%"}} onClick={sms.authed?()=>setDone(true):null}>휴면 해제하기</button>
      </div>
    </div>
  );
}

Object.assign(window, { LoginManualScreen, SignUpFlow, FindAccountFlow, DormantReleaseScreen, PermissionOnboarding });
