/* ===== Panex — Result dashboard ===== */

function ScoreRing({ value, size=126 }){
  const r=(size-16)/2, c=2*Math.PI*r, off=c*(1-value/100);
  return (
    <div style={{position:"relative",width:size,height:size}}>
      <svg width={size} height={size} style={{transform:"rotate(-90deg)"}}>
        <defs><linearGradient id="ring" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#7E6CF2"/><stop offset="100%" stopColor="#3D5AFE"/></linearGradient></defs>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="#ECEBFB" strokeWidth="9"/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="url(#ring)" strokeWidth="9" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={c} style={{animation:`ringdraw 1.3s var(--ease) .2s forwards`}}/>
        <style>{`@keyframes ringdraw{to{stroke-dashoffset:${off}}}`}</style>
      </svg>
      <div style={{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"}}>
        <div style={{fontSize:40,fontWeight:800,letterSpacing:"-.04em",lineHeight:1,background:"var(--grad-head)",WebkitBackgroundClip:"text",backgroundClip:"text",WebkitTextFillColor:"transparent"}}>{value}</div>
        <div style={{fontSize:12,color:"var(--ink-3)",fontWeight:700,marginTop:2}}>/ 100점</div>
      </div>
    </div>
  );
}

function Section({ title, sub, right, children, style }){
  return (
    <div className="rs-sec" style={style}>
      <div className="rs-sec-head">
        <div><h3>{title}</h3>{sub && <span>{sub}</span>}</div>
        {right}
      </div>
      {children}
    </div>
  );
}

const MARK = {
  good:{c:"var(--good)",s:"var(--good-soft)",g:"♥",l:"잘한 말"},
  warn:{c:"var(--warn)",s:"var(--warn-soft)",g:"!",l:"아쉬워요"},
  bad:{c:"var(--bad)",s:"var(--bad-soft)",g:"✕",l:"위험"},
};

function Result({ data, onBack, onRestart, toast }){
  const D = data;
  const [openReplay, setOpenReplay] = useState(false);
  const [tone, setTone] = useState(0);
  const [genKey, setGenKey] = useState(0);
  const grade = D.scores.mine>=80?"잘했어요":D.scores.mine>=65?"나쁘지 않아요":D.scores.mine>=50?"아슬아슬했어요":"복기가 필요해요";
  const heroNote = D.scores.mine>=80 ? "막판까지 분위기를 잘 끌고 갔어요."
    : D.scores.mine>=65 ? "초반 흐름은 좋았는데, 중반 이후가 아쉬웠어요."
    : D.scores.mine>=50 ? "기회는 있었는데 몇 번 놓쳤어요."
    : "전체적으로 다시 짚어볼 부분이 많아요.";
  const maxTemp = Math.max(...D.temperature);
  const peakMoment = D.highlights.find(h=>h.type==="good");
  const dipMoment = D.highlights.find(h=>h.type==="bad") || D.highlights.find(h=>h.type==="warn");
  const tempNote = peakMoment && dipMoment
    ? `${peakMoment.time}쯤 "${peakMoment.label}"로 분위기가 살아났고, ${dipMoment.time}쯤 "${dipMoment.label}"로 식었어요.`
    : "그래프에서 대화 분위기 변화를 확인해보세요.";

  return (
    <div className="screen result" style={{animation:"fadeIn .3s"}}>
      <AppHeader title="분석 결과" onBack={onBack}
        right={<button className="app-iconbtn" onClick={()=>toast("공유 링크가 복사됐어요")}><Icon name="share" size={19} color="#0E1626"/></button>}/>
      <div className="screen-body noscroll">

        {/* SCORE HERO */}
        <div className="score-hero" style={{animation:"rise .5s both"}}>
          <ScoreRing value={D.scores.mine}/>
          <div className="score-meta">
            <span className="score-grade">{grade}</span>
            <h2>이번 대화, <br/>{D.scores.mine}점이에요</h2>
            <p>{heroNote}</p>
          </div>
        </div>

        {/* STAT GRID */}
        <div className="stat-grid" style={{animation:"rise .5s .05s both"}}>
          <StatCard big icon="star"  color="var(--star)" soft="var(--star-soft)" label="내 대화 점수" value={D.scores.mine} unit="/100"/>
          <StatCard big icon="smile" color="var(--good)" soft="var(--good-soft)" label="상대 반응" value={D.scores.reaction} unit="/100"/>
          <StatCard big icon="frown" color="var(--warn)" soft="var(--warn-soft)" label="기회 날린 수" value={D.scores.missed} unit="회"/>
          <StatCard big icon="bolt"  color="var(--bad)"  soft="var(--bad-soft)"  label="분위기 깬 발언" value={D.scores.moodkill} unit="회"/>
        </div>

        {/* TEMPERATURE */}
        <Section title="대화 온도 흐름" sub="초반 → 후반" style={{animation:"rise .5s .1s both"}}
          right={<span className="info-pill"><Icon name="thermo" size={13} color="#6C5DD8"/>최고 {maxTemp}°</span>}>
          <div className="card temp-card">
            <TempGraph data={D.temperature} w={360} h={150}/>
            <div className="temp-x"><span>초반</span><span>중반</span><span>후반</span></div>
            <div className="temp-note"><Icon name="info" size={13} color="#B7BACB"/>{tempNote}</div>
          </div>
        </Section>

        {/* PATTERNS */}
        <Section title="대화 습관" sub="이번 대화에서 드러난 패턴" style={{animation:"rise .5s .12s both"}}>
          <div className="pat-grid">
            {D.patterns.map((p,i)=>(
              <div key={i} className="pat-card">
                <div className="pat-top"><span>{p.label}</span><span className={`pat-flag ${p.tone}`}>{p.tone==="good"?"좋아요":"주의"}</span></div>
                <div className="pat-val">{p.value}</div>
                <div className="pat-hint">{p.hint}</div>
              </div>
            ))}
          </div>
        </Section>

        {/* HIGHLIGHTS */}
        <Section title="주요 순간 하이라이트" sub="여기서 흐름이 바뀌었어요" style={{animation:"rise .5s .14s both"}}>
          <div className="hl-list">
            {D.highlights.map((h,i)=>{const m=MARK[h.type];return(
              <div key={i} className="hl-item card">
                <span className="hl-badge" style={{background:m.s,color:m.c}}>{m.g}</span>
                <div className="hl-body">
                  <div className="hl-row"><b style={{color:m.c}}>{h.label}</b><span className="hl-time">{h.time}</span></div>
                  <div className="hl-quote">"{h.text}"</div>
                  <div className="hl-note">{h.note}</div>
                </div>
              </div>
            );})}
          </div>
        </Section>

        {/* REPLAY */}
        <Section title="대화 복기" sub="순간별로 다시 돌려보기" style={{animation:"rise .5s .16s both"}}
          right={<button className="link-btn" onClick={()=>setOpenReplay(o=>!o)}>{openReplay?"접기":"펼치기"}<Icon name={openReplay?"chevD":"chevR"} size={15} color="#6C5DD8"/></button>}>
          {openReplay && (
            <div className="card replay" style={{animation:"rise .35s both"}}>
              {D.replay.map((r,i)=>{const m=r.mark&&MARK[r.mark];return(
                <div key={i} className={`bub-row ${r.me?"me":"you"}`}>
                  <div className="bub-wrap">
                    <div className={`bubble ${r.me?"me":"you"} ${r.mark?"marked "+r.mark:""}`}>
                      {r.text}
                      {m && <span className="bub-tag" style={{background:m.s,color:m.c}}>{m.g} {m.l}</span>}
                    </div>
                    {r.note && <div className="bub-note">{r.note}</div>}
                    <div className="bub-time">{r.time}</div>
                  </div>
                </div>
              );})}
            </div>
          )}
        </Section>

        {/* VERDICT */}
        <div className="verdict-card" style={{animation:"rise .5s .18s both"}}>
          <div className="vc-text"><b>총평</b><p>{D.verdict}</p></div>
          <Mascot size={68} mood="think" style={{flex:"0 0 auto"}}/>
        </div>

        {/* SUGGESTION */}
        <Section title="추천 다음 메시지" sub="지금 보내기 딱 좋은 한 줄" style={{animation:"rise .5s .2s both"}}>
          <div className="sg-tones">
            {D.suggestions.map((s,i)=>(
              <button key={i} className={`sg-tone ${tone===i?"on":""}`} onClick={()=>{setTone(i);setGenKey(k=>k+1)}}>{s.tone}</button>
            ))}
          </div>
          <div className="sg-box card" key={genKey} style={{animation:"rise .3s both"}}>
            <Icon name="sparkle" size={16} color="#6C5DD8" style={{flex:"0 0 auto",marginTop:2}}/>
            <p>{D.suggestions[tone].text}</p>
          </div>
          <div className="sg-actions">
            <button className="btn btn-soft btn-md" style={{flex:1}} onClick={()=>{setGenKey(k=>k+1);toast("새로 생성했어요 ✨")}}>
              <Icon name="refresh" size={17} color="var(--primary-700)"/> 다시 생성
            </button>
            <button className="btn btn-primary btn-md" style={{flex:1.4}} onClick={()=>toast("메시지를 복사했어요")}>
              <Icon name="copy" size={17} color="#fff"/> 복사하기
            </button>
          </div>
        </Section>

        {/* bottom actions */}
        <div className="result-foot">
          <button className="btn btn-ghost btn-md" onClick={onRestart}><Icon name="upload" size={17} color="#0E1626"/> 다른 대화 분석</button>
          <button className="btn btn-ghost btn-md" onClick={()=>toast("리포트를 저장했어요")}><Icon name="bookmark" size={17} color="#0E1626"/> 저장</button>
        </div>
        <div className="result-end">분석한 대화는 이 화면을 닫으면 삭제돼요 · 리뷰썸</div>
      </div>
    </div>
  );
}

Object.assign(window, { Result });
