// "사용 가능한 레슨권" — Home에서 "레슨 예약" 진입 시 보여주는 첫 화면
// 보유 레슨권이 있으면 리스트(진행도 포함), 없으면 빈 상태(레슨권 구매하기)

// 공유 보유 이용권 (구매한 이용권) — window 레벨로 구매·예약 흐름이 함께 참조
window.QA_OWNED = window.QA_OWNED || [
  {id:"own-jo", type:"lesson", kind:"정기이용권", name:"조현진 프로 레슨권", store:"퀀텀 아카데미 광교점", remainText:"1회(60분) 남음", remain:1, time:"60분", progress:null, pro:{name:"조현진 프로", init:"조", career:"KPGA 투어 3년 · 레슨 8년"}},
  {id:"own-han", type:"lesson", kind:"일일이용권", name:"한진선 프로 레슨권 100", store:"퀀텀 아카데미 판교점", remainText:"8일 남음", remain:8, time:"100분", progress:{used:40, total:100, label:"40분 연습완료", remain:"60분 이용가능"}, pro:{name:"한진선 프로", init:"한", career:"KLPGA 세미 · 여성 전문"}},
  {id:"own-pkg", type:"lesson", kind:"패키지 이용권", name:"조현진 프로 패키지 (레슨+연습)", store:"퀀텀 아카데미 판교점", remainText:"5회 남음", remain:5, time:"60분", package:true, pro:{name:"조현진 프로", init:"조", career:"KPGA 투어 3년 · 레슨 8년"}},
  {id:"own-fa", type:"training", name:"FA 무제한 60분", store:"퀀텀 아카데미 판교점", remainText:"잔여 14회", price:"-", meta:[["1일 사용가능 시간","60분"],["이용기간","90일"]]},
];
function ownedTickets(type){ return (window.QA_OWNED||[]).filter(t=>!type||t.type===type); }
function addOwnedTicket(t){ window.QA_OWNED = [t, ...(window.QA_OWNED||[])]; }

function LessonTickets({ onBack, onPickTicket, onBuy }){
  const [empty, setEmpty] = React.useState(false); // 데모 토글
  const list = ownedTickets("lesson");

  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="사용 가능한 레슨권" onBack={onBack}
        right={
          <button className="icon-btn" onClick={()=>setEmpty(e=>!e)}
            style={{fontSize:10,fontWeight:600,color:"var(--text-mute)",padding:"4px 6px"}}>
            (데모 {empty?"빈상태":"보유"})
          </button>
        }/>

      {!empty ? (
        <div className="scroll" style={{padding:"14px 20px 32px"}}>
          <div style={{display:"flex",flexDirection:"column",gap:12}}>
            {list.map(t=>(
              <button key={t.id} onClick={()=>onPickTicket && onPickTicket(t)}
                className="card" style={{padding:"16px 18px",textAlign:"left",display:"block"}}>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start"}}>
                  <span style={{fontSize:12,color:"var(--text-sub)"}}>{t.kind}</span>
                  <span style={{fontSize:12,fontWeight:700,color:"var(--primary)"}}>{t.remainText}</span>
                </div>
                <div style={{display:"flex",alignItems:"center",gap:4,marginTop:6,fontSize:16,fontWeight:800,letterSpacing:"-.01em",color:"var(--text)"}}>
                  {t.name}
                  <svg viewBox="0 0 12 12" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.6">
                    <path d="M4 2l4 4-4 4" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
                <div style={{display:"flex",alignItems:"center",gap:4,marginTop:6,fontSize:12,color:"var(--text-sub)"}}>
                  <svg viewBox="0 0 14 14" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.4">
                    <path d="M7 1l2 4 4 .6-3 3 .7 4.4L7 11l-3.7 2L4 8.6 1 5.6 5 5z"/>
                  </svg>
                  {t.store}
                </div>

                {t.progress && (
                  <div style={{marginTop:14}}>
                    <div style={{height:4,background:"var(--bg-soft)",borderRadius:99,overflow:"hidden"}}>
                      <div style={{
                        width:`${(t.progress.used/t.progress.total)*100}%`,
                        height:"100%",background:"var(--primary)",borderRadius:99
                      }}/>
                    </div>
                    <div style={{display:"flex",justifyContent:"space-between",marginTop:8,fontSize:11}}>
                      <span style={{color:"var(--primary)",fontWeight:700}}>{t.progress.label}</span>
                      <span style={{color:"var(--text-mute)"}}>{t.progress.remain}</span>
                    </div>
                  </div>
                )}
              </button>
            ))}
          </div>

          <button onClick={onBuy} style={{
            marginTop:20,width:"100%",height:46,borderRadius:10,
            background:"#fff",border:"1px solid var(--line-strong)",
            fontSize:13,fontWeight:700,color:"var(--text)",
            display:"flex",alignItems:"center",justifyContent:"center",gap:6
          }}>
            <span style={{fontSize:14,lineHeight:1}}>+</span> 레슨권 추가 구매하기
          </button>
        </div>
      ) : (
        <>
          <div className="scroll" style={{padding:"0 20px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"}}>
            <div style={{
              width:80,height:80,borderRadius:"50%",background:"var(--bg-soft)",
              display:"flex",alignItems:"center",justifyContent:"center",marginBottom:18
            }}>
              <svg viewBox="0 0 40 40" width="40" height="40" fill="none" stroke="#9CA3AF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M8 11h24a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H17l-6 5v-5H8a3 3 0 0 1-3-3V14a3 3 0 0 1 3-3z"/>
                <circle cx="15" cy="20" r="1.4" fill="#9CA3AF" stroke="none"/>
                <circle cx="20" cy="20" r="1.4" fill="#9CA3AF" stroke="none"/>
                <circle cx="25" cy="20" r="1.4" fill="#9CA3AF" stroke="none"/>
              </svg>
            </div>
            <div style={{fontSize:15,color:"var(--text-sub)",fontWeight:500}}>사용 가능한 이용권이 없어요.</div>
          </div>

          <div className="footer-bar">
            <button className="btn btn-primary" style={{width:"100%"}} onClick={onBuy}>레슨권 구매하기</button>
          </div>
        </>
      )}
    </div>
  );
}

