// screens/analysis.jsx — AI 진단 결과 (항목별 점수 + radar)

function AnalysisScreen({ persona, setRoute }) {
  const Icons = window.Icons;
  const [overlay, setOverlay] = React.useState("pores");
  const [showBaseline, setShowBaseline] = React.useState(true);

  const overlayOpts = [
    { v: "pores",   l: "모공" },
    { v: "sebum",   l: "유분/피지광" },
    { v: "redness", l: "홍조" },
    { v: "pigment", l: "색소" },
    { v: "wrinkle", l: "주름/탄력" },
  ];

  const scores = persona.skinScores;
  const overall = Math.round(Object.values(scores).reduce((a, b) => a + b, 0) / Object.keys(scores).length);
  const baselineAvg = Math.round(Object.values(BASELINE_SCORES).reduce((a, b) => a + b, 0) / Object.keys(BASELINE_SCORES).length);

  const sortedKeys = [...SCORE_KEYS].sort((a, b) => scores[a] - scores[b]); // worst → best
  const worst3 = sortedKeys.slice(0, 3);
  const best3 = sortedKeys.slice(-3).reverse();

  const TIME_STEPS = [
    { l: "이미지 수집", t: "5장 · 12MB", done: true },
    { l: "Region 분할", t: "8 영역", done: true },
    { l: "지표 추출", t: "47 features", done: true },
    { l: "점수화", t: "10 dimensions", done: true },
    { l: "Cohort 매칭", t: "유사 환자 142", done: true },
  ];

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">03 · AI 진단 결과</div>
          <h1 className="page-title">피부 정량 분석 — <span className="num" style={{ color: "var(--ink-2)" }}>{overall}</span> / 100</h1>
          <p className="page-sub">
            10개 지표의 정량 분석 결과입니다. 막대 위 검은 마커는 동일 연령대 일반 기준 점수이며, 표준화된 cohort {persona.id === "P-2026-0489" ? "286" : "142"}명 데이터와 매칭되었습니다.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-soft btn-sm" onClick={() => setRoute("capture")}><Icons.Rotate size={13} /> 재촬영</button>
          <button className="btn btn-soft btn-sm" onClick={() => setRoute("report")}><Icons.Doc size={13} /> 세부 리포트</button>
          <button className="btn btn-primary" onClick={() => setRoute("recommend")}>
            시술 추천 <Icons.Arrow size={14} />
          </button>
        </div>
      </div>

      {/* Pipeline timeline */}
      <Card pad="sm" style={{ marginBottom: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
          <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-4)", letterSpacing: "0.05em", marginRight: 12 }}>AI PIPELINE</span>
          {TIME_STEPS.map((s, i) => (
            <React.Fragment key={i}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{
                  width: 18, height: 18, borderRadius: "50%",
                  background: "var(--ink-1)", color: "#FFF",
                  display: "grid", placeItems: "center",
                }}>
                  <Icons.Check size={10} sw={3} stroke="#FFF" />
                </span>
                <div>
                  <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--ink-1)" }}>{s.l}</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{s.t}</div>
                </div>
              </div>
              {i < TIME_STEPS.length - 1 && <div style={{ flex: 1, height: 1, background: "var(--ink-1)", margin: "0 6px" }} />}
            </React.Fragment>
          ))}
          <div style={{ marginLeft: 16, display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ fontSize: 11, color: "var(--ink-3)" }}>소요</span>
            <span className="num" style={{ fontWeight: 600, color: "var(--ink-1)" }}>2.4s</span>
          </div>
        </div>
      </Card>

      <div className="grid grid-12">
        {/* LEFT — Face + heatmap */}
        <div className="col-5">
          <Card pad="md">
            <div className="card-title-row">
              <h3 className="card-title"><span className="dot"></span>히트맵 — 영역별 분포</h3>
              <Tabs tabs={overlayOpts} value={overlay} onChange={setOverlay} />
            </div>
            <div style={{ position: "relative", aspectRatio: "4/5", borderRadius: 14, overflow: "hidden", background: "#0F0F11" }}>
              <div className="skin-photo" style={{ position: "absolute", inset: 0, borderRadius: 14 }} />
              <HeatmapOverlay kind={overlay} />
              {/* Annotations */}
              <svg viewBox="0 0 100 100" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
                {overlay === "pores" && (
                  <>
                    <line x1="50" y1="52" x2="78" y2="32" stroke="rgba(255,255,255,0.7)" strokeWidth="0.3" />
                    <circle cx="78" cy="32" r="1" fill="#FFF" />
                  </>
                )}
              </svg>
              <div style={{ position: "absolute", top: 14, left: 14, background: "rgba(0,0,0,0.6)", color: "#FFF", padding: "6px 10px", borderRadius: 8, fontSize: 11 }}>
                <div className="mono" style={{ opacity: 0.7, fontSize: 9, letterSpacing: "0.06em" }}>OVERLAY</div>
                <div style={{ fontWeight: 600, fontSize: 12 }}>{overlayOpts.find(o => o.v === overlay).l}</div>
              </div>
              {/* Heatmap legend */}
              <div style={{ position: "absolute", bottom: 14, left: 14, right: 14, display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 10, color: "rgba(255,255,255,0.8)" }} className="mono">LOW</span>
                <div style={{ flex: 1, height: 6, borderRadius: 999, background: "linear-gradient(90deg, rgba(50,150,255,0.7), rgba(255,200,60,0.8), rgba(255,80,60,0.85))" }}></div>
                <span style={{ fontSize: 10, color: "rgba(255,255,255,0.8)" }} className="mono">HIGH</span>
              </div>
            </div>
          </Card>

          {/* Region cards */}
          <div className="grid grid-2" style={{ marginTop: 14 }}>
            <Card pad="sm">
              <div className="stat-label">최우선 개선 영역</div>
              <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 6 }}>
                {worst3.map((k, i) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontSize: 13, fontWeight: 500 }}>
                      <span className="num" style={{ color: "var(--ink-4)", marginRight: 6 }}>{String(i+1).padStart(2,"0")}</span>
                      {k}
                    </span>
                    <Pill tone={scores[k] < 65 ? "alert" : "watch"}>{scores[k]}점</Pill>
                  </div>
                ))}
              </div>
            </Card>
            <Card pad="sm">
              <div className="stat-label">우수 영역</div>
              <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 6 }}>
                {best3.map((k, i) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontSize: 13, fontWeight: 500 }}>
                      <span className="num" style={{ color: "var(--ink-4)", marginRight: 6 }}>{String(i+1).padStart(2,"0")}</span>
                      {k}
                    </span>
                    <Pill tone="good">{scores[k]}점</Pill>
                  </div>
                ))}
              </div>
            </Card>
          </div>
        </div>

        {/* CENTER — Score chart */}
        <div className="col-4">
          <Card pad="lg" style={{ height: "100%" }}>
            <div className="card-title-row">
              <h3 className="card-title"><span className="dot"></span>10대 지표 점수 (100점 만점)</h3>
              <button className={`pill ${showBaseline ? "pill-info" : "pill-outline"}`} onClick={() => setShowBaseline(!showBaseline)}>
                <span className="dot"></span>일반 기준 표시
              </button>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
              {SCORE_KEYS.map((k, i) => {
                const v = scores[k];
                const tone = v >= 80 ? "good" : v >= 65 ? "watch" : "alert";
                return (
                  <div key={k} className="fade-up" style={{ animationDelay: `${i * 40}ms` }}>
                    <ScoreBar label={k} value={v} base={showBaseline ? BASELINE_SCORES[k] : null} tone={tone} />
                  </div>
                );
              })}
            </div>
            <div className="divider" />
            <div style={{ display: "flex", gap: 16, fontSize: 11.5, color: "var(--ink-3)" }}>
              <span><span style={{ display: "inline-block", width: 18, height: 3, background: "var(--good)", borderRadius: 2, verticalAlign: "middle", marginRight: 4 }}></span> 80+ 양호</span>
              <span><span style={{ display: "inline-block", width: 18, height: 3, background: "var(--watch)", borderRadius: 2, verticalAlign: "middle", marginRight: 4 }}></span> 65-79</span>
              <span><span style={{ display: "inline-block", width: 18, height: 3, background: "var(--alert)", borderRadius: 2, verticalAlign: "middle", marginRight: 4 }}></span> &lt;65 주의</span>
              <span><span style={{ display: "inline-block", width: 2, height: 12, background: "var(--ink-2)", verticalAlign: "middle", marginRight: 4 }}></span> 일반 기준</span>
            </div>
          </Card>
        </div>

        {/* RIGHT — Radar + Overall */}
        <div className="col-3" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Card pad="lg" style={{ textAlign: "center" }}>
            <div className="stat-label" style={{ marginBottom: 14 }}>종합 피부 점수</div>
            <div style={{ display: "grid", placeItems: "center", margin: "0 auto" }}>
              <Donut value={overall} max={100} size={160} stroke={14}
                     color="var(--phase-tint)" label="OVERALL" subtitle={`vs. 일반 ${baselineAvg}`} />
            </div>
            <div style={{ marginTop: 16, display: "flex", justifyContent: "space-around" }}>
              <div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600 }}>{persona.skinAge}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>피부 나이</div>
              </div>
              <div style={{ width: 1, background: "var(--line-hair)" }}></div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, color: "var(--data-blue)" }}>{persona.skinType}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>피부 타입</div>
              </div>
            </div>
          </Card>

          <Card pad="md">
            <div className="stat-label" style={{ marginBottom: 6 }}>Top Concern</div>
            <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ink-1)", letterSpacing: "-0.01em" }}>{persona.topConcern}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>
              {persona.secondaryConcerns.join(" · ")}
            </div>
          </Card>

          <Card pad="md" style={{ flex: 1, minHeight: 0 }}>
            <div className="card-title-row">
              <h3 className="card-title"><span className="dot"></span>Radar</h3>
            </div>
            <div style={{ display: "grid", placeItems: "center" }}>
              <Radar axes={SCORE_KEYS} values={SCORE_KEYS.map(k => scores[k])} baseline={SCORE_KEYS.map(k => BASELINE_SCORES[k])} size={240} color="var(--phase-tint)" />
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

window.AnalysisScreen = AnalysisScreen;
