// screens/chart.jsx — Smart Chart Auto-fill

function ChartScreen({ persona, setRoute }) {
  const Icons = window.Icons;
  const [autoFilled, setAutoFilled] = React.useState(new Set([
    "patient_info", "skin_diag", "treatment_plan", "ba_images", "consent",
  ]));
  const [doctorNote, setDoctorNote] = React.useState(
    "환자분 코·볼 모공 밀도 일반 기준 대비 약 20% 높음. 염증성 여드름·홍조 동반되므로 ablative 시술 회피. RF Micro-needling 4회 + Salicylic Peel 4회 protocol 권장. 첫 회차 후 24h SMS 모니터링 필요."
  );

  const fields = [
    { id: "patient_info", k: "환자 정보", auto: true, from: "EMR · CRM" },
    { id: "skin_diag",   k: "피부 진단 결과 (10 지표)", auto: true, from: "AI Engine" },
    { id: "indicators",  k: "세부 측정 지표 (47 features)", auto: true, from: "AI Engine" },
    { id: "treatment_plan", k: "추천 시술 plan", auto: true, from: "Recommendation Engine" },
    { id: "device_setting", k: "장비 세팅 (energy/depth/shot)", auto: false, from: "(의사 입력 필요)" },
    { id: "ba_images",   k: "B&A 이미지", auto: true, from: "Pre/Post Capture" },
    { id: "consent",     k: "환자 동의서", auto: true, from: "전자 서명" },
    { id: "billing",     k: "수납·결제 정보", auto: true, from: "POS 연계" },
    { id: "doctor_note", k: "의사 소견 (자유 기재)", auto: false, from: "(의사 입력)" },
  ];

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">07 · Smart Chart Auto-fill</div>
          <h1 className="page-title">차트 자동 기록 — {autoFilled.size} / {fields.length} 자동 입력 완료</h1>
          <p className="page-sub">
            진단 결과·상담 내용·시술 setting·B&A 이미지·환자 동의 정보가 차트에 자동 반영됩니다. 의사는 자유 소견과 장비 세팅만 직접 기입합니다.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-soft btn-sm"><Icons.Download size={13} /> EMR 내보내기</button>
          <button className="btn btn-primary"><Icons.ShieldCheck size={13} /> 차트 잠금 · 확정</button>
        </div>
      </div>

      <div className="grid grid-12">
        {/* LEFT — Chart preview */}
        <div className="col-8">
          <Card pad="lg">
            <div className="card-title-row">
              <div>
                <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, letterSpacing: "-0.01em" }}>피부과 진료 차트</h3>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>
                  Chart ID <span className="num">CH-2026-05-27-0089</span> · 안양피부과 강남점 · 박지훈 원장
                </div>
              </div>
              <Pill tone="info"><Icons.Sparkle size={11} /> AI Auto-fill</Pill>
            </div>

            <div className="divider" />

            {/* Patient info section */}
            <ChartSection label="A · 환자 정보" filled>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
                <Field l="환자명" v={persona.nameMasked} />
                <Field l="ID" v={persona.id} mono />
                <Field l="나이/성별" v={`${persona.age}세 / ${persona.gender === "F" ? "여" : "남"}`} />
                <Field l="피부 타입" v={persona.skinType} />
                <Field l="알러지/주의" v="—" />
                <Field l="복용 약물" v="—" />
                <Field l="이전 시술 이력" v="RF Micro-needling × 3 (2025.11~2026.03)" wide />
              </div>
            </ChartSection>

            {/* Diagnosis */}
            <ChartSection label="B · 피부 진단 결과" filled>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 10 }}>
                {SCORE_KEYS.slice(0, 10).map(k => (
                  <div key={k} style={{ padding: "10px 12px", borderRadius: 10, background: "var(--bg-subtle)" }}>
                    <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{k}</div>
                    <div className="num" style={{ fontSize: 18, fontWeight: 700, marginTop: 2 }}>{persona.skinScores[k]}</div>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 12, fontSize: 12.5, color: "var(--ink-2)" }}>
                <strong>Top Concern:</strong> {persona.topConcern} · <strong>Secondary:</strong> {persona.secondaryConcerns.join(", ")}
              </div>
            </ChartSection>

            {/* Treatment plan */}
            <ChartSection label="C · 시술 plan (확정)" filled>
              <table className="table" style={{ marginTop: 0 }}>
                <thead>
                  <tr>
                    <th>회차</th>
                    <th>시술</th>
                    <th>장비</th>
                    <th>예상 일정</th>
                    <th>비용</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    { n: 1, tx: "Secret RF Micro-needling #1", dev: "Secret RF Duo", date: "2026.06.04", price: "₩32만" },
                    { n: 2, tx: "Salicylic Peel #1", dev: "—", date: "2026.06.04", price: "₩9만" },
                    { n: 3, tx: "Salicylic Peel #2", dev: "—", date: "2026.06.18", price: "₩9만" },
                    { n: 4, tx: "Secret RF Micro-needling #2", dev: "Secret RF Duo", date: "2026.07.02", price: "₩32만" },
                  ].map(r => (
                    <tr key={r.n}>
                      <td><span className="num" style={{ fontWeight: 700 }}>{r.n}</span></td>
                      <td>{r.tx}</td>
                      <td><span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{r.dev}</span></td>
                      <td className="num" style={{ color: "var(--ink-3)" }}>{r.date}</td>
                      <td className="num" style={{ fontWeight: 600 }}>{r.price}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </ChartSection>

            {/* Device setting (manual) */}
            <ChartSection label="D · 장비 세팅" required>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
                <Field l="장비" v="Secret RF Duo" />
                <Field l="부위" v="코·볼·이마" />
                <Field l="Energy (mJ)" v="—" placeholder mono />
                <Field l="Depth (mm)" v="—" placeholder mono />
                <Field l="Shots (개수)" v="—" placeholder mono />
                <Field l="Pulse" v="—" placeholder mono />
                <Field l="비고" v="" placeholder wide />
              </div>
              <div style={{ marginTop: 10, padding: "8px 10px", borderRadius: 8, background: "var(--data-blue-10)", fontSize: 11.5, color: "var(--data-blue)", display: "flex", gap: 6, alignItems: "center" }}>
                <Icons.Info size={12} /> AI 권장 reference: Energy 7-9mJ · Depth 1.5-2.0mm · Shots 1500 (cohort 142명 기준) — 최종 결정은 의사
              </div>
            </ChartSection>

            {/* Doctor note */}
            <ChartSection label="E · 의사 소견" required>
              <textarea className="textarea" value={doctorNote} onChange={e => setDoctorNote(e.target.value)} style={{ minHeight: 90 }} />
            </ChartSection>

            {/* B&A + consent */}
            <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14, marginTop: 14 }}>
              <ChartSection label="F · B&A 이미지" filled compact>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
                  {Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} style={{ aspectRatio: "1/1", borderRadius: 8, overflow: "hidden", position: "relative" }}>
                      <div className="skin-photo" style={{ position: "absolute", inset: 0, transform: `rotate(${i*8-12}deg) scale(1.3)` }} />
                      <span style={{ position: "absolute", bottom: 4, left: 4, padding: "1px 5px", background: "rgba(0,0,0,0.6)", color: "#FFF", fontSize: 9, borderRadius: 3, fontFamily: "var(--font-mono)" }}>{["FRONT","L45","R45","L90"][i]}</span>
                    </div>
                  ))}
                </div>
              </ChartSection>
              <ChartSection label="G · 동의서 · 결제" filled compact>
                <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 12 }}>
                  <Row l="시술 동의서" v="전자 서명 완료" tone="good" />
                  <Row l="개인정보 동의" v="동의" tone="good" />
                  <Row l="이미지 활용 동의" v="동의 (블러 처리)" tone="good" />
                  <Row l="결제" v="₩880,000 · 무이자 3개월" tone="info" />
                </div>
              </ChartSection>
            </div>
          </Card>
        </div>

        {/* RIGHT — auto-fill status */}
        <div className="col-4" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Card pad="lg">
            <div className="card-title-row">
              <h3 className="card-title"><span className="dot"></span>Auto-fill 진행 상태</h3>
              <Pill tone="good" dot>실시간</Pill>
            </div>
            <div style={{ marginBottom: 14 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>전체 진행률</span>
                <span className="num" style={{ fontSize: 13, fontWeight: 600 }}>{autoFilled.size} / {fields.length}</span>
              </div>
              <div style={{ height: 8, background: "var(--bg-subtle)", borderRadius: 999, overflow: "hidden" }}>
                <div style={{ width: `${(autoFilled.size / fields.length) * 100}%`, height: "100%", background: "var(--phase-tint)", borderRadius: 999, transition: "width 600ms" }}></div>
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {fields.map(f => {
                const filled = autoFilled.has(f.id);
                return (
                  <div key={f.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: "1px dashed var(--line-hair)" }}>
                    <span style={{
                      width: 18, height: 18, borderRadius: "50%",
                      background: filled ? "var(--good)" : f.auto ? "var(--bg-subtle)" : "var(--watch-10)",
                      color: filled ? "#FFF" : "var(--ink-3)",
                      display: "grid", placeItems: "center", flexShrink: 0,
                    }}>
                      {filled ? <Icons.Check size={11} sw={3} stroke="#FFF" /> : <Icons.Edit size={10} stroke="currentColor" />}
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 500 }}>{f.k}</div>
                      <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-4)" }}>{f.from}</div>
                    </div>
                    {!f.auto && <Pill tone="watch">수동</Pill>}
                  </div>
                );
              })}
            </div>
          </Card>

          <Card pad="md" title="규제 · 컴플라이언스">
            {[
              { l: "의료법 제22조 (의무기록)", state: "준수", t: "good" },
              { l: "개인정보보호법 (영상)", state: "준수", t: "good" },
              { l: "전자서명법", state: "준수", t: "good" },
              { l: "의료기기 SW 등급", state: "Class 2 검토중", t: "watch" },
            ].map((c, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 12.5, borderBottom: i < 3 ? "1px dashed var(--line-hair)" : "0" }}>
                <span style={{ color: "var(--ink-2)" }}>{c.l}</span>
                <Pill tone={c.t} dot>{c.state}</Pill>
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

function ChartSection({ label, filled, required, compact, children }) {
  const Icons = window.Icons;
  return (
    <div style={{ marginTop: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
        <span style={{ fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.06em", fontWeight: 700, textTransform: "uppercase" }}>{label}</span>
        {filled && <Pill tone="good"><Icons.Sparkle size={10} /> Auto</Pill>}
        {required && <Pill tone="watch">의사 입력</Pill>}
        <div style={{ flex: 1, height: 1, background: "var(--line-hair)" }}></div>
      </div>
      {children}
    </div>
  );
}

function Field({ l, v, mono, placeholder, wide }) {
  return (
    <div style={{ gridColumn: wide ? "span 4" : undefined }}>
      <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 4, letterSpacing: "0.02em" }}>{l}</div>
      <div className={mono ? "mono" : ""} style={{ fontSize: 13, fontWeight: 500, color: placeholder ? "var(--ink-4)" : "var(--ink-1)" }}>
        {v || "—"}
      </div>
    </div>
  );
}

function Row({ l, v, tone }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <span style={{ color: "var(--ink-2)" }}>{l}</span>
      <Pill tone={tone} dot>{v}</Pill>
    </div>
  );
}

window.ChartScreen = ChartScreen;
