// QR login — light theme

function QRScreen({ onClose }){
  const [tab, setTab] = React.useState("scan");
  const [countdown, setCountdown] = React.useState(15);
  const [toast, setToast] = React.useState(true);
  const [checkedIn, setCheckedIn] = React.useState(false); // 체크인 처리 결과 — 정책 §8 (신규 로직)

  React.useEffect(()=>{
    const t = setTimeout(()=>setToast(false), 2800);
    return ()=>clearTimeout(t);
  },[]);

  React.useEffect(()=>{
    if (tab !== "generate") return;
    const t = setInterval(()=>{
      setCountdown(c => c<=1 ? 15 : c-1);
    }, 1000);
    return ()=>clearInterval(t);
  },[tab]);

  const refresh = ()=>setCountdown(15);

  return (
    <div className="screen navy-top" style={{background:"var(--navy)"}}>
      <StatusBar onNavy/>
      {toast && <Toast icon="sun">밝기가 자동으로 최대로 조정되었습니다</Toast>}

      <div className="appbar on-navy">
        <div style={{fontSize:11,fontWeight:700,color:"rgba(255,255,255,.7)",letterSpacing:".1em"}}>SECURE LOGIN</div>
        <button className="icon-btn on-navy" onClick={onClose}><Icon name="x" size={18}/></button>
      </div>

      <div style={{padding:"0 20px 14px"}}>
        <div className="h-tabs" style={{background:"rgba(255,255,255,.12)",border:"1px solid rgba(255,255,255,.2)"}}>
          <button
            onClick={()=>setTab("scan")}
            style={{flex:1,padding:"10px 12px",borderRadius:7,fontSize:13,fontWeight:600,
              background: tab==="scan"?"#fff":"transparent",
              color: tab==="scan"?"var(--primary)":"rgba(255,255,255,.8)"}}>
            QR 스캔
          </button>
          <button
            onClick={()=>setTab("generate")}
            style={{flex:1,padding:"10px 12px",borderRadius:7,fontSize:13,fontWeight:600,
              background: tab==="generate"?"#fff":"transparent",
              color: tab==="generate"?"var(--primary)":"rgba(255,255,255,.8)"}}>
            QR 생성
          </button>
        </div>
      </div>

      <div className="scroll" style={{padding:"8px 20px 24px",color:"#fff"}}>
        {tab==="scan" ? (
          <>
            <div style={{fontSize:14,fontWeight:600,textAlign:"center",marginTop:8,color:"#fff"}}>매장 QR에 카메라를 맞춰주세요</div>
            <div style={{fontSize:12,textAlign:"center",marginTop:4,color:"rgba(255,255,255,.7)"}}>자동 인식되면 바로 입장됩니다</div>

            <div style={{
              marginTop:28,aspectRatio:"1/1",borderRadius:16,position:"relative",overflow:"hidden",
              background:"#1a202e",boxShadow:"0 20px 40px rgba(0,0,0,.4)"
            }}>
              <div style={{position:"absolute",inset:0,
                background:"radial-gradient(circle at 40% 50%,#24324a,#0e1422 70%)"}}/>
              <div style={{position:"absolute",inset:0,opacity:.18,
                background:"repeating-linear-gradient(90deg,transparent 0 3px,rgba(77,217,131,.12) 3px 4px)"}}/>
              <div style={{position:"absolute",inset:"14% 14%"}}>
                {["tl","tr","bl","br"].map(c=>{
                  const base = {position:"absolute",width:28,height:28,borderColor:"var(--primary-soft)",borderStyle:"solid"};
                  const map = {
                    tl:{top:0,left:0,borderWidth:"3px 0 0 3px",borderTopLeftRadius:6},
                    tr:{top:0,right:0,borderWidth:"3px 3px 0 0",borderTopRightRadius:6},
                    bl:{bottom:0,left:0,borderWidth:"0 0 3px 3px",borderBottomLeftRadius:6},
                    br:{bottom:0,right:0,borderWidth:"0 3px 3px 0",borderBottomRightRadius:6},
                  };
                  return <div key={c} style={{...base,...map[c]}}/>;
                })}
                <div className="scan-beam"/>
              </div>
              <div style={{position:"absolute",bottom:14,left:0,right:0,textAlign:"center",
                fontSize:11,color:"rgba(255,255,255,.6)",fontFamily:"DM Mono,monospace"}}>
                SCANNING · <span className="live-dot"/>
              </div>
            </div>

            <div style={{marginTop:20,padding:14,display:"flex",gap:10,alignItems:"center",
              background:"rgba(255,255,255,.08)",borderRadius:10,border:"1px solid rgba(255,255,255,.12)"}}>
              <div style={{color:"var(--primary-soft)"}}><Icon name="info" size={18}/></div>
              <div style={{fontSize:12,color:"rgba(255,255,255,.85)",lineHeight:1.55}}>
                QR이 인식되지 않으면 매장 직원에게 <b style={{color:"#fff"}}>QR 생성</b> 탭을 보여주세요
              </div>
            </div>

            <button onClick={()=>setCheckedIn(true)}
              style={{marginTop:12,width:"100%",height:44,borderRadius:10,background:"var(--primary)",color:"#fff",border:"none",fontSize:13,fontWeight:700}}>
              (데모) QR 인식 — 체크인 처리
            </button>
          </>
        ) : (
          <>
            <div style={{fontSize:14,fontWeight:600,textAlign:"center",marginTop:8,color:"#fff"}}>매장 직원에게 보여주세요</div>
            <div style={{fontSize:12,textAlign:"center",marginTop:4,color:"rgba(255,255,255,.7)"}}>15초 후 자동으로 갱신됩니다</div>

            <div style={{marginTop:24,display:"flex",flexDirection:"column",alignItems:"center"}}>
              <div className="qrbox">
                <div className="qrmatrix">
                  {Array.from({length:21*21}).map((_,i)=>{
                    const r = (Math.sin(i*13.31 + countdown*0.7)*10000);
                    const on = (r - Math.floor(r)) > 0.48;
                    const x = i%21, y = Math.floor(i/21);
                    const inCorner = (x<7&&y<7)||(x>13&&y<7)||(x<7&&y>13);
                    const cornerOn = inCorner && (
                      (x===0||x===6||y===0||y===6) ||
                      (x>=2&&x<=4&&y>=2&&y<=4) ||
                      ((x===14||x===20||y===0||y===6)&&(x>13&&y<7)) ||
                      (x>=16&&x<=18&&y>=2&&y<=4) ||
                      ((x===0||x===6||y===14||y===20)&&(x<7&&y>13)) ||
                      (x>=2&&x<=4&&y>=16&&y<=18)
                    );
                    return <i key={i} className={(inCorner?cornerOn:on)?"":"off"}/>;
                  })}
                </div>
              </div>

              <div style={{marginTop:22,display:"flex",alignItems:"center",gap:10}}>
                <div style={{
                  width:56,height:56,borderRadius:"50%",
                  background:`conic-gradient(var(--primary-soft) ${(countdown/15)*360}deg, rgba(255,255,255,.18) 0)`,
                  display:"flex",alignItems:"center",justifyContent:"center"
                }}>
                  <div style={{
                    width:46,height:46,borderRadius:"50%",background:"var(--navy)",
                    display:"flex",alignItems:"center",justifyContent:"center",
                    fontFamily:"DM Mono,monospace",fontWeight:700,color:"var(--primary-soft)"
                  }}>{countdown}s</div>
                </div>
                <button className="btn" style={{padding:"0 18px",height:46,background:"rgba(255,255,255,.12)",color:"#fff",border:"1px solid rgba(255,255,255,.2)"}} onClick={refresh}>
                  <Icon name="refresh" size={16}/> 새로고침
                </button>
              </div>

              <div style={{marginTop:28,padding:"14px 18px",background:"rgba(255,255,255,.1)",
                borderRadius:10,fontSize:12,color:"rgba(255,255,255,.8)",textAlign:"center"}}>
                회원번호 <b className="mono" style={{color:"#fff"}}>FA-2024-00183</b> · 라이언
              </div>
            </div>
          </>
        )}
      </div>

      {checkedIn && (
        <div style={{position:"absolute",inset:0,background:"var(--navy)",zIndex:50,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"0 28px",color:"#fff",textAlign:"center"}}>
          <div style={{width:84,height:84,borderRadius:"50%",background:"var(--primary)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 12px 30px rgba(34,197,94,.4)"}}>
            <Icon name="check" size={44} stroke={2.6}/>
          </div>
          <div style={{fontSize:22,fontWeight:800,marginTop:22}}>체크인 완료</div>
          <div style={{fontSize:13,color:"rgba(255,255,255,.75)",marginTop:8,lineHeight:1.5}}>
            이용권 사용이 확정되고 이용을 시작합니다.<br/>이용권은 이용 시작 시간에 차감됩니다.
          </div>
          <div style={{marginTop:26,width:"100%",maxWidth:300,background:"rgba(255,255,255,.1)",borderRadius:12,padding:"16px 18px",textAlign:"left"}}>
            {[
              ["매장","퀀텀 아카데미 판교점"],
              ["타석","라이언석"],
              ["이용 시간","오늘 19:00 ~ 21:00"],
              ["사용 이용권","정기 이용권 (1회)"],
              ["출석","이번 달 12일째 ✓"],
              ["상태","이용 중"],
            ].map(([k,v])=>(
              <div key={k} style={{display:"flex",justifyContent:"space-between",padding:"6px 0",fontSize:13}}>
                <span style={{color:"rgba(255,255,255,.6)"}}>{k}</span>
                <span style={{fontWeight:700,color: k==="상태" ? "var(--primary-soft)" : "#fff"}}>{v}</span>
              </div>
            ))}
          </div>
          <button onClick={()=>{ setCheckedIn(false); onClose(); }}
            style={{marginTop:26,width:"100%",maxWidth:300,height:50,borderRadius:12,background:"var(--primary)",color:"#fff",border:"none",fontSize:15,fontWeight:700}}>
            확인
          </button>
        </div>
      )}
    </div>
  );
}

window.QRScreen = QRScreen;
