// screens/recommend.jsx — 시술 추천 (Primary/Secondary, 3 옵션) + Package bundling

function RecommendScreen({ persona, setRoute }) {
  const Icons = window.Icons;
  const [mode, setMode] = React.useState("treatment"); // treatment | package
  const [selectedTx, setSelectedTx] = React.useState("rf-microneedling");
  const [scriptOpen, setScriptOpen] = React.useState(null);
  const [activePkg, setActivePkg] = React.useState("pkg-comprehensive");

  const tx = TREATMENTS.find(t => t.id === selectedTx) || TREATMENTS[0];
  const primary = TREATMENTS.filter(t => t.tier === "primary");
  const secondary = TREATMENTS.filter(t => t.tier === "secondary");
  const pkg = PACKAGES.find(p => p.id === activePkg);

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">05 · 시술 추천 · 패키지</div>
          <h1 className="page-title">개인화 시술 — Primary 2건 · Secondary 2건 추천</h1>
          <p className="page-sub">
            환자 배경, 진단 결과, 예산·다운타임 조건과 유사 환자 cohort 데이터를 결합하여 최적 시술 조합과 패키지 옵션을 도출했습니다. AI 추천은 의사 검토 후 최종 확정됩니다.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <Tabs tabs={[{v:"treatment",l:"개별 시술"}, {v:"package",l:"패키지 번들"}]} value={mode} onChange={setMode} />
          <button className="btn btn-primary" onClick={() => setRoute("ba")}>
            B&A 시뮬레이션 <Icons.Arrow size={14} />
          </button>
        </div>
      </div>

      {mode === "treatment" ? (
        <div className="grid grid-12">
          {/* LEFT — Treatment list */}
          <div className="col-7" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div>
              <div className="stat-label" style={{ marginBottom: 10 }}>Primary 추천 · 핵심 시술</div>
              {primary.map((t, i) => <TxCard key={t.id} tx={t} selected={selectedTx === t.id}
                                              onSelect={() => setSelectedTx(t.id)}
                                              onScript={() => setScriptOpen(scriptOpen === t.id ? null : t.id)}
                                              scriptOpen={scriptOpen === t.id}
                                              persona={persona} />)}
            </div>
            <div style={{ marginTop: 8 }}>
              <div className="stat-label" style={{ marginBottom: 10 }}>Secondary · 보조 시술</div>
              {secondary.map((t, i) => <TxCard key={t.id} tx={t} selected={selectedTx === t.id}
                                                onSelect={() => setSelectedTx(t.id)}
                                                onScript={() => setScriptOpen(scriptOpen === t.id ? null : t.id)}
                                                scriptOpen={scriptOpen === t.id}
                                                persona={persona} />)}
            </div>
          </div>

          {/* RIGHT — Detail + sessions */}
          <div className="col-5" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Card pad="lg" style={{ position: "sticky", top: 80 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                <Pill tone={tx.tier === "primary" ? "info" : "outline"}>{tx.tier === "primary" ? "Primary" : "Secondary"}</Pill>
                <Pill tone="skin">{tx.targetConcern.join(" · ")}</Pill>
              </div>
              <h2 style={{ margin: "8px 0 4px", fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>{tx.name}</h2>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{tx.category}</div>

              <div className="divider" />

              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
                <Stat mini label="적합도" value={`${tx.fit}%`} sub="AI cohort 기반" />
                <Stat mini label="시간" value={tx.duration} sub="회당" />
                <Stat mini label="다운타임" value={tx.downtime} />
                <Stat mini label="회당" value={`${tx.pricePerSession/10000}만`} sub="₩" />
              </div>

              <div className="divider" />

              <div className="stat-label" style={{ marginBottom: 10 }}>회차 옵션</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {tx.sessions.map((s, i) => (
                  <div key={i} style={{
                    display: "flex", alignItems: "center", justifyContent: "space-between",
                    padding: "12px 14px", borderRadius: 12,
                    background: s.recommended ? "var(--bg-subtle)" : "var(--bg-surface)",
                    border: `1px solid ${s.recommended ? "var(--ink-1)" : "var(--line-hair)"}`,
                  }}>
                    <div>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <span className="num" style={{ fontSize: 18, fontWeight: 700 }}>{s.count}</span>
                        <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>회 패키지</span>
                        {s.badge && <Pill tone={s.recommended ? "info" : "outline"}>{s.badge}</Pill>}
                      </div>
                      <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2 }}>
                        {Math.round(s.count * 1.5)}주 · 회당 ₩{Math.round(s.price / s.count / 1000)}K
                      </div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div className="num" style={{ fontSize: 17, fontWeight: 700 }}>₩{(s.price/10000).toFixed(0)}만</div>
                      <div style={{ fontSize: 11, color: "var(--ink-4)", textDecoration: "line-through" }}>
                        ₩{(s.original/10000).toFixed(0)}만
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              <div className="divider" />

              <div className="stat-label" style={{ marginBottom: 10 }}>AI 근거 (Evidence)</div>
              <div style={{ display: "flex", gap: 10 }}>
                <div style={{ flex: 1, padding: 12, background: "var(--bg-subtle)", borderRadius: 10 }}>
                  <div className="num" style={{ fontSize: 18, fontWeight: 700, color: "var(--ink-1)" }}>{tx.aiEvidence.studies}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)" }}>레퍼런스 연구</div>
                </div>
                <div style={{ flex: 1, padding: 12, background: "var(--bg-subtle)", borderRadius: 10 }}>
                  <div className="num" style={{ fontSize: 18, fontWeight: 700, color: "var(--ink-1)" }}>{tx.aiEvidence.improvement}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)" }}>평균 개선 폭</div>
                </div>
                <div style={{ flex: 1, padding: 12, background: "var(--bg-subtle)", borderRadius: 10 }}>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{tx.aiEvidence.cohort}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)" }}>6개월 추적</div>
                </div>
              </div>
            </Card>
          </div>
        </div>
      ) : (
        // PACKAGE MODE
        <div>
          <div className="grid grid-3" style={{ marginBottom: 18 }}>
            {PACKAGES.map((p, i) => (
              <Card key={p.id} pad="lg"
                    onClick={() => setActivePkg(p.id)}
                    style={{
                      cursor: "pointer",
                      borderColor: activePkg === p.id ? "var(--ink-1)" : "var(--line-hair)",
                      borderWidth: activePkg === p.id ? 1.5 : 1,
                      boxShadow: activePkg === p.id ? "0 8px 24px rgba(15,15,17,0.08)" : "var(--shadow-card)",
                      position: "relative",
                    }}>
                {p.recommended && (
                  <span style={{ position: "absolute", top: 12, right: 12 }} className="pill pill-info">
                    <Icons.Sparkle size={11} /> AI 권장
                  </span>
                )}
                <Pill tone={p.tier === "권장" ? "skin" : p.tier === "집중" ? "info" : "outline"}>{p.tier}</Pill>
                <h3 style={{ margin: "10px 0 4px", fontSize: 18, fontWeight: 700, letterSpacing: "-0.015em" }}>{p.name}</h3>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{p.targets.join(" · ")}</div>

                <div className="divider" />

                <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <span className="num" style={{ fontSize: 26, fontWeight: 700 }}>₩{(p.price / 10000).toFixed(0)}만</span>
                  <span style={{ fontSize: 12, color: "var(--ink-4)", textDecoration: "line-through" }}>
                    ₩{(p.original / 10000).toFixed(0)}만
                  </span>
                  <Pill tone="good">-{p.discount}%</Pill>
                </div>
                <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>
                  {p.sessions}회 · {p.duration} · 회당 평균 ₩{Math.round(p.price / p.sessions / 10000)}만
                </div>

                <div className="divider" />

                <div className="stat-label" style={{ marginBottom: 8 }}>구성</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {p.items.map((item, j) => (
                    <div key={j} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
                      <Icons.Check size={12} stroke="var(--good)" sw={2.4} />
                      <span style={{ color: "var(--ink-2)" }}>{item}</span>
                    </div>
                  ))}
                </div>
                <div style={{ marginTop: 14 }}>
                  <CoverageGauge value={p.coverage} label="고민 영역 커버리지" color={p.recommended ? "var(--phase-tint)" : "var(--ink-2)"} />
                </div>
              </Card>
            ))}
          </div>

          {/* Package detail */}
          <Card pad="lg">
            <div className="grid grid-12">
              <div className="col-8">
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                  <Pill tone="info"><Icons.Package size={11} /> 선택된 패키지</Pill>
                  <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>{pkg.name}</h2>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginTop: 16 }}>
                  <Stat label="총 세션" value={`${pkg.sessions}회`} sub={pkg.duration} />
                  <Stat label="패키지 가격" value={`₩${(pkg.price/10000).toFixed(0)}만`} sub={`정가 ₩${(pkg.original/10000).toFixed(0)}만`} />
                  <Stat label="할인율" value={`${pkg.discount}%`} sub={`₩${((pkg.original-pkg.price)/10000).toFixed(0)}만 절약`} />
                  <Stat label="회당 평균" value={`₩${Math.round(pkg.price/pkg.sessions/10000)}만`} sub="결제 분할 가능 (3/6/12개월)" />
                </div>

                <div className="divider" />

                <div className="stat-label" style={{ marginBottom: 10 }}>예상 일정 (자동 생성)</div>
                <div style={{ position: "relative", height: 64, background: "var(--bg-subtle)", borderRadius: 12, padding: "10px 14px" }}>
                  {/* Timeline */}
                  <div style={{ position: "absolute", left: 14, right: 14, top: "50%", height: 2, background: "var(--line-soft)" }}></div>
                  {Array.from({ length: pkg.sessions }).map((_, i) => {
                    const pos = (i / (pkg.sessions - 1)) * 100;
                    const recommended = i === 2;
                    return (
                      <div key={i} style={{ position: "absolute", left: `calc(14px + ${pos}% - ${pos * 28 / 100}px)`, top: "50%", transform: "translateY(-50%)" }}>
                        <div style={{
                          width: 10, height: 10, borderRadius: "50%",
                          background: i === 0 ? "var(--ink-1)" : "var(--bg-surface)",
                          border: "2px solid var(--ink-1)",
                        }}></div>
                        <div className="mono" style={{ position: "absolute", top: 12, left: "50%", transform: "translateX(-50%)", fontSize: 9, color: "var(--ink-4)", whiteSpace: "nowrap" }}>
                          W{i * Math.ceil(parseInt(pkg.duration) / pkg.sessions) || 0}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="col-4">
                <div style={{
                  padding: 18, borderRadius: 14,
                  background: "linear-gradient(180deg, #FAFAFA 0%, #F4F4F6 100%)",
                  border: "1px solid var(--line-hair)",
                }}>
                  <div style={{ fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.05em", textTransform: "uppercase", fontWeight: 600 }}>예상 결과 (6개월)</div>
                  <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 12 }}>
                    {pkg.targets.map((t, i) => (
                      <div key={t}>
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, fontWeight: 500, marginBottom: 4 }}>
                          <span>{t}</span>
                          <span className="num" style={{ color: "var(--good)", fontWeight: 600 }}>+{[38, 30, 24][i] || 22}%</span>
                        </div>
                        <div style={{ height: 6, background: "var(--bg-subtle)", borderRadius: 999, overflow: "hidden" }}>
                          <div style={{ width: `${[88, 76, 64][i] || 60}%`, height: "100%", background: "var(--phase-tint)", borderRadius: 999 }}></div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
                <button className="btn btn-primary btn-lg" style={{ width: "100%", marginTop: 14 }}>
                  <Icons.Check size={14} sw={2.4} stroke="#FFF" /> 패키지 확정
                </button>
              </div>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}

// Treatment card
function TxCard({ tx, selected, onSelect, onScript, scriptOpen, persona }) {
  const Icons = window.Icons;
  return (
    <div className="card" style={{
      padding: "16px 18px", marginBottom: 10,
      borderColor: selected ? "var(--ink-1)" : "var(--line-hair)",
      cursor: "pointer",
    }} onClick={onSelect}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: tx.tier === "primary" ? "var(--ink-1)" : "var(--bg-subtle)",
          color: tx.tier === "primary" ? "#FFF" : "var(--ink-1)",
          display: "grid", placeItems: "center", flexShrink: 0,
        }}>
          <Icons.Sparkle size={18} stroke="currentColor" />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2 }}>
                <h4 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>{tx.name}</h4>
                <Pill tone="outline">{tx.category}</Pill>
              </div>
              <div style={{ display: "flex", gap: 10, fontSize: 12, color: "var(--ink-3)" }}>
                <span>{tx.targetConcern.join(" · ")}</span>
                <span>·</span>
                <span>{tx.duration} · 다운타임 {tx.downtime}</span>
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="num" style={{ fontSize: 18, fontWeight: 700 }}>{tx.fit}<span style={{ fontSize: 11, color: "var(--ink-4)", marginLeft: 2 }}>%</span></div>
              <div style={{ fontSize: 10, color: "var(--ink-4)", letterSpacing: "0.04em", textTransform: "uppercase" }}>적합도</div>
            </div>
          </div>
          {scriptOpen && (
            <div style={{ marginTop: 12, padding: 12, borderRadius: 10, background: "var(--bg-subtle)", fontSize: 12.5, lineHeight: 1.6, color: "var(--ink-2)" }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)", marginBottom: 6, letterSpacing: "0.04em" }}>실장용 상담 스크립트</div>
              {tx.script}
            </div>
          )}
          <div style={{ display: "flex", gap: 8, marginTop: 10, alignItems: "center" }}>
            <button className="btn btn-soft btn-sm" onClick={(e) => { e.stopPropagation(); onScript(); }}>
              <Icons.Doc size={11} /> {scriptOpen ? "스크립트 닫기" : "상담 스크립트"}
            </button>
            <button className="btn btn-ghost btn-sm" onClick={(e) => e.stopPropagation()}><Icons.Sparkle size={11} /> 근거 보기</button>
            <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--ink-4)" }}>
              회당 <span className="num" style={{ color: "var(--ink-2)", fontWeight: 600 }}>₩{(tx.pricePerSession/10000).toFixed(0)}만</span>
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

window.RecommendScreen = RecommendScreen;