// ============================================================
// 이용권 구매 플로우 — 유형 → 매장 → 종류/프로 → 시작일 → 결제 → 완료
// 매장별 담당 프로·이용권 종류 상이 / 시작일 선택 / 휴업일 수만큼 사용기간 자동 연장
// ============================================================
const BUY_STORES = [
  {id:1, name:"퀀텀 아카데미 판교점", addr:"경기 성남시 분당구 판교역로 235", closures:2, x:54, y:50, type:"q", open:true, badges:["coupon"],
    pros:[
      {id:"jo", name:"조현진 프로", career:"KPGA 투어 3년 · 레슨 8년", init:"조",
        tickets:[
          {id:"jo12", name:"조현진 프로 정기 레슨권", desc:"주 1회 · 60분", count:"12회", validDays:90, price:480000, tag:"인기"},
          {id:"joday", name:"조현진 프로 일일 레슨권", desc:"60분 1회", count:"1회", validDays:30, price:45000},
        ]},
      {id:"han", name:"한진선 프로", career:"KLPGA 세미 · 여성 전문", init:"한",
        tickets:[ {id:"han100", name:"한진선 프로 레슨권 100", desc:"100분 패키지", count:"100분", validDays:60, price:120000} ]},
    ],
    training:[
      {id:"fa30", name:"FA 무제한 30일권", desc:"기간 내 연습 무제한", count:"무제한", validDays:30, price:99000, tag:"인기"},
      {id:"t10", name:"트레이닝 10회권", desc:"회당 60분", count:"10회", validDays:90, price:60000},
    ]},
  {id:2, name:"퀀텀 아카데미 광교점", addr:"경기 수원시 영통구 광교중앙로 140", closures:1, x:36, y:24, type:"q", open:true, badges:["coupon"],
    pros:[
      {id:"park", name:"박서연 프로", career:"KLPGA 세미 · 여성 전용", init:"박",
        tickets:[ {id:"park8", name:"박서연 프로 레슨권 8", desc:"주 1회 · 50분", count:"8회", validDays:60, price:320000} ]},
      {id:"lee", name:"이동우 프로", career:"USGTF 공인 · 아이언 전문", init:"이",
        tickets:[ {id:"lee12", name:"이동우 프로 정기 레슨권", desc:"주 2회 · 60분", count:"12회", validDays:60, price:520000} ]},
    ],
    training:[ {id:"fa90", name:"FA 무제한 90일권", desc:"기간 내 연습 무제한", count:"무제한", validDays:90, price:249000} ]},
  {id:3, name:"퀀텀 아카데미 정자점", addr:"경기 성남시 분당구 정자일로 248", closures:0, x:18, y:42, type:"fa", open:true, badges:[],
    pros:[ {id:"choi", name:"최민호 프로", career:"KPGA 2년 · 숏게임 전문", init:"최", tickets:[ {id:"choi8", name:"최민호 프로 레슨권 8", desc:"주 1회 · 50분", count:"8회", validDays:60, price:300000} ]} ],
    training:[ {id:"j-fa30", name:"FA 무제한 30일권", desc:"기간 내 연습 무제한", count:"무제한", validDays:30, price:99000} ]},
  {id:4, name:"퀀텀 아카데미 서현점", addr:"경기 성남시 분당구 황새울로 200", closures:1, x:74, y:22, type:"q", open:true, badges:["coupon"],
    pros:[ {id:"yoon", name:"윤서아 프로", career:"KLPGA 세미 · 드라이버 전문", init:"윤", tickets:[ {id:"yoon12", name:"윤서아 프로 정기 레슨권", desc:"주 2회 · 60분", count:"12회", validDays:90, price:500000} ]} ],
    training:[ {id:"s-t10", name:"트레이닝 10회권", desc:"회당 60분", count:"10회", validDays:90, price:60000} ]},
  {id:5, name:"퀀텀 아카데미 분당점", addr:"경기 성남시 분당구 정자동 100", closures:0, x:86, y:58, type:"fa", open:false, badges:["un"],
    pros:[],
    training:[ {id:"b-fa90", name:"FA 무제한 90일권", desc:"기간 내 연습 무제한", count:"무제한", validDays:90, price:249000} ]},
];

