// 리포트/스코어카드 — FS 구조: report(리포트: 스크린/트레이닝 탭) ↔ scorecard(목록·상세·공유) 분리

// 라운드 목록 행 (리포트 최근 미리보기 · 스코어카드 목록 공용)
function RoundRow({ r, onOpenDetail, compact }){
  return (
    <button onClick={()=>onOpenDetail(r)}
      style={{display:"block",width:"100%",textAlign:"left",padding:compact?"13px 0":"14px 20px",background:"transparent",borderBottom:"1px solid var(--line)"}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6}}>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <span style={{fontSize:13,fontWeight:600,color:"var(--text)"}}>{r.d}</span>
          <span className="store-badge sb-q">{r.t}</span>
        </div>
        <div style={{display:"flex",alignItems:"center",gap:6,fontSize:12,color:"var(--text-sub)",fontWeight:600}}>
          {r.people>=3 ? <Icon name="fire" size={14}/> : <Icon name="people" size={14}/>}
          <span>{r.people}명</span><span className="sdot"/><span>{r.holes}H</span>
        </div>
      </div>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <div style={{fontSize:17,fontWeight:800,letterSpacing:"-.02em",color:"var(--text)"}}>{r.c}</div>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <div style={{display:"flex",gap:2}}>{r.medals.map((m,k)=><span key={k} className={"medal "+m}>✓</span>)}</div>
          <div style={{fontSize:22,fontWeight:800,letterSpacing:"-.02em"}}>{r.score}</div>
        </div>
      </div>
    </button>
  );
}

// 라운드 데이터 (리포트 최근 · 스코어카드 목록 공용)
const QR_ROUNDS = {
  best: {score:70, course:"소피아그린", date:"2023.12.31"},
  months: [
    {m:"2024년 4월", rounds:[
      {d:"04월 20일",t:"Q",c:"소피아그린",people:3,holes:18,score:72,medals:["g","g","o","g"]},
      {d:"04월 15일",t:"Q",c:"비에이비스타",people:2,holes:18,score:78,medals:["g","o","o","g"]},
    ]},
    {m:"2023년 12월", rounds:[
      {d:"12월 31일",t:"Q",c:"소피아그린",people:3,holes:18,score:70,medals:["g","o","r","g"]},
      {d:"12월 19일",t:"Q",c:"서산수",people:3,holes:18,score:90,medals:["g","o","r","g"]},
    ]},
  ],
};

