// screens/capture.jsx — 피부 촬영 가이드 (3~5장)

function CaptureScreen({ persona, setRoute }) {
  const Icons = window.Icons;
  const SHOTS = [
    { id: "front", label: "정면", angle: "0°", note: "양쪽 광대 동등하게", required: true, done: true },
    { id: "left45", label: "좌측 45°", angle: "-45°", note: "왼쪽 광대·턱선", required: true, done: true },
    { id: "right45", label: "우측 45°", angle: "+45°", note: "오른쪽 광대·턱선", required: true, done: true },
    { id: "left90", label: "좌측 측면", angle: "-90°", note: "헤어라인·귀앞", required: false, done: false, current: true },
    { id: "up", label: "턱 아래 (선택)", angle: "Tilt +15°", note: "코끝 모공", required: false, done: false },
  ];
  const [current, setCurrent] = React.useState(3);
  const doneCount = SHOTS.filter(s => s.done).length;

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">02 · 피부 촬영 가이드</div>
          <h1 className="page-title">iPad 기반 다각도 촬영 — {SHOTS.length}장 (필수 3, 권장 5)</h1>
          <p className="page-sub">
            표준화된 얼굴 정렬 SW가 광원·각도·조명 일관성을 자동 보정합니다. 노이즈가 검출되면 재촬영을 요청합니다.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-soft btn-sm"><Icons.Rotate size={13} /> 가이드 다시 보기</button>
          <button className="btn btn-primary"
                  disabled={doneCount < 3}
                  onClick={() => setRoute("analysis")}>
            AI 분석 시작 <Icons.Arrow size={14} />
          </button>
        </div>
      </div>

      <div className="grid grid-12">
        {/* LEFT — Live capture viewport */}
        <div className="col-8">
          <Card pad="sm" style={{ overflow: "hidden", background: "#0F0F11" }}>
            {/* Camera viewport */}
            <div style={{
              position: "relative", borderRadius: 14, overflow: "hidden",
              aspectRatio: "4/3", background: "linear-gradient(135deg, #1a1a1c 0%, #2a2a2e 100%)",
            }}>
              {/* Skin photo placeholder */}
              <div className="skin-photo" style={{ position: "absolute", inset: 0, transform: "rotate(-12deg) scale(1.15)", opacity: 0.95, borderRadius: 14 }} />

              {/* Face guide overlay */}
              <svg viewBox="0 0 100 75" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
                <defs>
                  <pattern id="dot-grid" width="3" height="3" patternUnits="userSpaceOnUse">
                    <circle cx="1.5" cy="1.5" r="0.2" fill="rgba(255,255,255,0.18)" />
                  </pattern>
                </defs>
                <rect width="100" height="75" fill="url(#dot-grid)" opacity="0.4" />
                {/* Face oval guide */}
                <ellipse cx="50" cy="38" rx="22" ry="28" fill="none" stroke="rgba(255,255,255,0.6)" strokeWidth="0.3" strokeDasharray="1 1" />
                {/* Center cross */}
                <line x1="50" y1="32" x2="50" y2="44" stroke="rgba(255,255,255,0.85)" strokeWidth="0.2" />
                <line x1="44" y1="38" x2="56" y2="38" stroke="rgba(255,255,255,0.85)" strokeWidth="0.2" />
                {/* Brackets corners */}
                {[[12,8],[88,8],[12,67],[88,67]].map(([x,y],i) => {
                  const dx = x < 50 ? 1 : -1; const dy = y < 38 ? 1 : -1;
                  return <g key={i} stroke="#FFF" strokeWidth="0.4" fill="none">
                    <line x1={x} y1={y} x2={x+5*dx} y2={y} />
                    <line x1={x} y1={y} x2={x} y2={y+4*dy} />
                  </g>;
                })}
              </svg>

              {/* Top HUD */}
              <div style={{ position: "absolute", top: 16, left: 16, right: 16, display: "flex", justifyContent: "space-between" }}>
                <div style={{ display: "flex", gap: 8 }}>
                  <span style={{ background: "rgba(0,0,0,0.55)", color: "#FFF", padding: "4px 9px", borderRadius: 999, fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.04em" }}>
                    REC · ISO 200 · 1/125s
                  </span>
                  <span style={{ background: "rgba(0,0,0,0.55)", color: "#FFF", padding: "4px 9px", borderRadius: 999, fontSize: 11 }}>
                    조명 ✓  각도 ✓  포커스 ✓
                  </span>
                </div>
                <span style={{ background: "rgba(0,0,0,0.55)", color: "#FFF", padding: "4px 9px", borderRadius: 999, fontSize: 11 }}>
                  {SHOTS[current].label} · {SHOTS[current].angle}
                </span>
              </div>

              {/* Bottom guidance */}
              <div style={{ position: "absolute", bottom: 16, left: 16, right: 16, display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
                <div style={{ background: "rgba(0,0,0,0.55)", color: "#FFF", padding: "10px 14px", borderRadius: 12, maxWidth: 280 }}>
                  <div style={{ fontSize: 11, opacity: 0.75, letterSpacing: "0.04em" }}>가이드</div>
                  <div style={{ fontSize: 13, fontWeight: 500, marginTop: 2 }}>{SHOTS[current].note}</div>
                </div>
                <button style={{
                  width: 64, height: 64, borderRadius: "50%",
                  border: "4px solid #FFF", background: "rgba(255,255,255,0.18)",
                  boxShadow: "0 0 0 4px rgba(0,0,0,0.3)",
                  display: "grid", placeItems: "center",
                }} onClick={() => {
                  if (current < SHOTS.length - 1) setCurrent(current + 1);
                }}>
                  <div style={{ width: 48, height: 48, borderRadius: "50%", background: "#FFF" }}></div>
                </button>
                <div style={{ width: 100 }} />
              </div>
            </div>
          </Card>

          {/* Shot strip */}
          <div style={{ display: "grid", gridTemplateColumns: `repeat(${SHOTS.length}, 1fr)`, gap: 10, marginTop: 14 }}>
            {SHOTS.map((shot, i) => (
              <button key={shot.id} onClick={() => setCurrent(i)} style={{
                textAlign: "left", padding: 10, borderRadius: 12,
                background: i === current ? "var(--ink-1)" : "var(--bg-surface)",
                color: i === current ? "#FFF" : "var(--ink-1)",
                border: `1px solid ${i === current ? "var(--ink-1)" : "var(--line-hair)"}`,
                position: "relative",
              }}>
                <div style={{
                  aspectRatio: "1/1", borderRadius: 8, marginBottom: 8,
                  background: shot.done ? "#000" : i === current ? "rgba(255,255,255,0.08)" : "var(--bg-subtle)",
                  position: "relative", overflow: "hidden",
                }}>
                  {shot.done && <div className="skin-photo" style={{ position: "absolute", inset: 0, transform: `rotate(${i * 15 - 30}deg) scale(1.4)`, borderRadius: 8 }} />}
                  {shot.done && (
                    <span style={{ position: "absolute", top: 4, right: 4, width: 18, height: 18, borderRadius: "50%", background: "var(--good)", display: "grid", placeItems: "center" }}>
                      <Icons.Check size={11} stroke="#FFF" sw={2.4} />
                    </span>
                  )}
                  {!shot.done && i === current && (
                    <span style={{ position: "absolute", top: 4, right: 4 }} className="pill pill-info">촬영중</span>
                  )}
                </div>
                <div style={{ fontSize: 12, fontWeight: 600 }}>{shot.label}</div>
                <div className="mono" style={{ fontSize: 10, opacity: 0.7, marginTop: 1 }}>{shot.angle}</div>
              </button>
            ))}
          </div>
        </div>

        {/* RIGHT — Quality checks + preprocess */}
        <div className="col-4" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card pad="lg">
            <div className="card-title-row">
              <h3 className="card-title"><span className="dot"></span>이미지 품질 검증</h3>
              <Pill tone="good" dot>실시간</Pill>
            </div>
            {[
              { l: "얼굴 정렬 (Yaw / Pitch / Roll)", v: 96, t: "good" },
              { l: "노출 (Exposure)", v: 88, t: "good" },
              { l: "조명 균일도", v: 82, t: "good" },
              { l: "초점 (Focus)", v: 91, t: "good" },
              { l: "모션 블러", v: 12, t: "good", inverse: true },
              { l: "안경/마스크 가림", v: 0, t: "good", inverse: true },
            ].map((q, i) => (
              <div key={i} style={{ marginBottom: 10 }}>
                <ScoreBar label={q.l} value={q.v} tone={q.t} />
              </div>
            ))}
            <div className="divider" />
            <div style={{ background: "var(--good-10)", borderRadius: 10, padding: "10px 12px", display: "flex", gap: 10, alignItems: "center" }}>
              <Icons.ShieldCheck size={18} stroke="currentColor" style={{ color: "var(--good)", flexShrink: 0 }} />
              <div style={{ fontSize: 12.5 }}>
                <div style={{ fontWeight: 600, color: "var(--good)" }}>분석 가능 상태</div>
                <div style={{ color: "var(--ink-3)", marginTop: 1 }}>{doneCount}/3 필수 컷 완료 — AI 분석 시작 가능</div>
              </div>
            </div>
          </Card>

          <Card pad="md" title="이미지 전처리 파이프라인">
            {[
              { l: "얼굴 keypoint 추출", t: "MediaPipe Face Mesh", done: true },
              { l: "정렬·정규화", t: "Affine warp · 1024×1024", done: true },
              { l: "노이즈 보정", t: "Denoise + WB 조정", done: true },
              { l: "RGB → multi-spectral", t: "Chromophore 분리", done: true },
              { l: "Region segmentation", t: "코·볼·이마·턱·눈주변", done: false, active: true },
              { l: "Skin texture map", t: "표면 요철 추정", done: false },
            ].map((step, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: i < 5 ? "1px dashed var(--line-hair)" : "0" }}>
                <span style={{
                  width: 22, height: 22, borderRadius: "50%",
                  background: step.done ? "var(--ink-1)" : step.active ? "var(--phase-tint)" : "var(--bg-subtle)",
                  color: "#FFF", display: "grid", placeItems: "center", flexShrink: 0,
                }}>
                  {step.done ? <Icons.Check size={12} sw={2.4} stroke="#FFF" /> :
                   step.active ? <Spinner size={12} /> : <span style={{ fontSize: 10, color: "var(--ink-4)" }}>{i+1}</span>}
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--ink-1)" }}>{step.l}</div>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-4)", marginTop: 1 }}>{step.t}</div>
                </div>
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

window.CaptureScreen = CaptureScreen;