function TicketBuyFlow({ onClose, goHome, goTickets, initialType, initialStore, initialPro }){
  const [type, setType] = React.useState(initialType || null);
  const [store, setStore] = React.useState(initialStore || null);
  const [pro, setPro] = React.useState(initialPro || null);
  const [ticket, setTicket] = React.useState(null);
  const [startIdx, setStartIdx] = React.useState(null);
  const [pay, setPay] = React.useState("card");
  const [agreed, setAgreed] = React.useState(false);
  const [view, setView] = React.useState("map"); // 매장 보기: 지도/목록 (매장찾기와 통일)
  const [selIdx, setSelIdx] = React.useState(0); // 지도 선택 매장 인덱스
  const dragX = React.useRef(null);
  const [kindCat, setKindCat] = React.useState("all"); // 종류 필터칩
  // 프로 상세에서 진입하면 매장·프로가 이미 지정 → 매장 선택 생략, 종류부터
  const [step, setStep] = React.useState(initialStore ? "kind" : (initialType ? "store" : "type"));
  const typeColor = t => t==="fa"?"#16A34A" : t==="q"?"#1A1C1F" : t==="t2"?"#F59E0B" : "#3B82F6";

  const STEPS = []
    .concat(initialType ? [] : [["type","유형"]])
    .concat(initialStore ? [] : [["store","매장"]])
    .concat([["kind","종류"],["date","시작일"],["pay","결제"],["done","완료"]]);
  const idx = STEPS.findIndex(s=>s[0]===step);
  const stepper = <Stepper steps={STEPS.map(s=>s[1])} active={idx<0?0:idx}/>;
  const next = ()=> setStep(STEPS[Math.min(idx+1, STEPS.length-1)][0]);
  const prev = ()=> idx<=0 ? onClose() : setStep(STEPS[idx-1][0]);

  const won = n => n.toLocaleString("ko-KR")+"원";
  const today = new Date();
  const days = Array.from({length:14},(_,i)=>{ const d=new Date(today); d.setDate(today.getDate()+i); return d; });
  const WD = ["일","월","화","수","목","금","토"];
  const fmt = d => `${d.getMonth()+1}.${String(d.getDate()).padStart(2,"0")}`;
  const startDate = startIdx!=null ? days[startIdx] : null;
  const closures = store?.closures || 0;
  const baseExpiry = startDate && ticket ? (()=>{ const e=new Date(startDate); e.setDate(e.getDate()+ticket.validDays-1); return e; })() : null;
  const expiry = startDate && ticket ? (()=>{ const e=new Date(startDate); e.setDate(e.getDate()+ticket.validDays-1+closures); return e; })() : null;

  const proTickets = type==="lesson" ? (pro?.tickets || []) : (store?.training || []);

  return (
    <div className="screen">
      <StatusBar/>
      <Appbar title="이용권 구매" onBack={prev}
        right={<button className="icon-btn" onClick={onClose}><Icon name="x" size={18}/></button>}/>
      {step!=="done" && stepper}

      {/* 유형 */}
      {step==="type" && (
        <>
          <div className="scroll" style={{padding:"18px 20px 100px"}}>
            <div style={{fontSize:18,fontWeight:800,letterSpacing:"-.02em",marginBottom:18}}>어떤 이용권을 구매할까요?</div>
            <div style={{display:"flex",flexDirection:"column",gap:12}}>
              {[["lesson","레슨 이용권","담당 프로에게 받는 1:1 레슨"],["training","트레이닝 이용권","연습 · 아카데미 자율 연습"]].map(([id,t,d])=>(
                <button key={id} onClick={()=>{ setType(id); setPro(null); setTicket(null); setSelIdx(0); setStep("store"); }} style={{textAlign:"left",padding:18,borderRadius:12,background:"#fff",border:type===id?"1.5px solid var(--primary)":"1.5px solid var(--line)"}}>
                  <div style={{fontSize:16,fontWeight:800}}>{t}</div>
                  <div style={{fontSize:12.5,color:"var(--text-sub)",marginTop:4}}>{d}</div>
                </button>
              ))}
            </div>
          </div>
        </>
      )}

      {/* 매장 — 이용권 판매 매장만, 매장찾기와 동일한 지도/목록 (패닝 지도 + 스와이프 카드) */}
      {step==="store" && (()=>{
        const sellStores = BUY_STORES.filter(s => type==="lesson" ? s.pros.length>0 : s.training.length>0);
        const pick = s => { setStore(s); setPro(null); setTicket(null); setStep("kind"); };
        const sel = sellStores[selIdx] || sellStores[0];
        const goRel = d => setSelIdx(i => (i + d + sellStores.length) % sellStores.length);
        return (
          <div style={{flex:1,position:"relative",overflow:"hidden",background:"#fff"}}>
            {/* 지도/목록 토글 (아이콘 pill) + 판매 매장 수 */}
            <div style={{position:"absolute",top:12,left:12,right:12,zIndex:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8}}>
              <div style={{display:"flex",background:"#fff",borderRadius:999,boxShadow:"0 2px 8px rgba(0,0,0,.12)",overflow:"hidden",border:"1px solid var(--line)"}}>
                <button onClick={()=>setView("map")} style={{padding:"8px 12px",background:view==="map"?"var(--primary)":"#fff",color:view==="map"?"#fff":"var(--text-sub)",display:"flex"}}><Icon name="map" size={16}/></button>
                <button onClick={()=>setView("list")} style={{padding:"8px 12px",background:view==="list"?"var(--primary)":"#fff",color:view==="list"?"#fff":"var(--text-sub)",display:"flex"}}><Icon name="list" size={16}/></button>
              </div>
              <span style={{fontSize:11.5,fontWeight:700,color:"var(--text-sub)",background:"rgba(255,255,255,.92)",padding:"6px 11px",borderRadius:999,boxShadow:"0 2px 8px rgba(0,0,0,.08)"}}>이용권 판매 {sellStores.length}곳</span>
            </div>

            {view==="map" ? (
              <>
                <div style={{position:"absolute",inset:0,overflow:"hidden"}}>
                  <div style={{position:"absolute",inset:0,transform:`translate(${sel?50-sel.x:0}%, ${sel?52-sel.y:0}%)`,transition:"transform .45s cubic-bezier(.2,.8,.2,1)"}}>
                    <div className="map-bg" style={{position:"absolute",inset:"-70%"}}>
                      <div style={{position:"absolute",top:"40%",left:0,right:0,height:6,background:"#FECACA",opacity:.6,transform:"rotate(-4deg)"}}/>
                      <div style={{position:"absolute",top:"30%",left:"36%",right:"34%",bottom:"30%",background:"rgba(134,239,172,.25)",borderRadius:40}}/>
                    </div>
                    {sellStores.map((s,i)=>{ const on=selIdx===i; return (
                      <button key={s.id} onClick={()=>setSelIdx(i)} style={{position:"absolute",left:`${s.x}%`,top:`${s.y}%`,transform:"translate(-50%,-100%)",background:"none",zIndex:on?5:1}}>
                        <div className="pin" style={{background:typeColor(s.type),transform:on?"scale(1.25)":"scale(1)",transition:"transform .2s",boxShadow:on?"0 6px 14px rgba(0,0,0,.3)":"0 4px 10px rgba(34,187,95,.3)"}}><span style={{fontSize:10,fontWeight:800}}>{(s.type||"q").toUpperCase()}</span></div>
                      </button>
                    );})}
                    <div style={{position:"absolute",left:"50%",top:"52%",transform:"translate(-50%,-50%)"}}><div style={{width:20,height:20,borderRadius:"50%",background:"rgba(239,68,68,.25)",display:"flex",alignItems:"center",justifyContent:"center"}}><div style={{width:10,height:10,borderRadius:"50%",background:"#EF4444",border:"2px solid #fff"}}/></div></div>
                  </div>
                </div>

                {sel && (
                  <div onPointerDown={e=>{dragX.current=e.clientX;}} onPointerUp={e=>{ if(dragX.current==null)return; const dx=e.clientX-dragX.current; dragX.current=null; if(Math.abs(dx)>40) goRel(dx<0?1:-1); }}
                    style={{position:"absolute",left:12,right:12,bottom:12,background:"#fff",borderRadius:14,padding:"14px 16px 10px",boxShadow:"0 6px 20px rgba(0,0,0,.14)",zIndex:30,touchAction:"pan-y",userSelect:"none"}}>
                    <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:6}}>
                      <div style={{fontSize:15,fontWeight:800,letterSpacing:"-.01em"}}>{sel.name}</div>
                      {(sel.badges||[]).includes("un") && <span className="store-badge sb-un">무인</span>}
                      {(sel.badges||[]).includes("coupon") && <span className="store-badge sb-coupon">쿠폰</span>}
                    </div>
                    <div style={{fontSize:12.5,display:"flex",alignItems:"center",gap:6,marginBottom:8}}>
                      <span style={{color:sel.open?"var(--primary)":"var(--text-mute)",fontWeight:700}}>{sel.open?"영업중":"영업종료"}</span>
                      <span style={{color:"var(--text-mute)"}}>·</span>
                      <span style={{color:"var(--text-sub)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{sel.addr}</span>
                    </div>
                    <div style={{fontSize:12,color:"var(--text-mute)",marginBottom:10}}>{type==="lesson" ? `레슨 프로 ${sel.pros.length}명` : `트레이닝 이용권 ${sel.training.length}종`}</div>
                    <button className="btn btn-primary" style={{width:"100%",height:46,fontSize:14}} onClick={()=>pick(sel)}>이 매장 선택</button>
                    <div className="pager" style={{justifyContent:"center",paddingTop:12}}>
                      {sellStores.map((_,i)=><i key={i} className={selIdx===i?"on":""} style={selIdx===i?{background:"var(--primary)"}:{background:"var(--line-strong)"}}/>)}
                    </div>
                  </div>
                )}
              </>
            ) : (
              <div className="scroll" style={{position:"absolute",inset:0,paddingTop:60,background:"#fff"}}>
                {sellStores.map((s,i)=>(
                  <button key={s.id} onClick={()=>pick(s)} style={{display:"block",width:"100%",textAlign:"left",padding:"16px 20px",borderBottom:"1px solid var(--line)",background:"transparent"}}>
                    <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:5}}>
                      <div style={{fontSize:15,fontWeight:800}}>{s.name}</div>
                      {(s.badges||[]).includes("coupon") && <span className="store-badge sb-coupon">쿠폰</span>}
                    </div>
                    <div style={{fontSize:12,color:"var(--text-sub)"}}><span style={{color:s.open?"var(--primary)":"var(--text-mute)",fontWeight:700}}>{s.open?"영업중":"영업종료"}</span><span className="sdot"/>{s.addr}</div>
                    <div style={{fontSize:11.5,color:"var(--text-mute)",marginTop:6}}>{type==="lesson" ? `레슨 프로 ${s.pros.length}명` : `트레이닝 이용권 ${s.training.length}종`}</div>
                  </button>
                ))}
              </div>
            )}
          </div>
        );
      })()}

      {/* 종류 / 프로 */}
      {step==="kind" && (
        <>
          <div className="scroll" style={{padding:"16px 20px 100px"}}>
            {type==="lesson" && (store?.pros || (pro?[pro]:[])).length>0 && (
              <>
                <div style={{fontSize:14,fontWeight:800,marginBottom:10}}>담당 프로</div>
                <div style={{display:"flex",gap:8,overflowX:"auto",scrollbarWidth:"none",marginBottom:18}}>
                  {(store?.pros || (pro?[pro]:[])).map(p=>(
                    <button key={p.id} onClick={()=>{ setPro(p); setTicket(null); }} style={{flexShrink:0,display:"flex",alignItems:"center",gap:8,padding:"10px 12px",borderRadius:12,background:pro?.id===p.id?"var(--primary-tint)":"#fff",border:pro?.id===p.id?"1.5px solid var(--primary)":"1px solid var(--line)"}}>
                      <span className="avatar" style={{width:32,height:32,fontSize:13}}>{p.init}</span>
                      <span style={{textAlign:"left"}}><span style={{display:"block",fontSize:13,fontWeight:700}}>{p.name}</span><span style={{display:"block",fontSize:10.5,color:"var(--text-sub)"}}>{p.career}</span></span>
                    </button>
                  ))}
                </div>
              </>
            )}
            <div style={{fontSize:14,fontWeight:800,marginBottom:10}}>{type==="lesson" ? "레슨권 종류" : "트레이닝 이용권"}</div>
            <TicketCatChips cat={kindCat} setCat={setKindCat}/>
            {type==="lesson" && !pro ? (
              <div style={{padding:"30px 0",textAlign:"center",fontSize:13,color:"var(--text-mute)"}}>담당 프로를 먼저 선택해주세요.</div>
            ) : (
              <div style={{display:"flex",flexDirection:"column",gap:10}}>
                {proTickets.filter(t => kindCat==="all" || ticketCat(t)===kindCat).map(t=>(
                  <button key={t.id} onClick={()=>setTicket(t)} style={{textAlign:"left",padding:16,borderRadius:12,background:"#fff",border:ticket?.id===t.id?"1.5px solid var(--primary)":"1.5px solid var(--line)"}}>
                    <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:5}}>
                      <span style={{fontSize:15,fontWeight:800}}>{t.name}</span>
                      {t.tag && <span className="chip" style={{background:"var(--primary-tint)",color:"var(--primary)",fontSize:10,fontWeight:700,padding:"2px 8px"}}>{t.tag}</span>}
                    </div>
                    <div style={{fontSize:12,color:"var(--text-sub)"}}>{t.desc} · {t.count} · 사용 가능 {t.validDays}일</div>
                    <div style={{fontSize:17,fontWeight:800,marginTop:8,color:ticket?.id===t.id?"var(--primary)":"var(--text)"}}>{won(t.price)}</div>
                  </button>
                ))}
                {proTickets.filter(t => kindCat==="all" || ticketCat(t)===kindCat).length===0 && (
                  <div style={{padding:"24px 0",textAlign:"center",fontSize:13,color:"var(--text-mute)"}}>해당 유형의 이용권이 없어요.</div>
                )}
              </div>
            )}
          </div>
          <div className="footer-bar">
            <button className={"btn " + (ticket?"btn-primary":"btn-disabled")} onClick={()=>ticket&&next()}>다음</button>
          </div>
        </>
      )}

      {/* 시작일 */}
      {step==="date" && (
        <>
          <div className="scroll" style={{padding:"16px 20px 100px"}}>
            <div style={{fontSize:18,fontWeight:800,letterSpacing:"-.02em",marginBottom:6}}>시작일을 선택해주세요.</div>
            <div style={{fontSize:12.5,color:"var(--text-sub)",marginBottom:16}}>선택한 날부터 이용권 사용 기간이 시작돼요.</div>
            <div style={{display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:6}}>
              {days.map((d,i)=>{
                const on=startIdx===i, dow=d.getDay();
                return (
                  <button key={i} onClick={()=>setStartIdx(i)} style={{padding:"10px 0",borderRadius:10,border:on?"1.5px solid var(--primary)":"1px solid var(--line)",background:on?"var(--primary-tint)":"#fff"}}>
                    <div style={{fontSize:10,color:dow===0?"#EF4444":dow===6?"#3B82F6":"var(--text-mute)"}}>{WD[dow]}</div>
                    <div style={{fontSize:14,fontWeight:on?800:600,color:on?"var(--primary)":"var(--text)",marginTop:2}}>{d.getDate()}</div>
                  </button>
                );
              })}
            </div>

            {startDate && (
              <div className="card" style={{marginTop:20,padding:16}}>
                <div style={{display:"flex",justifyContent:"space-between",padding:"4px 0",fontSize:13}}>
                  <span style={{color:"var(--text-sub)"}}>사용 시작일</span><span style={{fontWeight:700}}>{fmt(startDate)} ({WD[startDate.getDay()]})</span>
                </div>
                <div style={{display:"flex",justifyContent:"space-between",padding:"4px 0",fontSize:13}}>
                  <span style={{color:"var(--text-sub)"}}>기본 사용 기간</span><span style={{fontWeight:700}}>{ticket.validDays}일</span>
                </div>
                {closures>0 && (
                  <div style={{display:"flex",justifyContent:"space-between",padding:"4px 0",fontSize:13}}>
                    <span style={{color:"var(--text-sub)"}}>휴업일 자동 연장</span><span style={{fontWeight:700,color:"var(--primary)"}}>+{closures}일</span>
                  </div>
                )}
                <div style={{height:1,background:"var(--line)",margin:"8px 0"}}/>
                <div style={{display:"flex",justifyContent:"space-between",padding:"2px 0",fontSize:14}}>
                  <span style={{fontWeight:700}}>사용 만료일</span><span style={{fontWeight:800,color:"var(--primary)"}}>{fmt(expiry)} ({WD[expiry.getDay()]})</span>
                </div>
                {closures>0 && <div style={{fontSize:11,color:"var(--text-mute)",marginTop:8,lineHeight:1.5}}>· 매장 휴업일 {closures}일이 사용 기간에 포함되어 만료일이 자동 연장되었어요.</div>}
              </div>
            )}
          </div>
          <div className="footer-bar">
            <button className={"btn " + (startDate?"btn-primary":"btn-disabled")} onClick={()=>startDate&&next()}>다음</button>
          </div>
        </>
      )}

      {/* 결제 */}
      {step==="pay" && (
        <>
          <div className="scroll" style={{padding:"16px 20px 120px"}}>
            <div className="h3" style={{fontSize:15,marginBottom:8}}>구매 정보</div>
            <div className="card" style={{padding:"4px 16px"}}>
              {[["이용권", ticket.name], type==="lesson"?["담당 프로", pro.name]:null, ["매장", store.name],
                ["사용 기간", `${fmt(startDate)} ~ ${fmt(expiry)}`], ["수량", ticket.count]].filter(Boolean).map((r,i,a)=>(
                <div key={i} style={{display:"flex",justifyContent:"space-between",padding:"12px 0",fontSize:13.5,borderBottom:i<a.length-1?"1px solid var(--line)":"0"}}>
                  <span style={{color:"var(--text-sub)"}}>{r[0]}</span><span style={{fontWeight:700,textAlign:"right",maxWidth:"60%"}}>{r[1]}</span>
                </div>
              ))}
            </div>

            <div className="h3" style={{fontSize:15,margin:"22px 0 8px"}}>결제 수단</div>
            <div style={{display:"flex",flexDirection:"column",gap:8}}>
              {[["card","신용·체크카드","신한카드 ···· 4821"],["kakaopay","카카오페이","간편결제"]].map(([id,t,s])=>(
                <button key={id} onClick={()=>setPay(id)} style={{display:"flex",alignItems:"center",gap:10,padding:"14px 16px",borderRadius:10,background:"#fff",border:pay===id?"1.5px solid var(--primary)":"1px solid var(--line)",textAlign:"left"}}>
                  <span style={{width:18,height:18,borderRadius:"50%",border:pay===id?"5px solid var(--primary)":"2px solid var(--line-strong)"}}/>
                  <span style={{flex:1}}><span style={{display:"block",fontSize:14,fontWeight:700}}>{t}</span><span style={{display:"block",fontSize:11.5,color:"var(--text-sub)"}}>{s}</span></span>
                </button>
              ))}
            </div>

            <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",margin:"22px 0 14px"}}>
              <span style={{fontSize:15,fontWeight:800}}>총 결제 금액</span>
              <span style={{fontSize:22,fontWeight:800,color:"var(--primary)",letterSpacing:"-.02em"}}>{won(ticket.price)}</span>
            </div>

            <button onClick={()=>setAgreed(a=>!a)} style={{display:"flex",alignItems:"center",gap:8,width:"100%",textAlign:"left",background:"transparent",padding:"4px 0"}}>
              <span style={{width:20,height:20,borderRadius:6,background:agreed?"var(--primary)":"#fff",border:agreed?"none":"1.5px solid var(--line-strong)",display:"flex",alignItems:"center",justifyContent:"center"}}>{agreed && <Icon name="check" size={13} stroke={3} style={{color:"#fff"}}/>}</span>
              <span style={{fontSize:12.5,color:"var(--text-sub)"}}>[필수] 이용권 구매 및 취소·환불 규정에 동의합니다.</span>
            </button>
          </div>
          <div className="footer-bar">
            <button className={"btn " + (agreed?"btn-primary":"btn-disabled")} onClick={()=>{ if(!agreed) return; addOwnedTicket({ id:"own-"+Date.now(), type, kind: type==="lesson"?"정기이용권":"트레이닝권", name:ticket.name, store:store.name, remainText:`${ticket.count} 남음`, progress:null, pro: type==="lesson"?{name:pro.name,init:pro.init,career:pro.career}:null, price:won(ticket.price), meta:[["이용 시작일",fmt(startDate)],["사용 기간",`${fmt(startDate)} ~ ${fmt(expiry)}`]] }); setStep("done"); }}>{won(ticket.price)} 결제하기</button>
          </div>
        </>
      )}

      {/* 완료 */}
      {step==="done" && (
        <>
          <div className="scroll" style={{padding:"40px 20px 24px",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center"}}>
            <div style={{width:64,height:64,borderRadius:"50%",background:"var(--primary)",display:"flex",alignItems:"center",justifyContent:"center",marginBottom:18}}><Icon name="check" size={30} stroke={3} style={{color:"#fff"}}/></div>
            <div style={{fontSize:19,fontWeight:800,letterSpacing:"-.02em"}}>이용권 구매가 완료됐어요!</div>
            <div style={{fontSize:13,color:"var(--text-sub)",marginTop:8,lineHeight:1.5}}>{ticket.name}<br/>{fmt(startDate)} ~ {fmt(expiry)} 사용 가능</div>
            <div className="card" style={{marginTop:22,padding:16,width:"100%",textAlign:"left"}}>
              {[["이용권", ticket.name], ["매장", store.name], ["사용 기간", `${fmt(startDate)} ~ ${fmt(expiry)}`], ["결제 금액", won(ticket.price)]].map((r,i,a)=>(
                <div key={i} style={{display:"flex",justifyContent:"space-between",padding:"10px 0",fontSize:13,borderBottom:i<a.length-1?"1px solid var(--line)":"0"}}>
                  <span style={{color:"var(--text-sub)"}}>{r[0]}</span><span style={{fontWeight:700,textAlign:"right",maxWidth:"60%"}}>{r[1]}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="footer-bar" style={{display:"flex",gap:10}}>
            <button className="btn btn-outline" style={{flex:1}} onClick={goHome}>홈으로</button>
            <button className="btn btn-primary" style={{flex:2}} onClick={goTickets}>내 이용권 보기</button>
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, { LessonTickets, TicketBuyFlow });