// 빈 상태 (기록 없음) — 리포트/스코어카드/트레이닝 공용
function EmptyState({ icon="stats", title, desc, cta, onCta }){
  return (
    <div style={{padding:"64px 30px",textAlign:"center"}}>
      <div style={{width:72,height:72,borderRadius:20,background:"var(--bg-soft)",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px",color:"var(--text-mute)"}}>
        <Icon name={icon} size={32}/>
      </div>
      <div style={{fontSize:15,fontWeight:800}}>{title}</div>
      <div style={{fontSize:12.5,color:"var(--text-sub)",marginTop:6,lineHeight:1.6}}>{desc}</div>
      {cta && <button onClick={onCta} className="btn btn-soft" style={{width:"auto",display:"inline-flex",padding:"0 22px",height:42,marginTop:18}}>{cta}</button>}
    </div>
  );
}

// ===== 스코어카드 목록 (홈 퀵 · 리포트 '전체 스코어카드' 진입) =====
function ScorecardListScreen({ onBack, onOpenDetail }){
  const [typ, setTyp] = React.useState("Q");
  const [holes, setHoles] = React.useState("18");
  const [empty, setEmpty] = React.useState(false);
  const { best, months } = QR_ROUNDS;
  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="스코어카드" onBack={onBack}
        right={<button onClick={()=>setEmpty(v=>!v)} className="icon-btn" style={{fontSize:9,fontWeight:600,color:"var(--text-mute)",width:"auto",padding:"4px 6px"}}>데모:{empty?"빈":"기록"}</button>}/>
      <div className="scroll" style={{paddingBottom:40}}>
        {empty ? (
          <EmptyState icon="stats" title="아직 스코어카드가 없어요" desc="스크린 라운드를 플레이하면 스코어카드가 여기에 쌓여요."/>
        ) : (<>
        {/* 베스트 스코어 */}
        <div style={{padding:"14px 20px 20px"}}>
          <div style={{display:"flex",alignItems:"baseline",gap:6,marginBottom:12}}>
            <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em"}}>베스트 스코어</div>
            <div style={{fontSize:16,fontWeight:700,color:"var(--primary)"}}>1</div>
          </div>
          <div style={{width:148,height:180,borderRadius:16,border:"1.5px solid var(--primary)",padding:18,display:"flex",flexDirection:"column",justifyContent:"space-between",position:"relative"}}>
            <div><div style={{display:"flex",alignItems:"baseline"}}>
              <span style={{fontSize:40,fontWeight:800,color:"var(--primary)",letterSpacing:"-.03em",lineHeight:1}}>{best.score}</span>
              <span style={{fontSize:22,fontWeight:700,color:"var(--primary)",marginLeft:2}}>타</span>
            </div></div>
            <div>
              <div style={{fontSize:14,fontWeight:700,color:"var(--text)"}}>{best.course}</div>
              <div className="muted" style={{fontSize:12,marginTop:2}}>{best.date}</div>
            </div>
            <div style={{position:"absolute",top:14,right:14,color:"var(--primary)"}}><Icon name="people" size={20}/></div>
          </div>
        </div>

        <div style={{height:1,background:"var(--line)",margin:"0 20px"}}/>

        {/* 전체 */}
        <div style={{padding:"16px 20px 12px"}}>
          <div style={{display:"flex",alignItems:"baseline",gap:6}}>
            <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em"}}>전체</div>
            <div style={{fontSize:16,fontWeight:700,color:"var(--primary)"}}>132</div>
          </div>
        </div>

        {/* 필터 */}
        <div className="fchips">
          <button className="fchip">유형 <Icon name="chev-d"/></button>
          <button className={"fchip " + (typ==="Q"?"on":"")} onClick={()=>setTyp("Q")}>퀀텀 아카데미 Q <Icon name="chev-d"/></button>
          <button className={"fchip " + (holes==="18"?"on":"")} onClick={()=>setHoles("18")}>18홀</button>
          <button className={"fchip " + (holes==="9"?"on":"")} onClick={()=>setHoles("9")}>9홀</button>
        </div>

        {/* 월별 목록 */}
        {months.map((mon,mi)=>(
          <div key={mi}>
            <div style={{padding:"12px 20px 4px",fontSize:13,fontWeight:700,color:"var(--text-sub)"}}>{mon.m}</div>
            {mon.rounds.map((r,i)=><RoundRow key={i} r={r} onOpenDetail={onOpenDetail}/>)}
          </div>
        ))}
        </>)}
      </div>
    </div>
  );
}

// ===== 리포트 (스크린 / 트레이닝 탭) =====
// 상세 진입 후 뒤로가기 시 직전 탭 유지 (SPA 내비 간 보존, 새로고침 시 초기화)
let RP_TAB = "screen";
function ReportScreen({ onNav, onBack, onOpenDetail, onOpenShare, onOpenScorecard, onOpenClub, onOpenAnalysis, onOpenSwing, onOpenAiSwing }){
  const [tab, setTabRaw] = React.useState(()=>RP_TAB);     // screen | training
  const setTab = (t)=>{ RP_TAB = t; setTabRaw(t); };
  const [machine, setMachine] = React.useState("Q");  // Q | T2
  const [roundCnt, setRoundCnt] = React.useState(5);  // 5 | 10 | 20
  const [trPeriod, setTrPeriod] = React.useState("30일"); // 트레이닝 기간 필터: 7일 | 30일 | 전체
  const [empty, setEmpty] = React.useState(false);    // 데모: 기록 없음(빈 상태)

  // 트레이닝 — 클럽별 평균 비거리(막대), 스윙 영상 클립
  const clubDist = [
    {club:"드라이버",   dist:175.5},
    {club:"우드",      dist:158.2},
    {club:"하이브리드", dist:150.0},
    {club:"7번 아이언", dist:132.4},
    {club:"웨지",      dist:88.6},
  ];
  const distMax = Math.max(...clubDist.map(c=>c.dist));
  const swings = [
    {tag:"어프로치", dist:"20.1m",  club:"52° 웨지", shot:"어프로치"},
    {tag:"티샷",    dist:"153.9m", club:"드라이버",  shot:"티샷", best:true},
    {tag:"퍼팅",    dist:"3.9m",   club:"퍼터",     shot:"퍼팅"},
  ];
  const openSwing = (s)=> onOpenSwing && onOpenSwing({dist:s.dist, club:s.club, shot:s.shot, author:"라이언", store:"판교점 · 연습", date:"1월 20일"});
  // AI 스윙 분석 — 최근 진단 기록 (기계 IP 카메라 촬영 결과를 앱에서 조회)
  const aiSwings = [
    {club:"Driver",   grade:"NOT BAD", date:"2026.06.20", store:"판교점", dist:"305.0m"},
    {club:"W3",       grade:"GOOD",    date:"2026.06.15", store:"판교점", dist:"238.4m"},
    {club:"7번 아이언", grade:"GOOD",    date:"2026.06.10", store:"강남점", dist:"152.0m"},
  ];
  const aiGradeColor = (g)=> ({PERFECT:"#3B82F6", GOOD:"#16A34A", "NOT BAD":"#F59E0B", BAD:"#EF4444"}[g] || "var(--text-mute)");

  // 기록 분석 레이더 — 내 기록 vs 등급 평균
  const radarAxes = ["비거리","정확도","그린","쇼트","퍼팅"];
  const myVals = [0.66,0.6,0.42,0.55,0.5];
  const avgVals = [0.52,0.5,0.46,0.5,0.55];
  const rPt = (i,r)=>{ const a=(-90+i*72)*Math.PI/180; return [70+r*Math.cos(a), 70+r*Math.sin(a)]; };
  const polyOf = vals => vals.map((v,i)=>rPt(i,52*v).join(",")).join(" ");
  const rGrid = [0.25,0.5,0.75,1].map(g=> radarAxes.map((_,i)=>rPt(i,52*g).join(",")).join(" "));
  const gradeColor = g => ({S:"#0E7A3B",A:"#16A34A",B:"#F59E0B",C:"#EF4444"}[g] || "var(--text-mute)");
  const analysis = [
    {id:"score",   label:"평균 타수",      me:"90타",    avg:"93타",    rank:"B"},
    {id:"drive",   label:"드라이버 비거리", me:"112.7m",  avg:"108.2m",  rank:"A"},
    {id:"fairway", label:"페어웨이 안착률", me:"60.7%",   avg:"52.4%",   rank:"A"},
    {id:"green",   label:"그린 적중률",    me:"20.5%",   avg:"18.1%",   rank:"B"},
    {id:"parsave", label:"파 세이브율",    me:"41.2%",   avg:"35.0%",   rank:"B"},
    {id:"putt",    label:"평균 퍼트",      me:"2.5개",   avg:"2.3개",   rank:"C"},
  ];
  const recent = [
    {d:"04월 20일",t:"Q",c:"소피아그린",people:3,holes:18,score:72,medals:["g","g","o","g"]},
    {d:"04월 15일",t:"Q",c:"비에이비스타",people:2,holes:18,score:78,medals:["g","o","o","g"]},
    {d:"12월 31일",t:"Q",c:"소피아그린",people:3,holes:18,score:70,medals:["g","o","r","g"]},
  ];
  const gradeStyle = (g)=>({display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",background:g==="S"?"#22C55E":"#9CA3AF",color:"#fff",fontSize:12,fontWeight:800,flexShrink:0});
  const clubMeasures = [
    {d:"12월 10일", club:"드라이버 5구", dist:"175.5m", grade:"S"},
    {d:"12월 10일", club:"하이브리드 5번", dist:"150m", grade:"A"},
  ];

  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="리포트" onBack={onBack||(()=>onNav("home"))}
        right={<button onClick={()=>setEmpty(v=>!v)} className="icon-btn" style={{fontSize:9,fontWeight:600,color:"var(--text-mute)",width:"auto",padding:"4px 6px"}}>데모:{empty?"빈":"기록"}</button>}/>

      {/* 상단 탭 — 스크린 / 트레이닝 (FS TabReportType) */}
      <div style={{display:"flex",padding:"0 16px",borderBottom:"1px solid var(--line)"}}>
        {[["screen","스크린"],["training","트레이닝"]].map(([id,label])=>(
          <button key={id} onClick={()=>setTab(id)} style={{flex:1,padding:"13px 0",fontSize:14,fontWeight:700,color:tab===id?"var(--text)":"var(--text-mute)",borderBottom:"2px solid "+(tab===id?"var(--primary)":"transparent"),background:"none"}}>{label}</button>
        ))}
      </div>

      <div className="scroll" style={{paddingBottom:110}}>
        {tab==="screen" ? (
          empty ? <EmptyState icon="stats" title="아직 스크린 라운드 기록이 없어요" desc="스크린 골프를 플레이하면 기록 분석과 스코어카드가 여기에 쌓여요." cta="스크린 예약하기" onCta={()=>onNav("home")}/> : (
          <>
            {/* 프로필·평균 */}
            <div style={{padding:"14px 20px 0"}}>
              <div style={{display:"flex",alignItems:"center",gap:14,marginBottom:14}}>
                <div style={{width:60,height:60,borderRadius:16,background:"linear-gradient(180deg,#7dd3fc 0%,#86efac 100%)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:30}}>🐻</div>
                <div style={{flex:1}}>
                  <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.01em"}}>라이언</div>
                  <div style={{fontSize:12,color:"var(--text-sub)",marginTop:2}}>보기 플레이어 · 라운드 11회</div>
                </div>
                <div style={{textAlign:"right"}}>
                  <div style={{fontSize:11,color:"var(--text-sub)"}}>평균</div>
                  <div style={{fontSize:20,fontWeight:800}}>90<span style={{fontSize:12,fontWeight:700}}>타</span></div>
                </div>
              </div>
            </div>

            {/* 기록 분석 — 필터 + 레이더(내/평균) + 분석 항목 */}
            <div style={{padding:"0 20px"}}>
              <div className="card" style={{padding:16}}>
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8}}>
                  <div className="h3" style={{fontSize:15}}>기록 분석</div>
                  <div style={{display:"flex",gap:6}}>
                    <button onClick={()=>setMachine(m=>m==="Q"?"T2":"Q")} className="fchip" style={{height:28,fontSize:11}}>{machine} <Icon name="chev-d"/></button>
                    <button onClick={()=>setRoundCnt(c=>c===5?10:c===10?20:5)} className="fchip" style={{height:28,fontSize:11}}>최근 {roundCnt}경기 <Icon name="chev-d"/></button>
                  </div>
                </div>
                <div style={{display:"flex",justifyContent:"center",padding:"4px 0 0"}}>
                  <svg viewBox="0 0 140 140" width="168" height="168">
                    {rGrid.map((g,i)=><polygon key={i} points={g} fill="none" stroke="var(--line)" strokeWidth="1"/>)}
                    {radarAxes.map((_,i)=>{ const [x,y]=rPt(i,52); return <line key={i} x1="70" y1="70" x2={x} y2={y} stroke="var(--line)" strokeWidth="1"/>; })}
                    <polygon points={polyOf(avgVals)} fill="rgba(148,163,184,.16)" stroke="#94A3B8" strokeWidth="1.4"/>
                    <polygon points={polyOf(myVals)} fill="rgba(34,197,94,.22)" stroke="#22C55E" strokeWidth="1.6"/>
                    {radarAxes.map((lab,i)=>{ const [x,y]=rPt(i,63); return <text key={i} x={x} y={y} fontSize="8" fontWeight="700" fill="#6B7280" textAnchor="middle" dominantBaseline="middle">{lab}</text>; })}
                  </svg>
                </div>
                <div style={{display:"flex",justifyContent:"center",gap:16,margin:"2px 0 4px"}}>
                  <span style={{display:"flex",alignItems:"center",gap:5,fontSize:11,color:"var(--text-sub)"}}><span style={{width:9,height:9,borderRadius:2,background:"#22C55E"}}/>내 기록</span>
                  <span style={{display:"flex",alignItems:"center",gap:5,fontSize:11,color:"var(--text-sub)"}}><span style={{width:9,height:9,borderRadius:2,background:"#94A3B8"}}/>등급 평균</span>
                </div>
                <div style={{borderTop:"1px solid var(--line)"}}>
                  <div style={{display:"grid",gridTemplateColumns:"1.3fr 1fr 1fr 34px",padding:"8px 0",fontSize:10.5,fontWeight:700,color:"var(--text-mute)"}}>
                    <div></div><div style={{textAlign:"right"}}>나</div><div style={{textAlign:"right"}}>등급평균</div><div style={{textAlign:"center"}}>등급</div>
                  </div>
                  {analysis.map((row,i)=>(
                    <button key={i} onClick={()=>onOpenAnalysis&&onOpenAnalysis(row.id)} style={{width:"100%",background:"transparent",display:"grid",gridTemplateColumns:"1.3fr 1fr 1fr 34px",padding:"9px 0",fontSize:12.5,alignItems:"center",borderTop:"1px solid var(--line)",borderLeft:0,borderRight:0,borderBottom:0}}>
                      <div style={{color:"var(--text-sub)",textAlign:"left"}}>{row.label}</div>
                      <div className="mono" style={{fontWeight:700,textAlign:"right"}}>{row.me}</div>
                      <div className="mono" style={{color:"var(--text-sub)",textAlign:"right"}}>{row.avg}</div>
                      <div style={{display:"flex",justifyContent:"center"}}>
                        <span style={{width:20,height:20,borderRadius:"50%",background:gradeColor(row.rank),color:"#fff",fontSize:10,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center"}}>{row.rank}</span>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </div>

            <div style={{height:10,background:"var(--bg-soft)",margin:"20px 0 0"}}/>

            {/* 최근 스코어카드 미리보기 + 전체 스코어카드 */}
            <div style={{padding:"16px 20px 0"}}>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4}}>
                <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em"}}>스코어카드</div>
                <button onClick={onOpenScorecard} style={{fontSize:12,color:"var(--text-sub)",fontWeight:600,background:"transparent",display:"flex",alignItems:"center",gap:2}}>전체 <Icon name="chev-r" size={12}/></button>
              </div>
              {recent.map((r,i)=><RoundRow key={i} r={r} onOpenDetail={onOpenDetail} compact/>)}
              <button onClick={onOpenScorecard} className="btn btn-soft" style={{width:"100%",height:44,marginTop:14}}>전체 스코어카드 보기</button>
            </div>
          </>
          )
        ) : (
          empty ? <EmptyState icon="stats" title="아직 트레이닝 기록이 없어요" desc="연습·클럽 측정 데이터가 쌓이면 여기에서 확인할 수 있어요." cta="트레이닝 예약하기" onCta={()=>onNav("home")}/> : (
          <>
            {/* 트레이닝 리포트 (FS ReportTraining) — 기간 필터·최근 클럽·누적·클럽별 비거리·스윙영상·클럽측정 */}
            {/* 기간 필터 */}
            <div style={{display:"flex",gap:6,padding:"14px 20px 0"}}>
              {["7일","30일","전체"].map(p=>(
                <button key={p} onClick={()=>setTrPeriod(p)} style={{fontSize:12,fontWeight:700,padding:"6px 13px",borderRadius:16,border:"none",background:trPeriod===p?"var(--primary)":"var(--bg-soft)",color:trPeriod===p?"#fff":"var(--text-sub)"}}>{p==="전체"?"전체":`최근 ${p}`}</button>
              ))}
            </div>

            {/* 최근 연습한 클럽 — 실사 에셋 + 클럽 측정 상세로 이동 */}
            <div style={{padding:"16px 20px 0"}}>
              <div style={{fontSize:13,fontWeight:700,color:"var(--text-mute)",marginBottom:8}}>최근 연습한 클럽</div>
              <button onClick={()=>onOpenClub&&onOpenClub()} className="card" style={{width:"100%",padding:"14px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",textAlign:"left",border:"1px solid var(--line)"}}>
                <div>
                  <div style={{fontSize:19,fontWeight:800,letterSpacing:"-.02em"}}>드라이버</div>
                  <div style={{display:"flex",alignItems:"center",gap:8,marginTop:5}}>
                    <span style={{fontSize:26,fontWeight:800,letterSpacing:"-.02em"}}>175.5<span style={{fontSize:15,fontWeight:700}}>m</span></span>
                    <span style={gradeStyle("S")}>S</span>
                  </div>
                </div>
                <img src="assets/club-driver.png" alt="드라이버" style={{width:120,height:74,objectFit:"contain",flexShrink:0}}/>
              </button>
            </div>

            {/* 누적 연습 시간 / 볼 수 */}
            <div style={{padding:"14px 20px 0"}}>
              <div className="card" style={{padding:"16px 12px",display:"flex"}}>
                {[["누적 연습 시간","10,290","분"],["누적 연습 볼 수","211,118","구"]].map(([k,v,u],i)=>(
                  <React.Fragment key={i}>
                    {i>0 && <div style={{width:1,background:"var(--line)"}}/>}
                    <div style={{flex:1,textAlign:"center"}}>
                      <div style={{fontSize:12,color:"var(--text-sub)",fontWeight:600}}>{k}</div>
                      <div style={{fontSize:19,fontWeight:800,marginTop:5}}>{v}<span style={{fontSize:12,fontWeight:700}}>{u}</span></div>
                    </div>
                  </React.Fragment>
                ))}
              </div>
            </div>

            {/* 클럽별 평균 비거리 */}
            <div style={{padding:"20px 20px 0"}}>
              <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em",marginBottom:12}}>클럽별 평균 비거리</div>
              <div style={{display:"flex",flexDirection:"column",gap:11}}>
                {clubDist.map((c,i)=>(
                  <div key={i} style={{display:"flex",alignItems:"center",gap:10}}>
                    <div style={{width:64,fontSize:12.5,fontWeight:600,color:"var(--text-sub)",flexShrink:0}}>{c.club}</div>
                    <div style={{flex:1,height:8,borderRadius:99,background:"#EDEFF2",overflow:"hidden"}}>
                      <div style={{height:"100%",width:`${Math.round(c.dist/distMax*100)}%`,background:i===0?"var(--primary)":"#86EFAC",borderRadius:99}}/>
                    </div>
                    <div className="mono" style={{width:52,textAlign:"right",fontSize:12.5,fontWeight:700,flexShrink:0}}>{c.dist.toFixed(1)}m</div>
                  </div>
                ))}
              </div>
            </div>

            <div style={{height:10,background:"var(--bg-soft)",margin:"22px 0 0"}}/>

            {/* 스윙 영상 — 전체 이동 + 재생 시 상세로 */}
            <div style={{padding:"18px 20px 0"}}>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12}}>
                <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em"}}>스윙 영상</div>
                <button onClick={()=>onNav("swing")} style={{fontSize:12,color:"var(--text-sub)",fontWeight:600,background:"transparent",display:"flex",alignItems:"center",gap:2}}>전체 <Icon name="chev-r" size={12}/></button>
              </div>
              <div className="hscroll">
                {swings.map((s,i)=>(
                  <button key={i} onClick={()=>openSwing(s)} className="swing-card" style={{padding:0,cursor:"pointer"}}>
                    <img src="assets/swing-poster.png" alt="" style={{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",opacity:.9}}/>
                    <div style={{position:"absolute",inset:0,background:"linear-gradient(180deg,rgba(0,0,0,.15) 0%,rgba(0,0,0,.45) 100%)"}}/>
                    {s.best && <span style={{position:"absolute",right:8,top:8,fontSize:9,fontWeight:800,color:"#111",background:"#FDE047",padding:"2px 5px",borderRadius:4}}>베스트</span>}
                    <div className="tag">{s.tag}</div>
                    <div style={{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",width:34,height:34,borderRadius:"50%",background:"rgba(255,255,255,.28)",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff"}}><Icon name="play" size={14}/></div>
                    <div className="big" style={{fontSize:16}}>{s.dist}</div>
                  </button>
                ))}
              </div>
            </div>

            {/* AI 스윙 분석 — 최근 진단 (IP 카메라 촬영 결과 조회) */}
            <div style={{padding:"22px 20px 0"}}>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4}}>
                <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em"}}>AI 스윙 분석</div>
                <span style={{fontSize:11,color:"var(--text-mute)",fontWeight:600}}>IP 카메라 매장</span>
              </div>
              <div style={{fontSize:11.5,color:"var(--text-sub)",marginBottom:12}}>스크린 골프 롱게임 스윙을 6구간으로 진단한 결과예요.</div>
              {aiSwings.map((a,i)=>(
                <button key={i} onClick={()=>onOpenAiSwing&&onOpenAiSwing(a)} style={{width:"100%",display:"flex",alignItems:"center",gap:12,padding:"13px 14px",background:"var(--bg-soft)",borderRadius:12,marginBottom:8,border:"none",textAlign:"left"}}>
                  <span style={{width:40,height:40,borderRadius:10,background:aiGradeColor(a.grade)+"1F",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke={aiGradeColor(a.grade)} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 14s1.5-2 4-2 4 2 4 2M12 12s1.5-2 4-2 4 2 4 2"/><circle cx="8" cy="8" r="1.4"/><circle cx="16" cy="8" r="1.4"/><path d="M4 20h16"/></svg>
                  </span>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{display:"flex",alignItems:"center",gap:6}}>
                      <span style={{fontSize:14.5,fontWeight:800}}>{a.club}</span>
                      <span style={{fontSize:10.5,fontWeight:800,color:"#fff",background:aiGradeColor(a.grade),borderRadius:5,padding:"2px 7px"}}>{a.grade}</span>
                    </div>
                    <div style={{fontSize:11.5,color:"var(--text-sub)",marginTop:2}}>{a.store} · <span className="mono">{a.date}</span> · {a.dist}</div>
                  </div>
                  <Icon name="chev-r" size={15} style={{color:"var(--text-mute)"}}/>
                </button>
              ))}
            </div>

            {/* 클럽 측정 — 행 탭 시 상세 */}
            <div style={{padding:"22px 20px 0"}}>
              <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em",marginBottom:12}}>클럽 측정</div>
              {clubMeasures.map((c,i)=>(
                <button key={i} onClick={()=>onOpenClub&&onOpenClub()} style={{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",background:"var(--bg-soft)",borderRadius:10,marginBottom:8,border:"none",textAlign:"left"}}>
                  <div>
                    <div style={{fontSize:12,color:"var(--text-mute)",marginBottom:3}}>{c.d}</div>
                    <div style={{fontSize:15,fontWeight:700}}>{c.club}</div>
                  </div>
                  <div style={{display:"flex",alignItems:"center",gap:10}}>
                    <span style={{fontSize:20,fontWeight:800,letterSpacing:"-.02em"}}>{c.dist}</span>
                    <span style={gradeStyle(c.grade)}>{c.grade}</span>
                    <Icon name="chev-r" size={15} style={{color:"var(--text-mute)"}}/>
                  </div>
                </button>
              ))}
              <button onClick={()=>onOpenClub&&onOpenClub()} className="btn btn-outline" style={{width:"100%",height:44,marginTop:6}}>전체보기</button>
            </div>
          </>
          )
        )}
      </div>

      <TabBar current="report" onNav={onNav}/>
    </div>
  );
}

// ===== AI 스윙 분석 (클라이언트 AiSwing 씬을 앱 조회 콘텐츠로 이식) =====
// 6구간 진단 · 풋프린트(체중이동) · 스윙 영상 · 종합 진단 · 이전 기록
const AI_GRADE = (g)=> ({PERFECT:"#3B82F6", GOOD:"#16A34A", "NOT BAD":"#F59E0B", BAD:"#EF4444", A:"#16A34A", B:"#3B82F6", C:"#F59E0B", D:"#EF4444"}[g] || "var(--text-mute)");
const AI_PHASES = [
  {ko:"어드레스",     en:"Address",        grade:"A", items:[["정렬(스탠스)","양호"],["볼 위치","양호"],["척추 각도","보통"]]},
  {ko:"테이크 어웨이", en:"Take Away",      grade:"B", items:[["클럽 궤도","보통"],["손목 코킹","양호"],["어깨 회전 시작","주의"]]},
  {ko:"백스윙 탑",    en:"Backswing Top",  grade:"B", items:[["어깨 회전량","양호"],["회전 축 유지","보통"],["클럽 위치","주의"]]},
  {ko:"다운 스윙",    en:"Downswing",      grade:"C", items:[["체중 이동","주의"],["클럽 래깅","보통"],["하체 리드","주의"]]},
  {ko:"임팩트",      en:"Impact",         grade:"B", items:[["임팩트 자세","양호"],["헤드 스피드","보통"],["페이스 각","양호"]]},
  {ko:"팔로우 스루",  en:"Follow Through", grade:"A", items:[["피니시 균형","양호"],["회전 마무리","양호"],["체중 이동","보통"]]},
];
const AI_SUMMARY = {
  headline:"연습이 필요해 보입니다.",
  sections:[
    {title:"이런 점이 아쉬워요", color:"#EF4444", text:"다운스윙에서 체중 이동이 늦어 임팩트 때 상체가 뒤로 밀리고 있어요. 상체가 먼저 열리면서 슬라이스가 나기 쉬운 스윙입니다."},
    {title:"개선이 필요해요",   color:"#F59E0B", text:"백스윙 탑에서 회전 축이 흔들려 클럽 위치가 불안정합니다. 축을 고정한 채 어깨를 충분히 돌리는 연습이 필요해요."},
    {title:"Tips",           color:"#16A34A", text:"하체를 먼저 리드하며 다운스윙을 시작하고, 임팩트까지 시선을 볼에 고정해보세요. 하프 스윙부터 천천히 반복하면 도움이 됩니다."},
  ],
};
const aiStatusColor = (s)=> ({양호:"#16A34A", 보통:"var(--text-mute)", 주의:"#F59E0B"}[s] || "var(--text-mute)");

// 풋프린트(체중 이동) — 발 모양 + 상/하단 비율 + 좌우 밸런스
function Footprint({ view }){
  const L={top:73,bot:27}, R={top:51,bot:50}, bal={l:99,r:1};
  const Foot = ({x, top, bot})=> (
    <g>
      <path d={`M${x} 14 q10 -8 18 0 q6 8 3 34 q-2 18 -10 20 q-9 2 -11 -18 q-3 -28 0 -36 z`} fill="none" stroke="var(--line-strong)" strokeWidth="1.4"/>
      <circle cx={x+8} cy="26" r={view==="Graph"?4:3} fill="var(--primary)"/>
      <circle cx={x+8} cy="58" r={view==="Graph"?4:3} fill="#86EFAC"/>
    </g>
  );
  return (
    <div>
      <div style={{display:"flex",alignItems:"center",justifyContent:"center",gap:8}}>
        <div style={{textAlign:"right",width:56}}>
          <div style={{fontSize:18,fontWeight:800}}>{L.top}%</div>
          <div style={{fontSize:13,fontWeight:700,color:"var(--text-sub)",marginTop:26}}>{L.bot}%</div>
        </div>
        <svg viewBox="0 0 92 80" width="150" height="130">
          <Foot x={12} top={L.top} bot={L.bot}/>
          <Foot x={54} top={R.top} bot={R.bot}/>
          {view==="Graph" && <path d="M20 26 L62 26 M20 58 L62 58" stroke="#FDE047" strokeWidth="2" strokeLinecap="round"/>}
        </svg>
        <div style={{textAlign:"left",width:56}}>
          <div style={{fontSize:18,fontWeight:800}}>{R.top}%</div>
          <div style={{fontSize:13,fontWeight:700,color:"var(--text-sub)",marginTop:26}}>{R.bot}%</div>
        </div>
      </div>
      {/* 좌우 밸런스 */}
      <div style={{display:"flex",alignItems:"center",gap:8,marginTop:8,padding:"0 12px"}}>
        <span style={{fontSize:13,fontWeight:800,width:36}}>{bal.l}%</span>
        <div style={{flex:1,height:8,borderRadius:99,background:"#EDEFF2",overflow:"hidden",display:"flex"}}>
          <div style={{width:`${bal.l}%`,background:"var(--primary)"}}/>
          <div style={{width:`${bal.r}%`,background:"#FDE047"}}/>
        </div>
        <span style={{fontSize:13,fontWeight:800,width:36,textAlign:"right",color:"var(--text-sub)"}}>{bal.r}%</span>
      </div>
    </div>
  );
}

function AiSwingAnalysis({ rec, onBack }){
  const r = rec || {club:"Driver", grade:"NOT BAD", date:"2026.06.20", store:"판교점", dist:"305.0m"};
  const [tab, setTab] = React.useState("진단"); // 진단 | 영상 | 종합
  const [fpView, setFpView] = React.useState("Graph"); // Graph | Line
  const [phase, setPhase] = React.useState(0);
  const [aspect, setAspect] = React.useState("정면");
  const SPEEDS=[0.25,0.5,0.75,1]; const [speed,setSpeed]=React.useState(0.5);
  const gc = AI_GRADE(r.grade);
  const ph = AI_PHASES[phase];
  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="AI 스윙 분석" onBack={onBack}/>
      {/* 진단 헤더 */}
      <div style={{padding:"14px 20px 14px",display:"flex",alignItems:"center",gap:12,borderBottom:"1px solid var(--line)"}}>
        <div style={{flex:1}}>
          <div style={{display:"flex",alignItems:"center",gap:7}}>
            <span style={{fontSize:19,fontWeight:800,letterSpacing:"-.02em"}}>{r.club}</span>
            <span style={{fontSize:12,fontWeight:800,color:"#fff",background:gc,borderRadius:6,padding:"3px 9px"}}>{r.grade}</span>
          </div>
          <div style={{fontSize:12,color:"var(--text-sub)",marginTop:3}}>{r.store} · <span className="mono">{r.date}</span> · 비거리 {r.dist}</div>
        </div>
      </div>
      {/* 탭 */}
      <div style={{display:"flex",padding:"0 16px",borderBottom:"1px solid var(--line)"}}>
        {["진단","영상","종합"].map(t=>(
          <button key={t} onClick={()=>setTab(t)} style={{flex:1,padding:"12px 0",fontSize:14,fontWeight:700,color:tab===t?"var(--text)":"var(--text-mute)",borderBottom:"2px solid "+(tab===t?"var(--primary)":"transparent"),background:"none",marginBottom:-1}}>{t==="진단"?"구간 진단":t==="영상"?"스윙 영상":"종합 진단"}</button>
        ))}
      </div>

      <div className="scroll" style={{paddingBottom:90}}>
        {tab==="진단" && (
          <>
            {/* 풋프린트 */}
            <div style={{padding:"18px 20px 0"}}>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6}}>
                <div style={{fontSize:15,fontWeight:800}}>풋프린트 <span style={{fontSize:12,fontWeight:600,color:"var(--text-sub)"}}>체중 이동</span></div>
                <div style={{display:"flex",background:"var(--bg-soft)",borderRadius:8,padding:2}}>
                  {["Graph","Line"].map(v=>(
                    <button key={v} onClick={()=>setFpView(v)} style={{fontSize:11.5,fontWeight:700,padding:"5px 12px",borderRadius:6,border:"none",background:fpView===v?"#fff":"transparent",color:fpView===v?"var(--text)":"var(--text-mute)",boxShadow:fpView===v?"0 1px 3px rgba(0,0,0,.1)":"none"}}>{v}</button>
                  ))}
                </div>
              </div>
              <div className="card" style={{padding:"14px 10px"}}><Footprint view={fpView}/></div>
            </div>
            {/* 6구간 진단 */}
            <div style={{padding:"22px 20px 0"}}>
              <div style={{fontSize:15,fontWeight:800,marginBottom:10}}>6구간 진단</div>
              <div style={{display:"flex",gap:6,overflowX:"auto",scrollbarWidth:"none",paddingBottom:2}}>
                {AI_PHASES.map((p,i)=>{
                  const on=i===phase;
                  return (
                    <button key={i} onClick={()=>setPhase(i)} style={{flexShrink:0,minWidth:52,padding:"8px 6px",borderRadius:10,border:"1.5px solid "+(on?AI_GRADE(p.grade):"var(--line)"),background:on?AI_GRADE(p.grade)+"12":"#fff",display:"flex",flexDirection:"column",alignItems:"center",gap:4}}>
                      <span style={{width:22,height:22,borderRadius:"50%",background:AI_GRADE(p.grade),color:"#fff",fontSize:11,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center"}}>{p.grade}</span>
                      <span style={{fontSize:9.5,fontWeight:700,color:on?"var(--text)":"var(--text-sub)",lineHeight:1.1,textAlign:"center"}}>{p.ko}</span>
                    </button>
                  );
                })}
              </div>
              {/* 선택 구간 항목별 평가 */}
              <div className="card" style={{padding:"4px 0",marginTop:12}}>
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid var(--line)"}}>
                  <div style={{fontSize:14,fontWeight:800}}>{ph.ko} <span style={{fontSize:11.5,color:"var(--text-mute)",fontWeight:600}}>{ph.en}</span></div>
                  <span style={{fontSize:11,fontWeight:800,color:"#fff",background:AI_GRADE(ph.grade),borderRadius:5,padding:"2px 8px"}}>{ph.grade}</span>
                </div>
                {ph.items.map(([k,v],i)=>(
                  <div key={i} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderTop:i?"1px solid var(--line)":"none"}}>
                    <span style={{fontSize:13.5,color:"var(--text-sub)"}}>{k}</span>
                    <span style={{fontSize:13,fontWeight:700,color:aiStatusColor(v),display:"flex",alignItems:"center",gap:5}}>
                      <span style={{width:6,height:6,borderRadius:"50%",background:aiStatusColor(v)}}/>{v}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}

        {tab==="영상" && (
          <div style={{padding:"14px 0 0"}}>
            {/* 정면/측면 */}
            <div style={{display:"flex",padding:"0 20px",gap:6}}>
              {["정면","측면"].map(a=>(
                <button key={a} onClick={()=>setAspect(a)} style={{fontSize:12.5,fontWeight:700,padding:"7px 16px",borderRadius:16,border:"none",background:aspect===a?"var(--primary)":"var(--bg-soft)",color:aspect===a?"#fff":"var(--text-sub)"}}>{a}</button>
              ))}
            </div>
            {/* 플레이어 */}
            <div style={{position:"relative",margin:"12px 20px 0",borderRadius:12,overflow:"hidden",aspectRatio:"3/4",background:"#111"}}>
              <img src="assets/swing-poster.png" alt="" style={{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",opacity:.92,transform:aspect==="측면"?"scaleX(-1)":"none"}}/>
              <div style={{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",width:46,height:46,borderRadius:"50%",background:"rgba(255,255,255,.28)",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff"}}><Icon name="play" size={18}/></div>
              <button onClick={()=>setSpeed(s=>SPEEDS[(SPEEDS.indexOf(s)+1)%SPEEDS.length])} style={{position:"absolute",right:10,bottom:10,fontSize:11,fontWeight:800,color:"#fff",background:"rgba(0,0,0,.5)",borderRadius:6,padding:"4px 8px",border:"none"}}>x{speed}</button>
            </div>
            {/* 6구간 타임라인 마커 */}
            <div style={{display:"flex",gap:4,overflowX:"auto",scrollbarWidth:"none",padding:"12px 20px 0"}}>
              {AI_PHASES.map((p,i)=>(
                <button key={i} onClick={()=>setPhase(i)} style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"6px 9px",borderRadius:8,border:"none",background:i===phase?AI_GRADE(p.grade):"var(--bg-soft)",color:i===phase?"#fff":"var(--text-sub)"}}>{p.ko}</button>
              ))}
            </div>
            <div style={{padding:"14px 20px 0",fontSize:12,color:"var(--text-mute)",lineHeight:1.6}}>구간을 선택하면 해당 스윙 지점으로 이동해요. 정면·측면 영상과 배속(x0.25~x1)으로 자세를 비교해보세요.</div>
          </div>
        )}

        {tab==="종합" && (
          <div style={{padding:"18px 20px 0"}}>
            <div style={{display:"flex",alignItems:"center",gap:10,padding:"16px",borderRadius:14,background:gc+"12",marginBottom:16}}>
              <span style={{fontSize:14,fontWeight:800,color:"#fff",background:gc,borderRadius:8,padding:"5px 12px"}}>{r.grade}</span>
              <div style={{fontSize:15,fontWeight:800}}>{AI_SUMMARY.headline}</div>
            </div>
            {AI_SUMMARY.sections.map((s,i)=>(
              <div key={i} style={{marginBottom:14}}>
                <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:6}}>
                  <span style={{width:4,height:14,borderRadius:2,background:s.color}}/>
                  <span style={{fontSize:14,fontWeight:800,color:s.color}}>{s.title}</span>
                </div>
                <div style={{fontSize:13.5,color:"var(--text-sub)",lineHeight:1.65,paddingLeft:10}}>{s.text}</div>
              </div>
            ))}
            <div style={{marginTop:6,padding:"12px 14px",background:"var(--bg-soft)",borderRadius:10,fontSize:12,color:"var(--text-mute)",lineHeight:1.55}}>* IP 카메라가 설치된 매장의 롱게임 타석에서 촬영·분석된 결과입니다.</div>
          </div>
        )}
      </div>

      {/* 하단 — 이전 기록 */}
      <div style={{position:"absolute",left:0,right:0,bottom:0,padding:"12px 20px 22px",background:"#fff",borderTop:"1px solid var(--line)"}}>
        <button onClick={onBack} className="btn btn-soft" style={{width:"100%",height:48}}>이전 기록 보기</button>
      </div>
    </div>
  );
}

function ScorecardDetail({ onBack, onShare }){
  // 코스(공통) — 같은 매장/코스 라운드
  const PAR_OUT = [4,3,4,4,5,3,4,4,5];   // 36
  const PAR_IN  = [4,5,3,4,4,3,5,4,4];   // 36
  const COURSE_PAR = 72;
  const HOLES_OUT = [1,2,3,4,5,6,7,8,9];
  const HOLES_IN  = [10,11,12,13,14,15,16,17,18];

  // 경기 모드 데모 전환 (실서비스는 라운드 데이터로 자동 결정)
  const MODES = [
    {id:"multi",   label:"멀티 스트로크"},
    {id:"fstroke", label:"포섬 스트로크"},
    {id:"fmatch",  label:"포섬 매치"},
    {id:"partial", label:"미완주"},
    {id:"none",    label:"한 홀 미진행"},
  ];
  const [mode, setMode] = React.useState("multi");
  const isTeam = mode==="fstroke" || mode==="fmatch";
  const isMatch = mode==="fmatch";
  const isPartial = mode==="partial";
  const isNone = mode==="none";

  const sum = a => a.reduce((x,y)=> x + (typeof y==="number"?y:0), 0);
  const hasDash = a => a.some(v=>v==="-");
  const pillClass = (s,p)=>{ const d=s-p; return d<=-2?"sc-pill eagle":d===-1?"sc-pill birdie":d===0?"sc-pill par":d===1?"sc-pill bogey":"sc-pill dbogey"; };
  const overLabel = t => { const o=t-COURSE_PAR; return o>0?`+${o}`:o<0?`${o}`:"E"; };
  const overColor = t => { const o=t-COURSE_PAR; return o>0?"var(--text-sub)":o<0?"var(--primary)":"var(--text)"; };
  // 매치플레이: 이긴홀 UP(빨강)·비긴홀 AS·진홀 DN(파랑), 토탈 = UP/DN 수치 또는 A/S
  const matchColor = m => m==="UP" ? "var(--danger)" : m==="DN" ? "#2563EB" : "var(--text-mute)";
  const matchNet = arr => arr.filter(m=>m==="UP").length - arr.filter(m=>m==="DN").length;
  const matchLabel = n => n>0?`${n}UP`:n<0?`${-n}DN`:"A/S";
  const matchTotColor = n => n>0?"var(--danger)":n<0?"#2563EB":"var(--text-mute)";

  // 개인(멀티/스트로크) 플레이어
  const players = [
    {name:"라이언", me:true, sOut:[5,3,4,4,6,3,5,4,5], sIn:[4,5,4,5,4,4,5,4,5], pOut:[2,1,2,2,2,1,2,2,2], pIn:[2,2,2,2,2,1,2,2,2]},
    {name:"내이름은차은우", sOut:[4,4,5,4,5,3,4,5,6], sIn:[5,6,4,4,5,4,5,4,5], pOut:[2,2,2,2,2,1,2,2,2], pIn:[2,2,2,2,2,2,2,2,2]},
    {name:"뉴공아지", sOut:[5,4,5,5,6,4,5,5,6], sIn:[5,6,4,5,5,4,6,5,5], pOut:[2,2,2,3,2,2,2,2,2], pIn:[2,2,2,2,3,2,2,2,2]},
  ];
  // 미완주: 기록 있는 홀만, 나머지 '-' / 한 홀 미진행: 전부 '-'
  const D9 = ["-","-","-","-","-","-","-","-","-"];
  const partialPlayers = [{name:"라이언", me:true, sOut:[5,3,4,5,"-","-","-","-","-"], sIn:[...D9], pOut:[2,1,2,2,"-","-","-","-","-"], pIn:[...D9]}];
  const nonePlayers = [{name:"라이언", me:true, sOut:[...D9], sIn:[...D9], pOut:[...D9], pIn:[...D9]}];
  // 포섬/포볼 팀 (스트로크/매치 공용) — 매치는 홀별 UP/AS/DN. 팀명: Q=Team ACE/EPIC
  const teams = [
    {name:"Team ACE", color:"#16A34A", members:["김프로24","미라니에","파소리","정체불명사나이","통둥이","고담"],
      sOut:[4,4,5,3,4,4,4,4,4], sIn:[4,5,3,4,4,3,5,4,4], pOut:[2,2,2,1,2,2,2,2,2], pIn:[2,2,1,2,2,1,2,2,2],
      mOut:["UP","AS","AS","UP","UP","UP","UP","UP","UP"], mIn:["AS","UP","AS","UP","AS","DN","UP","UP","UP"]},
    {name:"Team EPIC", color:"#EF4444", members:["라이언","어피치","프로도"],
      sOut:[5,4,5,3,5,4,4,5,4], sIn:[5,5,4,4,5,3,5,4,5], pOut:[2,2,2,2,2,2,2,2,2], pIn:[2,2,2,2,2,2,2,2,2],
      mOut:["DN","AS","AS","DN","DN","DN","DN","DN","DN"], mIn:["AS","DN","AS","DN","AS","UP","DN","DN","DN"]},
  ];

  // 현재 모드 참가자 카드
  const cards = isNone ? nonePlayers : isPartial ? partialPlayers : isTeam ? teams : players;
  const metaLabel = isMatch ? `포섬 매치 · ${teams.length}팀` : isTeam ? `포섬 스트로크 · ${teams.length}팀`
    : mode==="multi" ? `멀티플레이 · ${players.length}명` : `스트로크 · ${cards.length}명`;

  const [openP, setOpenP] = React.useState({0:true});
  const toggleP = i => setOpenP(s=>({...s,[i]:!s[i]}));

  // 모드별 노출 제어 — 랭킹=멀티만 / 라운드분석=멀티(스크린 18홀 완주)만 / 한 홀 미진행=하단 전부 하이드+토스트
  const showRanking = mode==="multi";
  const analysisAvailable = mode==="multi";
  const [toast, setToast] = React.useState(null);
  React.useEffect(()=>{ if(isNone){ setToast("해당 라운드의 기록이 없습니다."); const t=setTimeout(()=>setToast(null),2400); return ()=>clearTimeout(t); } setToast(null); }, [mode]);

  // 등급평가 (나 / 등급평균 / 평가) — 등급 색: A 초록 · B 주황 · C 빨강 · S 진초록
  const gradeColor = g => ({S:"#0E7A3B",A:"#16A34A",B:"#F59E0B",C:"#EF4444"}[g] || "var(--text-mute)");
  const analysis = [
    {label:"최대 비거리",   me:"255.2m", avg:"250.9m", grade:"A"},
    {label:"평균 비거리",   me:"226.7m", avg:"269m",   grade:"B"},
    {label:"페어웨이 안착률", me:"56.3%",  avg:"집계중",  grade:null},
    {label:"그린 적중률",   me:"25%",    avg:"11.2%",  grade:"A"},
    {label:"파 세이브율",   me:"81.8%",  avg:"23.4%",  grade:"B"},
    {label:"샌드 세이브율", me:"11.2%",  avg:"11.2%",  grade:"A"},
    {label:"평균 퍼트 수",  me:"1.6개",  avg:"2개",    grade:"A"},
  ];

  // 랭킹보드 (멀티) — 글로벌 리더보드, 본인 순위 하이라이트
  const myRank = {rank:99, name:players[0].name, strokes:112};
  const ranking = [
    {rank:1, name:"지나태윤",       strokes:68},
    {rank:2, name:"쑹크리스탈",     strokes:68},
    {rank:3, name:"다다제이",       strokes:70},
    {rank:4, name:"밤토리엄니",     strokes:73},
    {rank:5, name:"청라동버디땅콩", strokes:76},
  ];

  // 홀 공략 기록 — OUT/IN 토글 + 홀 페이저
  const [oi, setOi] = React.useState("OUT");
  const [hole, setHole] = React.useState(1);
  const moveHole = d => setHole(h => { const n=h+d; return n<1?1:n>18?18:n; });

  // 샷 기록 (클럽 / 구질 / 비거리 / 안착지점) — 포섬/포볼은 플레이어 컬럼 추가
  const shots = [
    {no:1, club:"DR", shape:"풀 슬라이스", dist:"250.9m", land:"페어웨이", player:"하얀끼야"},
    {no:2, club:"DR", shape:"풀 훅",       dist:"250.9m", land:"OB",       player:"까만끼야"},
    {no:3, club:"-",  shape:"-",           dist:"-",       land:"페널티",   player:"밀크티"},
    {no:4, club:"DR", shape:"스트레이트",  dist:"250.9m", land:"러프",     player:"삐동이"},
    {no:5, club:"I7", shape:"푸쉬",        dist:"180.2m", land:"에이프런", player:"하얀끼야"},
    {no:6, club:"PT", shape:"-",           dist:"12.4m",  land:"그린",     player:"까만끼야"},
    {no:7, club:"-",  shape:"-",           dist:"(1.1m)", land:"컨시드",   player:"밀크티"},
  ];
  const landColor = l => /페널티|OB/.test(l) ? "var(--danger)" : /컨시드|더블파/.test(l) ? "var(--primary)" : "var(--text-sub)";
  const shotCols = isTeam ? "34px 46px 1fr 0.9fr 0.9fr 60px" : "42px 52px 1.1fr 1fr 1fr";

  // 스트로크 9홀 그리드 ('-' 미기록 홀 처리)
  const Nine = ({tag, nums, par, score, putt})=>(
    <div className="hole-grid" style={{border:"1px solid var(--line)",borderRadius:10,overflow:"hidden",marginTop:tag==="IN"?8:0}}>
      <div className="lbl">HOLE</div>
      {nums.map(h=><div key={h} style={{fontWeight:700,color:"var(--text-sub)",background:"#F7F8FA"}}>{h}</div>)}
      <div className="sum">{tag}</div>
      <div className="lbl">PAR</div>
      {par.map((v,k)=><div key={k}>{v}</div>)}
      <div className="sum">{sum(par)}</div>
      <div className="lbl">SCORE</div>
      {score.map((v,k)=><div key={k}>{v==="-"?<span style={{color:"var(--text-mute)"}}>-</span>:<span className={pillClass(v,par[k])}>{v}</span>}</div>)}
      <div className="sum">{hasDash(score)?"-":sum(score)}</div>
      <div className="lbl">PUTT</div>
      {putt.map((v,k)=><div key={k}>{v==="-"?<span style={{color:"var(--text-mute)"}}>-</span>:v}</div>)}
      <div className="sum">{hasDash(putt)?"-":sum(putt)}</div>
    </div>
  );
  // 매치 9홀 그리드 (HOLE/PAR/MATCH)
  const NineMatch = ({tag, nums, par, match})=>(
    <div className="hole-grid" style={{border:"1px solid var(--line)",borderRadius:10,overflow:"hidden",marginTop:tag==="IN"?8:0}}>
      <div className="lbl">HOLE</div>
      {nums.map(h=><div key={h} style={{fontWeight:700,color:"var(--text-sub)",background:"#F7F8FA"}}>{h}</div>)}
      <div className="sum">{tag}</div>
      <div className="lbl">PAR</div>
      {par.map((v,k)=><div key={k}>{v}</div>)}
      <div className="sum">{sum(par)}</div>
      <div className="lbl">MATCH</div>
      {match.map((m,k)=><div key={k}><span style={{color:matchColor(m),fontWeight:800,fontSize:9.5}}>{m==="AS"?"A/S":m}</span></div>)}
      <div className="sum" style={{color:matchTotColor(matchNet(match))}}>{matchLabel(matchNet(match))}</div>
    </div>
  );

  const legendItems = [["이글 이하","sc-pill eagle"],["버디","sc-pill birdie"],["파","sc-pill par"],["보기","sc-pill bogey"],["더블보기 이상","sc-pill dbogey"]];

  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="스코어카드 상세" onBack={onBack} right={<button className="icon-btn" onClick={onShare}><Icon name="share" size={18}/></button>}/>
      {toast && <div className="toast"><span>{toast}</span></div>}

      <div className="scroll" style={{paddingBottom:40}}>
        {/* 데모: 경기 모드 전환 (실서비스는 라운드 데이터로 자동 결정) */}
        <div style={{display:"flex",alignItems:"center",gap:6,padding:"10px 16px",borderBottom:"1px solid var(--line)",overflowX:"auto",scrollbarWidth:"none"}}>
          <span style={{flexShrink:0,fontSize:9,color:"var(--text-mute)",fontWeight:700,border:"1px dashed var(--line)",borderRadius:4,padding:"2px 5px"}}>데모</span>
          {MODES.map(m=>(
            <button key={m.id} onClick={()=>{setMode(m.id); setOpenP({0:true});}} style={{flexShrink:0,fontSize:11.5,fontWeight:700,padding:"5px 11px",borderRadius:14,border:"none",background:mode===m.id?"var(--primary)":"var(--bg-soft)",color:mode===m.id?"#fff":"var(--text-sub)"}}>{m.label}</button>
          ))}
        </div>

        {/* 코스/라운드 헤더 — 매장+날짜 / CC명(코스 상세) / 경기유형·인원·제품·난이도 */}
        <div style={{padding:"14px 20px 16px",borderBottom:"1px solid var(--line)"}}>
          <div style={{display:"flex",alignItems:"baseline",justifyContent:"space-between"}}>
            <div style={{fontSize:14,fontWeight:600}}>퀀텀 아카데미 판교점</div>
            <div className="mono" style={{fontSize:11,color:"var(--text-sub)"}}>2024.04.02</div>
          </div>
          <button style={{display:"flex",alignItems:"center",gap:3,marginTop:8,background:"transparent",padding:0}}>
            <span style={{fontSize:17,fontWeight:800,letterSpacing:"-.02em"}}>뉴 스프링빌</span>
            <Icon name="chev-r" size={15} style={{color:"var(--text-mute)"}}/>
          </button>
          <div className="muted" style={{fontSize:11.5,marginTop:2}}>록키 코스 · 올림프스 코스</div>
          <div style={{display:"flex",alignItems:"center",gap:8,marginTop:12}}>
            <span style={{display:"inline-flex",alignItems:"center",gap:5,fontSize:12,color:"var(--text-sub)",fontWeight:600}}>
              <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="6" cy="6" r="2.4"/><circle cx="11.5" cy="6.5" r="1.8"/><path d="M2 13c0-2.2 1.8-3.6 4-3.6S10 10.8 10 13M10.5 9.6c1.7.1 3 1.3 3 3.4" strokeLinecap="round"/></svg>
              {metaLabel}
            </span>
            <span style={{width:1,height:11,background:"var(--line-strong)"}}/>
            <span style={{fontSize:11,fontWeight:800,padding:"2px 7px",borderRadius:4,background:"var(--primary-tint)",color:"var(--primary)"}}>Q</span>
            <span style={{fontSize:12,color:"var(--text-sub)",fontWeight:600}}>프로</span>
          </div>
        </div>

        {/* 참가자별 스코어카드 (개인 or 팀, 접기/펴기) */}
        {cards.map((c,i)=>{
          const open = !!openP[i];
          const allS = isMatch ? [] : [...c.sOut, ...c.sIn];
          const dash = !isMatch && hasDash(allS);
          const total = (!isMatch && !dash) ? sum(c.sOut)+sum(c.sIn) : null;
          const mNet = isMatch ? matchNet([...c.mOut, ...c.mIn]) : 0;
          return (
            <div key={i} style={{padding:"14px 20px",borderBottom:"1px solid var(--line)"}}>
              <button onClick={()=>toggleP(i)} style={{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",background:"transparent",padding:0}}>
                <div style={{display:"flex",alignItems:"center",gap:10}}>
                  {isTeam ? (
                    <>
                      <div style={{width:34,height:34,borderRadius:"50%",background:c.color,color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:800,fontSize:13}}>{c.name.replace("Team ","")[0]}</div>
                      <div style={{fontSize:15,fontWeight:700}}>{c.name}</div>
                      <span style={{fontSize:11,fontWeight:700,color:"var(--text-sub)",background:"var(--bg-soft)",padding:"2px 8px",borderRadius:10}}>{c.members.length}명</span>
                    </>
                  ) : (
                    <>
                      <div style={{position:"relative"}}>
                        <div className="avatar" style={{width:34,height:34,fontSize:14}}>{c.name[0]}</div>
                        {c.me && <span style={{position:"absolute",right:-3,bottom:-3,background:"var(--primary)",color:"#fff",fontSize:8.5,fontWeight:800,width:16,height:16,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",border:"1.5px solid #fff"}}>나</span>}
                      </div>
                      <div style={{fontSize:15,fontWeight:700}}>{c.name}</div>
                    </>
                  )}
                </div>
                <div style={{display:"flex",alignItems:"baseline",gap:6}}>
                  {isMatch ? (
                    <div style={{fontSize:19,fontWeight:800,color:matchTotColor(mNet)}}>{matchLabel(mNet)}</div>
                  ) : dash ? (
                    <div style={{fontSize:22,fontWeight:800,color:"var(--text-mute)"}}>-</div>
                  ) : (
                    <>
                      <div style={{fontSize:22,fontWeight:800}}>{total}</div>
                      <div className="mono" style={{fontSize:12,fontWeight:700,color:overColor(total)}}>({overLabel(total)})</div>
                    </>
                  )}
                  <svg viewBox="0 0 16 16" width="16" height="16" style={{marginLeft:4,transform:open?"rotate(180deg)":"none",transition:"transform .15s",color:"var(--text-mute)"}}><path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </div>
              </button>

              {open && (
                <div style={{marginTop:12}}>
                  {isTeam && (
                    <div style={{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10}}>
                      {c.members.map((m,k)=><span key={k} style={{fontSize:11,color:"var(--text-sub)",background:"var(--bg-soft)",padding:"3px 8px",borderRadius:10}}>{m}</span>)}
                    </div>
                  )}
                  {isMatch ? (
                    <>
                      <NineMatch tag="OUT" nums={HOLES_OUT} par={PAR_OUT} match={c.mOut}/>
                      <NineMatch tag="IN"  nums={HOLES_IN}  par={PAR_IN}  match={c.mIn}/>
                    </>
                  ) : (
                    <>
                      <Nine tag="OUT" nums={HOLES_OUT} par={PAR_OUT} score={c.sOut} putt={c.pOut}/>
                      <Nine tag="IN"  nums={HOLES_IN}  par={PAR_IN}  score={c.sIn} putt={c.pIn}/>
                    </>
                  )}
                </div>
              )}
            </div>
          );
        })}

        {/* 범례 — 매치는 UP/AS/DN, 그 외 스코어 색. 한 홀 미진행이면 생략 */}
        {!isNone && (
          <div style={{display:"flex",flexWrap:"wrap",gap:"8px 14px",padding:"12px 20px",borderBottom:"1px solid var(--line)"}}>
            {isMatch ? (
              [["이긴홀 UP","var(--danger)"],["비긴홀 A/S","var(--text-mute)"],["진홀 DN","#2563EB"]].map(([label,col],i)=>(
                <div key={i} style={{display:"flex",alignItems:"center",gap:5,fontSize:11,color:"var(--text-sub)"}}>
                  <span style={{width:8,height:8,borderRadius:"50%",background:col}}/> {label}
                </div>
              ))
            ) : legendItems.map(([label,cls],i)=>(
              <div key={i} style={{display:"flex",alignItems:"center",gap:5,fontSize:11,color:"var(--text-sub)"}}>
                <span className={cls} style={{width:16,height:16,fontSize:0}}/> {label}
              </div>
            ))}
          </div>
        )}

        {/* 한 홀 미진행 — 하단 전부 하이드, 안내 플레이스홀더 */}
        {isNone && (
          <div style={{margin:"20px",padding:"44px 20px",border:"1px dashed var(--line-strong)",borderRadius:12,textAlign:"center",color:"var(--text-mute)",fontSize:13,fontWeight:600}}>
            해당 라운드의 기록이 없습니다.
          </div>
        )}

        {/* 랭킹보드 — 멀티플레이 라운드만 (슬라이드 5570) */}
        {showRanking && (
          <div style={{padding:"20px 20px 0"}}>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
              <div className="h3">랭킹보드</div>
              <button className="icon-btn" aria-label="새로고침">
                <svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="var(--text-sub)" strokeWidth="1.6"><path d="M16 6a7 7 0 1 0 1.5 5" strokeLinecap="round"/><path d="M16 2v4h-4" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </div>
            <div className="card" style={{padding:0,overflow:"hidden"}}>
              <div style={{display:"flex",alignItems:"center",gap:12,padding:"12px 16px",background:"var(--primary-tint)"}}>
                <div style={{width:30,textAlign:"center",fontWeight:800,color:"var(--primary)"}}>{myRank.rank}</div>
                <div style={{flex:1,fontWeight:700}}>{myRank.name}</div>
                <div style={{fontWeight:800}}>{myRank.strokes}타</div>
              </div>
              {ranking.map((r,i)=>(
                <div key={i} style={{display:"flex",alignItems:"center",gap:12,padding:"12px 16px",borderTop:"1px solid var(--line)"}}>
                  <div style={{width:30,textAlign:"center",fontWeight:700,color:"var(--text-sub)"}}>{r.rank}</div>
                  <div style={{flex:1,fontWeight:600}}>{r.name}</div>
                  <div className="mono" style={{fontWeight:700}}>{r.strokes}타</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 스윙영상 — 한 홀 미진행이면 하이드 */}
        {!isNone && (
        <div style={{padding:"20px 20px 0"}}>
          <div className="h3" style={{marginBottom:10}}>스윙영상</div>
          <div className="hscroll">
            {[{tag:"어프로치",dist:"201.1m"},{tag:"티샷",dist:"153.9m"},{tag:"파팅",dist:"3.9m"}].map((s,i)=>(
              <div key={i} className="swing-card">
                <div className="tag">{s.tag}</div>
                <div style={{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",width:30,height:30,borderRadius:"50%",background:"rgba(255,255,255,.22)",display:"flex",alignItems:"center",justifyContent:"center"}}><Icon name="play" size={13}/></div>
                <div className="big" style={{fontSize:16}}>{s.dist}</div>
              </div>
            ))}
          </div>
        </div>
        )}

        {/* 라운드 분석 (나 / 등급평균 / 평가) — 노출조건 미충족 시 영역 하이드 */}
        {analysisAvailable && (
        <div style={{padding:"20px 20px 0"}}>
          <div className="h3" style={{marginBottom:12}}>라운드 분석</div>
          <div className="card" style={{padding:"4px 16px"}}>
            <div style={{display:"grid",gridTemplateColumns:"1.4fr 1fr 1fr 44px",padding:"10px 0",fontSize:11,fontWeight:700,color:"var(--text-mute)",borderBottom:"1px solid var(--line)"}}>
              <div></div><div style={{textAlign:"right"}}>나</div><div style={{textAlign:"right"}}>등급평균</div><div style={{textAlign:"center"}}>평가</div>
            </div>
            {analysis.map((row,k)=>(
              <div key={k} style={{display:"grid",gridTemplateColumns:"1.4fr 1fr 1fr 44px",padding:"11px 0",fontSize:12.5,alignItems:"center",borderBottom:k<analysis.length-1?"1px solid var(--line)":"0"}}>
                <div style={{color:"var(--text-sub)"}}>{row.label}</div>
                <div className="mono" style={{fontWeight:700,textAlign:"right"}}>{row.me}</div>
                <div className="mono" style={{color:"var(--text-sub)",textAlign:"right"}}>{row.avg}</div>
                <div style={{display:"flex",justifyContent:"center"}}>
                  {row.grade ? (
                    <span style={{width:22,height:22,borderRadius:"50%",background:gradeColor(row.grade),color:"#fff",fontSize:11,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center"}}>{row.grade}</span>
                  ) : <span style={{color:"var(--text-mute)"}}>-</span>}
                </div>
              </div>
            ))}
          </div>
        </div>
        )}

        {/* 홀 공략 기록 — 9홀이면 IN 하이드, 한 홀 미진행이면 섹션 하이드 */}
        {!isNone && (
        <div style={{padding:"20px 20px 0"}}>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
            <div className="h3">홀 공략 기록</div>
            <div style={{display:"flex",background:"var(--bg-soft)",borderRadius:8,padding:2}}>
              {["OUT","IN"].map(v=>(
                <button key={v} onClick={()=>{setOi(v); setHole(v==="OUT"?1:10);}} style={{
                  padding:"5px 14px",borderRadius:6,fontSize:12,fontWeight:700,border:"none",
                  background:oi===v?"var(--primary)":"transparent",color:oi===v?"#fff":"var(--text-sub)"
                }}>{v}</button>
              ))}
            </div>
          </div>
          <div className="card" style={{padding:12,background:"#F0FDF4"}}>
            <div style={{position:"relative",height:200,background:"linear-gradient(180deg,#22C55E 0%,#15803D 70%,#166534 100%)",borderRadius:10,overflow:"hidden"}}>
              <div style={{position:"absolute",top:10,bottom:30,left:"35%",right:"35%",background:"rgba(236,253,245,.3)",borderRadius:"50% 50% 40% 40% / 30% 30% 70% 70%"}}/>
              {[{l:42,t:70},{l:52,t:50},{l:48,t:30}].map((s,i)=>(
                <React.Fragment key={i}>
                  <div style={{position:"absolute",left:`${s.l}%`,top:`${s.t}%`,width:10,height:10,borderRadius:"50%",background:"#FF7A1A",boxShadow:"0 0 0 2px #fff",zIndex:2}}/>
                  <div style={{position:"absolute",left:`${s.l}%`,top:`${s.t}%`,fontSize:9,fontWeight:700,color:"#fff",transform:"translate(8px,-14px)"}}>{[ "250.9m","120.2m","18.4m"][i]}</div>
                </React.Fragment>
              ))}
              <div style={{position:"absolute",left:"48%",top:"18%",width:14,height:14}}>
                <svg viewBox="0 0 14 14"><path d="M3 11V2l7 2-4 2 4 2-7 1v2" fill="#fff"/></svg>
              </div>
            </div>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:10}}>
              <button onClick={()=>moveHole(-1)} className="icon-btn" style={{width:28,height:28}}><Icon name="chev-l" size={16}/></button>
              <div style={{display:"flex",alignItems:"center",gap:8,fontSize:12.5}}>
                <span style={{fontWeight:800}}>{hole}H</span>
                <span style={{color:"var(--text-sub)"}}>Par 4 · 310.0m</span>
                <span style={{color:"var(--primary)",fontWeight:700}}>3온 2파팅</span>
              </div>
              <button onClick={()=>moveHole(1)} className="icon-btn" style={{width:28,height:28}}><Icon name="chev-r" size={16}/></button>
            </div>
          </div>
        </div>
        )}

        {/* 샷 기록 — 포섬/포볼은 플레이어 컬럼, 선택 홀과 연동. 한 홀 미진행이면 하이드 */}
        {!isNone && (
        <div style={{padding:"20px 20px 20px"}}>
          <div className="h3" style={{marginBottom:10}}>샷 기록</div>
          <div className="card">
            <div style={{display:"grid",gridTemplateColumns:shotCols,padding:"10px 14px",fontSize:11,fontWeight:700,color:"var(--text-sub)",borderBottom:"1px solid var(--line)"}}>
              <div></div><div>클럽</div><div>구질</div><div style={{textAlign:"right"}}>비거리</div><div style={{textAlign:"right"}}>안착지점</div>{isTeam && <div style={{textAlign:"right"}}>플레이어</div>}
            </div>
            {shots.map((r,i)=>(
              <div key={i} style={{display:"grid",gridTemplateColumns:shotCols,padding:"11px 14px",fontSize:12,alignItems:"center",borderBottom:i<shots.length-1?"1px solid var(--line)":"0"}}>
                <div className="mono" style={{color:"var(--text-mute)",fontWeight:700}}>{r.no}</div>
                <div>{r.club==="-" ? <span style={{color:"var(--text-mute)"}}>-</span> : <span className="chip" style={{background:"#F4F5F7",color:"var(--text)",fontSize:10}}>{r.club}</span>}</div>
                <div style={{color:"var(--text-sub)"}}>{r.shape}</div>
                <div className="mono" style={{fontWeight:700,textAlign:"right"}}>{r.dist}</div>
                <div style={{textAlign:"right",fontWeight:600,color:landColor(r.land)}}>{r.land}</div>
                {isTeam && <div style={{textAlign:"right",color:"var(--text-sub)",fontSize:11}}>{r.player}</div>}
              </div>
            ))}
          </div>
        </div>
        )}
      </div>
    </div>
  );
}

function ScorecardShare({ onBack }){
  const [mode, setMode] = React.useState("basic");
  const [variant, setVariant] = React.useState("stroke"); // 기본형: 스트로크 / 포섬·포볼 매치
  const [bg, setBg] = React.useState("char");
  const [editTab, setEditTab] = React.useState("bg");     // 편집형: 배경 / 레이아웃
  const [layout, setLayout] = React.useState("br");       // 점수 우하단 / 중앙 / 스코어카드
  const [toast, setToast] = React.useState(null);
  const [sheet, setSheet] = React.useState(false);

  const bgs = [
    {id:"char", label:"캐릭터", icon:"char"},
    {id:"course", label:"코스", icon:"flag-pin"},
    {id:"camera", label:"카메라", icon:"cam-round"},
    {id:"album", label:"앨범", icon:"album-round"},
  ];
  const layouts = [{id:"br",label:"점수 우하단"},{id:"center",label:"점수 중앙"},{id:"card",label:"스코어카드"}];
  const popToast = (m)=>{ setToast(m); setTimeout(()=>setToast(null), 2400); };
  const doShare = (ch)=>{ setSheet(false); popToast(`${ch}(으)로 공유했습니다.`); };

  // 기본형 카드 데이터 (매치는 홀별 UP/AS/DN)
  const blocks = [
    {tag:"OUT", holes:[1,2,3,4,5,6,7,8,9],        pars:[4,4,5,3,4,5,3,4,4,36], scores:[4,1,2,1,3,3,1,1,3,19], putts:[2,2,2,2,2,2,2,2,2,18], match:["UP","AS","AS","UP","UP","UP","UP","UP","UP","7UP"]},
    {tag:"IN",  holes:[10,11,12,13,14,15,16,17,18], pars:[4,5,4,3,4,5,4,3,4,36], scores:[0,2,3,0,1,1,0,0,1,8],  putts:[1,1,2,1,1,1,1,2,2,12], match:["AS","UP","AS","UP","AS","DN","UP","UP","UP","4UP"]},
  ];
  const mColor = m => /UP/.test(m) ? "var(--danger)" : /DN/.test(m) ? "#2563EB" : "var(--text-mute)";

  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="스코어카드 공유하기" onBack={onBack}/>
      {toast && <div className="toast"><span>{toast}</span></div>}

      <div className="scroll" style={{padding:"12px 20px 140px"}}>
        <div className="h-tabs" style={{marginBottom:16}}>
          <button className={mode==="basic"?"on":""} onClick={()=>setMode("basic")}>기본형</button>
          <button className={mode==="edit"?"on":""} onClick={()=>setMode("edit")}>편집형</button>
        </div>

        {mode==="basic" ? (
          <>
            {/* 데모: 스트로크 / 포섬·포볼 매치 */}
            <div style={{display:"flex",gap:6,marginBottom:14}}>
              {[["stroke","스트로크"],["match","포섬·포볼 매치"]].map(([id,label])=>(
                <button key={id} onClick={()=>setVariant(id)} style={{fontSize:11.5,fontWeight:700,padding:"5px 11px",borderRadius:14,border:"none",background:variant===id?"var(--primary)":"var(--bg-soft)",color:variant===id?"#fff":"var(--text-sub)"}}>{label}</button>
              ))}
            </div>
            <div className="card" style={{overflow:"hidden"}}>
              <div style={{padding:"18px 16px 14px"}}>
                <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between"}}>
                  <div>
                    <div style={{fontSize:16,fontWeight:800}}>{variant==="match"?"Team EPIC":"나는쏘니야"}</div>
                    <div className="muted" style={{fontSize:11,marginTop:2}}>비에이비스타 · 몬티 / 벨라</div>
                  </div>
                  <div style={{fontSize:variant==="match"?28:38,fontWeight:800,letterSpacing:"-.03em",color:variant==="match"?"var(--danger)":"var(--text)"}}>{variant==="match"?"11UP":"99"}</div>
                </div>
              </div>

              {blocks.map((blk,bi)=>(
                <div key={bi} style={{borderTop:"1px solid var(--line)"}}>
                  <div style={{display:"grid",gridTemplateColumns:"52px repeat(9,1fr) 36px",fontSize:11}}>
                    <div style={{padding:"9px 0",textAlign:"center",fontWeight:700,color:"var(--text-sub)",background:"#FAFBFC"}}>HOLE</div>
                    {blk.holes.map((h,k)=><div key={k} style={{padding:"9px 0",textAlign:"center",fontWeight:700,color:"var(--text-sub)",background:"#FAFBFC"}}>{h}</div>)}
                    <div style={{padding:"9px 0",textAlign:"center",fontWeight:700,color:"var(--text-sub)",background:"#F1F3F5"}}>{blk.tag}</div>

                    <div style={{background:"#F4F5F7",padding:"10px 0",textAlign:"center",fontWeight:700,color:"var(--text-sub)"}}>PAR</div>
                    {blk.pars.slice(0,9).map((v,k)=><div key={k} style={{padding:"10px 0",textAlign:"center",background:"#F4F5F7",fontWeight:600,color:"var(--text-sub)"}}>{v}</div>)}
                    <div style={{padding:"10px 0",textAlign:"center",background:"#E5E7EB",fontWeight:700,color:"var(--text-sub)"}}>{blk.pars[9]}</div>

                    {variant==="match" ? (
                      <>
                        <div style={{padding:"10px 0",textAlign:"center",fontWeight:700,color:"var(--text-sub)"}}>MATCH</div>
                        {blk.match.slice(0,9).map((m,k)=><div key={k} style={{padding:"10px 0",textAlign:"center",fontWeight:800,fontSize:9.5,color:mColor(m)}}>{m==="AS"?"A/S":m}</div>)}
                        <div style={{padding:"10px 0",textAlign:"center",fontWeight:800,fontSize:10,color:mColor(blk.match[9])}}>{blk.match[9]}</div>
                      </>
                    ) : (
                      <>
                        <div style={{padding:"10px 0",textAlign:"center",fontWeight:700,color:"var(--text-sub)"}}>SCORE</div>
                        {blk.scores.slice(0,9).map((v,k)=>{ const par=blk.pars[k]; const on=v>0&&v<par;
                          return <div key={k} style={{padding:"4px 0",textAlign:"center"}}>{on?<span className="sc-pill" style={{background:"#BEE5FA",color:"#0284C7"}}>{v}</span>:<span>{v}</span>}</div>; })}
                        <div style={{padding:"10px 0",textAlign:"center",fontWeight:800}}>{blk.scores[9]}</div>

                        <div style={{padding:"10px 0",textAlign:"center",fontWeight:700,color:"var(--text-sub)"}}>PUTT</div>
                        {blk.putts.slice(0,9).map((v,k)=><div key={k} style={{padding:"10px 0",textAlign:"center"}}>{v}</div>)}
                        <div style={{padding:"10px 0",textAlign:"center",fontWeight:700}}>{blk.putts[9]}</div>
                      </>
                    )}
                  </div>
                </div>
              ))}

              <div style={{background:"#1A1C1F",color:"#fff",padding:"14px 16px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                <div style={{fontWeight:800,letterSpacing:"-.01em"}}>QUANTUM RANGE</div>
                <div className="mono" style={{fontSize:12}}>2024.07.19</div>
              </div>
            </div>
            <div className="muted" style={{fontSize:11,marginTop:10,lineHeight:1.5}}>· 9홀(또는 미진행 홀)은 후반 IN코스가 <b style={{color:"var(--text-sub)"}}>-</b>로 표기되어 공유 · FA 9홀은 공유 불가</div>
          </>
        ) : (
          <>
            <div style={{
              height:380,borderRadius:12,position:"relative",overflow:"hidden",
              background:bg==="char" ? "linear-gradient(180deg,#7dd3fc 0%,#38bdf8 55%,#86efac 100%)" :
                         bg==="course" ? "linear-gradient(180deg,#0f172a 0%,#312e81 30%,#84cc16 70%,#166534 100%)" :
                         bg==="camera" ? "linear-gradient(135deg,#475569,#1e293b)" :
                         "linear-gradient(135deg,#fde68a,#fbbf24)",
            }}>
              <div style={{position:"absolute",top:14,left:14,right:14,display:"flex",justifyContent:"space-between",color:"#fff"}}>
                <div style={{fontWeight:800,letterSpacing:"-.01em"}}>QUANTUM RANGE</div>
                <div className="mono" style={{fontSize:12}}>2024.07.19</div>
              </div>

              {bg==="char" && (
                <div className="char-ph" style={{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%,-55%)",width:160,height:160,borderRadius:28}}>placeholder: 라이언</div>
              )}
              {bg==="course" && (
                <div style={{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",opacity:.5,color:"rgba(255,255,255,.6)",fontFamily:"DM Mono,monospace",fontSize:12}}>course_photo</div>
              )}
              {(bg==="camera"||bg==="album") && (
                <div style={{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"rgba(255,255,255,.8)",fontSize:13,fontWeight:600}}>{bg==="camera"?"카메라 촬영 사진":"앨범 사진"}</div>
              )}

              {layout==="card" ? (
                <div style={{position:"absolute",left:14,right:14,bottom:14,background:"rgba(255,255,255,.94)",borderRadius:10,padding:"10px 12px"}}>
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
                    <div style={{fontSize:14,fontWeight:800}}>라이언</div>
                    <div style={{fontSize:24,fontWeight:800}}>74</div>
                  </div>
                  <div style={{display:"grid",gridTemplateColumns:"repeat(9,1fr)",gap:2}}>
                    {[4,3,5,4,4,3,4,5,4].map((v,k)=><div key={k} style={{fontSize:9,textAlign:"center",color:"var(--text-sub)"}}>{v}</div>)}
                  </div>
                </div>
              ) : (
                <div style={{position:"absolute",left:14,right:14,bottom:14,background:"rgba(20,30,40,.55)",backdropFilter:"blur(8px)",borderRadius:10,padding:"14px 16px",display:"flex",flexDirection:layout==="center"?"column":"row",alignItems:layout==="center"?"center":"flex-end",justifyContent:"space-between",gap:layout==="center"?4:0,textAlign:layout==="center"?"center":"left",color:"#fff"}}>
                  <div>
                    <div style={{fontSize:16,fontWeight:800}}>라이언</div>
                    <div style={{fontSize:11,opacity:.85,marginTop:2}}>비에이비스타 · 몬티 / 벨라</div>
                  </div>
                  <div style={{fontSize:44,fontWeight:800,letterSpacing:"-.04em",lineHeight:1}}>74</div>
                </div>
              )}
            </div>

            {/* 배경 / 레이아웃 서브탭 */}
            <div style={{display:"flex",gap:16,marginTop:20,borderBottom:"1px solid var(--line)",padding:"0 4px"}}>
              {[["bg","배경"],["layout","레이아웃"]].map(([id,label])=>(
                <button key={id} onClick={()=>setEditTab(id)} style={{padding:"10px 0",fontSize:14,fontWeight:700,background:"transparent",color:editTab===id?"var(--text)":"var(--text-mute)",borderBottom:editTab===id?"2px solid var(--text)":"2px solid transparent",marginBottom:-1}}>{label}</button>
              ))}
            </div>

            {editTab==="bg" ? (
              <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8,marginTop:20}}>
                {bgs.map(b=>(
                  <button key={b.id} onClick={()=>setBg(b.id)} className="cat">
                    <div className="ic" style={{border:bg===b.id?"2px solid var(--primary)":"2px solid transparent",background:bg===b.id?"#fff":"#F4F5F7"}}>
                      <Icon name={b.icon} size={28}/>
                    </div>
                    <div className="nm">{b.label}</div>
                  </button>
                ))}
              </div>
            ) : (
              <div style={{display:"flex",gap:8,marginTop:20}}>
                {layouts.map(l=>(
                  <button key={l.id} onClick={()=>setLayout(l.id)} style={{flex:1,padding:"11px 0",borderRadius:9,fontSize:12,fontWeight:700,border:layout===l.id?"2px solid var(--primary)":"1px solid var(--line)",background:layout===l.id?"var(--primary-tint)":"#fff",color:layout===l.id?"var(--primary)":"var(--text-sub)"}}>{l.label}</button>
                ))}
              </div>
            )}
          </>
        )}
      </div>

      <div style={{position:"absolute",bottom:0,left:0,right:0,padding:"14px 20px 24px",background:"#fff",borderTop:"1px solid var(--line)",display:"flex",gap:8}}>
        <button className="btn btn-outline" style={{flex:1}} onClick={()=>popToast("이미지 저장이 완료되었습니다.")}>이미지 저장</button>
        <button className="btn btn-primary" style={{flex:1.4}} onClick={()=>setSheet(true)}>공유하기</button>
      </div>

      {/* 시스템 공유 시트 */}
      {sheet && (
        <div onClick={()=>setSheet(false)} style={{position:"absolute",inset:0,background:"rgba(0,0,0,.4)",zIndex:30,display:"flex",alignItems:"flex-end"}}>
          <div onClick={e=>e.stopPropagation()} style={{width:"100%",background:"#fff",borderRadius:"16px 16px 0 0",padding:"10px 20px 28px"}}>
            <div style={{width:40,height:4,borderRadius:2,background:"var(--line-strong)",margin:"6px auto 16px"}}/>
            <div style={{fontSize:14,fontWeight:800,marginBottom:16}}>공유하기</div>
            <div style={{display:"flex",justifyContent:"space-around"}}>
              {[{k:"메시지",c:"#34C759"},{k:"카카오톡",c:"#FAE100"},{k:"인스타그램",c:"#E1306C"}].map(o=>(
                <button key={o.k} onClick={()=>doShare(o.k)} style={{display:"flex",flexDirection:"column",alignItems:"center",gap:8,background:"transparent"}}>
                  <div style={{width:52,height:52,borderRadius:"50%",background:o.c,display:"flex",alignItems:"center",justifyContent:"center",fontWeight:800,color:o.k==="카카오톡"?"#3A1D1D":"#fff",fontSize:18}}>{o.k[0]}</div>
                  <div style={{fontSize:11,color:"var(--text-sub)",fontWeight:600}}>{o.k}</div>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ===== 기록 분석 상세 (리포트 기록분석 → 지표 드릴다운, FS ReportScreenAnalyzeFragment / Figma 기록분석1~6) =====
// 추이 라인차트 (지표 자체 min/max로 정규화)
function TrendChart({ data }){
  const W=320,H=132,padX=16,padT=26,padB=16;
  const min=Math.min(...data), max=Math.max(...data), rng=(max-min)||1;
  const x=i=> padX + i*(W-2*padX)/(data.length-1);
  const y=v=> padT + (1-(v-min)/rng)*(H-padT-padB);
  const pts=data.map((v,i)=>[x(i),y(v)]);
  const line=pts.map(p=>p.join(",")).join(" ");
  const area=`${padX},${H-padB} ${line} ${W-padX},${H-padB}`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{display:"block"}}>
      <polygon points={area} fill="rgba(34,197,94,.10)"/>
      <polyline points={line} fill="none" stroke="#22C55E" strokeWidth="2" strokeLinejoin="round"/>
      {pts.map((p,i)=>(
        <g key={i}>
          <circle cx={p[0]} cy={p[1]} r="3.1" fill="#16A34A"/>
          <text x={p[0]} y={p[1]-8} fontSize="8.5" fontWeight="700" fill="#4B5563" textAnchor="middle">{data[i]}</text>
        </g>
      ))}
    </svg>
  );
}

// 반원 게이지 (스코어 분포 · 퍼트 정확도) — 세그먼트 비율만큼 호를 채움
function GaugeSemi({ segs }){
  const r=72, cx=100, cy=94, sw=28, C=Math.PI*r;
  const total=segs.reduce((s,x)=>s+(x.w||0),0)||1;
  const path=`M ${cx-r} ${cy} A ${r} ${r} 0 0 1 ${cx+r} ${cy}`;
  let off=0;
  return (
    <svg viewBox="0 0 200 108" width="100%" style={{maxWidth:250,display:"block",margin:"4px auto 0"}}>
      <path d={path} fill="none" stroke="var(--bg-soft)" strokeWidth={sw}/>
      {segs.map((s,i)=>{ const len=s.w/total*C; const el=(
        <path key={i} d={path} fill="none" stroke={s.color} strokeWidth={sw}
          strokeDasharray={`${Math.max(len-1.5,0)} ${C}`} strokeDashoffset={-off} strokeLinecap="butt"/>
      ); off+=len; return el; })}
    </svg>
  );
}

function AnalysisDetail({ metric="score", onBack }){
  const grid = [
    {id:"score",   v:"90타",   l:"타수"},
    {id:"drive",   v:"222.7m", l:"드라이브 거리"},
    {id:"fairway", v:"90.4%",  l:"페어웨이 안착률"},
    {id:"green",   v:"60.0%",  l:"그린 적중률"},
    {id:"parsave", v:"20.9%",  l:"파 세이브율"},
    {id:"putt",    v:"2.1타",  l:"평균 퍼팅"},
  ];
  const M = {
    score:   {title:"평균 타수",     grade:"Normal", my:"90타",   avg:"100타",  trend:[90,89,88,85,76,78,83,92,92,117]},
    drive:   {title:"드라이브 거리",  grade:"Good",   my:"183.1m", avg:"171.9m", trend:[168,175,180,172,185,179,188,183]},
    fairway: {title:"페어웨이 안착률", grade:"Normal", my:"60.9%",  avg:"78.3%",  trend:[55,62,58,66,60,71,57,61], rounds:true},
    green:   {title:"그린 적중률",    grade:"Bad",    my:"5.2%",   avg:"8.3%",   trend:[4,6,5,7,5,8,6,5]},
    parsave: {title:"파 세이브율",    grade:"Normal", my:"20.5%",  avg:"21.3%",  trend:[18,22,19,25,20,24,17,21]},
    putt:    {title:"평균 퍼팅",      grade:"Good",   my:"2.1타",  avg:"2.3타",  trend:[2.3,2.1,2.4,2.0,2.2,1.9,2.5,2.1]},
  };
  const [sel, setSel] = React.useState(M[metric] ? metric : "score");
  const cur = M[sel];

  const gradeBadge = (g)=>{ const map={Good:["#16A34A","#DCFCE7"],Normal:["#6B7280","#F3F4F6"],Bad:["#EF4444","#FEE2E2"]};
    const [c,bg]=map[g]||map.Normal; return <span style={{fontSize:10,fontWeight:800,color:c,background:bg,padding:"3px 9px",borderRadius:6}}>{g}</span>; };

  // 지표별 하단 분석 섹션
  const StatRows = ({rows})=>(
    <div style={{marginTop:14}}>
      {rows.map((r,i)=>(
        <div key={i} style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"11px 4px",borderTop:i>0?"1px solid var(--line)":"0",fontSize:13}}>
          <span style={{color:"var(--text-sub)"}}>{r.k}</span>
          <span style={{fontWeight:700}}>{r.v}</span>
        </div>
      ))}
    </div>
  );
  const dist = { // 스코어 분포 / 퍼트 정확도 세그먼트 (게이지+리스트)
    score:[
      {label:"버디 이하",  cnt:"1회",  w:1,  color:"#F472B6"},
      {label:"파",         cnt:"13회", w:13, color:"#22C55E"},
      {label:"보기",       cnt:"2회",  w:2,  color:"#FDE047"},
      {label:"더블보기",   cnt:"2회",  w:2,  color:"#FB923C"},
      {label:"트리플보기 이상", cnt:"0회", w:0.001, color:"#D1D5DB"},
    ],
    putt:[
      {label:"1퍼트",       cnt:"9회", w:9, color:"#15803D"},
      {label:"2퍼트",       cnt:"2회", w:2, color:"#22C55E"},
      {label:"3퍼트 이상",  cnt:"7회", w:7, color:"#86EFAC"},
    ],
  };
  const DistSection = ({title, segs})=>(
    <>
      <SectionHead title={title}/>
      <GaugeSemi segs={segs}/>
      <div style={{marginTop:6}}>
        {segs.map((s,i)=>(
          <div key={i} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"9px 4px",borderTop:i>0?"1px solid var(--line)":"0"}}>
            <span style={{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text-sub)"}}>
              <span style={{width:9,height:9,borderRadius:"50%",background:s.color}}/>{s.label}
            </span>
            <span style={{fontWeight:700,fontSize:13}}>{s.cnt}</span>
          </div>
        ))}
      </div>
    </>
  );
  // 존 비율 리스트 (안착률/홀컵)
  const zoneList = z => (
    <div style={{marginTop:14}}>
      {z.map((r,i)=>(
        <div key={i} style={{display:"flex",justifyContent:"space-between",padding:"10px 4px",borderTop:i>0?"1px solid var(--line)":"0",fontSize:13}}>
          <span style={{color:"var(--text-sub)"}}>{r.k}</span><span style={{fontWeight:700}}>{r.v}</span>
        </div>
      ))}
    </div>
  );

  const section = () => {
    switch(sel){
      case "score": return <DistSection title="스코어 분포" segs={dist.score}/>;
      case "putt":  return <DistSection title="퍼트 정확도" segs={dist.putt}/>;
      case "drive": return (<>
        <SectionHead title="드라이브 샷 분석"/>
        <svg viewBox="0 0 220 120" width="100%" style={{maxWidth:280,display:"block",margin:"6px auto 0"}}>
          {[0,12,24,36,48].map((a,i)=>{ const rad=(a)*Math.PI/180; const L=150;
            return <line key={i} x1="40" y1="104" x2={40+L*Math.cos(rad)} y2={104-L*Math.sin(rad)} stroke="var(--line)" strokeWidth="1"/>; })}
          <path d={`M40 104 L${40+150*Math.cos(12*Math.PI/180)} ${104-150*Math.sin(12*Math.PI/180)} A150 150 0 0 0 ${40+150*Math.cos(18*Math.PI/180)} ${104-150*Math.sin(18*Math.PI/180)} Z`} fill="rgba(34,197,94,.16)"/>
          <line x1="40" y1="104" x2={40+150*Math.cos(15.3*Math.PI/180)} y2={104-150*Math.sin(15.3*Math.PI/180)} stroke="#22C55E" strokeWidth="2.2"/>
          <circle cx="40" cy="104" r="7" fill="#fff" stroke="var(--line-strong)" strokeWidth="1.4"/>
          <text x="150" y="60" fontSize="15" fontWeight="800" fill="#16A34A">15.3°</text>
        </svg>
        <StatRows rows={[{k:"나의 발사각",v:"15.3°"},{k:"나의 볼스피드",v:"66.1m/s"}]}/>
      </>);
      case "fairway": return (<>
        <SectionHead title="안착률 분석"/>
        <svg viewBox="0 0 260 150" width="100%" style={{maxWidth:300,display:"block",margin:"6px auto 0"}}>
          <path d="M30 96 Q20 44 78 40 Q150 34 176 58 Q212 90 168 118 Q96 142 56 124 Q30 114 30 96Z" fill="#15803D"/>
          <path d="M64 92 Q58 60 104 58 Q150 56 160 78 Q168 100 132 110 Q92 120 72 108 Q62 102 64 92Z" fill="#4ADE80"/>
          <text x="26" y="40" fontSize="10" fontWeight="700" fill="var(--text-sub)">OB 10%</text>
          <text x="104" y="46" fontSize="10" fontWeight="800" fill="#166534">벙커 10%</text>
          <text x="26" y="118" fontSize="10" fontWeight="700" fill="var(--text-sub)">러프 10%</text>
          <text x="196" y="120" fontSize="10" fontWeight="700" fill="var(--text-sub)">해저드 10%</text>
          <text x="104" y="90" fontSize="11" fontWeight="800" fill="#fff">페어웨이</text>
        </svg>
        {zoneList([{k:"페어웨이",v:"50%"},{k:"벙커",v:"10%"},{k:"러프",v:"10%"},{k:"OB",v:"10%"},{k:"해저드",v:"10%"}])}
      </>);
      case "green": return (<>
        <SectionHead title="홀컵 적중도"/>
        <svg viewBox="0 0 220 150" width="100%" style={{maxWidth:280,display:"block",margin:"6px auto 0"}}>
          <ellipse cx="110" cy="80" rx="98" ry="62" fill="#15803D"/>
          <ellipse cx="110" cy="80" rx="66" ry="42" fill="#22C55E"/>
          <ellipse cx="110" cy="80" rx="34" ry="22" fill="#86EFAC"/>
          <text x="30" y="82" fontSize="10" fontWeight="700" fill="#fff">10m이내 10%</text>
          <text x="72" y="70" fontSize="10" fontWeight="800" fill="#166534">5m이내 10%</text>
          <text x="96" y="84" fontSize="9.5" fontWeight="800" fill="#166534">3m 10%</text>
          <path d="M132 60 v-22 l10 4-10 4" fill="#DC2626" stroke="#DC2626" strokeWidth="1.5"/>
        </svg>
        {zoneList([{k:"3m 이내",v:"10%"},{k:"5m 이내",v:"10%"},{k:"10m 이내",v:"10%"}])}
      </>);
      case "parsave": return (<>
        <SectionHead title="샌드 세이브율" badge={gradeBadge("Good")} my="50.5%" avg="48.3%"/>
        <StatRows rows={[{k:"시도 횟수",v:"9회"},{k:"성공 횟수",v:"5회"}]}/>
      </>);
      default: return null;
    }
  };

  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="기록 분석" onBack={onBack} right={<button className="icon-btn"><Icon name="share" size={18}/></button>}/>
      <div className="scroll" style={{paddingBottom:40}}>
        {/* 필터 */}
        <div className="fchips" style={{paddingTop:12}}>
          <button className="fchip on">Q <Icon name="chev-d"/></button>
          <button className="fchip">필터 <Icon name="chev-d"/></button>
          {cur.rounds && <><button className="fchip">라운드채본 <Icon name="chev-d"/></button><button className="fchip">라운드안해본 <Icon name="chev-d"/></button></>}
        </div>

        {/* 지표 선택 그리드 */}
        <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:8,padding:"6px 20px 4px"}}>
          {grid.map(g=>{ const on=sel===g.id; return (
            <button key={g.id} onClick={()=>setSel(g.id)} style={{textAlign:"left",padding:"12px 12px",borderRadius:12,border:"none",
              background:on?"var(--primary)":"var(--bg-soft)"}}>
              <div style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em",color:on?"#fff":"var(--text)"}}>{g.v}</div>
              <div style={{fontSize:11,fontWeight:600,marginTop:3,color:on?"rgba(255,255,255,.9)":"var(--text-sub)"}}>{g.l}</div>
            </button>
          ); })}
        </div>

        {/* 선택 지표 헤더 + 추이 */}
        <div style={{padding:"14px 20px 0"}}>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
            <div style={{display:"flex",alignItems:"center",gap:8}}>
              <span style={{fontSize:17,fontWeight:800,letterSpacing:"-.02em"}}>{cur.title}</span>
              {gradeBadge(cur.grade)}
            </div>
            <div style={{textAlign:"right"}}>
              <div style={{display:"flex",gap:14,alignItems:"baseline"}}>
                <span style={{fontSize:11,color:"var(--text-mute)"}}>나의 평균</span>
                <span style={{fontSize:11,color:"var(--text-mute)"}}>등급 평균</span>
              </div>
              <div style={{display:"flex",gap:14,alignItems:"baseline",marginTop:2}}>
                <span style={{fontSize:16,fontWeight:800,color:"var(--primary)"}}>{cur.my}</span>
                <span style={{fontSize:16,fontWeight:800,color:"var(--text-sub)"}}>{cur.avg}</span>
              </div>
            </div>
          </div>
          <div style={{marginTop:14}}><TrendChart data={cur.trend}/></div>
        </div>

        <div style={{height:10,background:"var(--bg-soft)",margin:"18px 0 0"}}/>
        <div style={{padding:"18px 20px 0"}}>{section()}</div>
      </div>
    </div>
  );
}

// 하단 분석 섹션 헤더 (제목 + 날짜, 옵션 등급배지·나/등급평균)
function SectionHead({ title, badge, my, avg }){
  return (
    <div style={{marginBottom:6}}>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <span style={{fontSize:16,fontWeight:800,letterSpacing:"-.02em"}}>{title}</span>
          {badge}
        </div>
        {my ? (
          <div style={{textAlign:"right"}}>
            <div style={{display:"flex",gap:14}}><span style={{fontSize:11,color:"var(--text-mute)"}}>나의 평균</span><span style={{fontSize:11,color:"var(--text-mute)"}}>등급 평균</span></div>
            <div style={{display:"flex",gap:14,marginTop:2}}><span style={{fontSize:15,fontWeight:800,color:"var(--primary)"}}>{my}</span><span style={{fontSize:15,fontWeight:800,color:"var(--text-sub)"}}>{avg}</span></div>
          </div>
        ) : <span className="mono" style={{fontSize:11,color:"var(--text-mute)"}}>2024.02.17</span>}
      </div>
    </div>
  );
}

Object.assign(window, { ReportScreen, ScorecardListScreen, ScorecardDetail, ScorecardShare, AnalysisDetail });
