// screens/intake.jsx — 환자 체크인 · 문진 (RFM·고민·유입경로)

function IntakeScreen({ persona, role, setRoute }) {
  const Icons = window.Icons;
  const [concerns, setConcerns] = React.useState(["모공", "유분/피지광"]);
  const [secondary, setSecondary] = React.useState(["여드름", "홍조"]);
  const [inflow, setInflow] = React.useState("instagram");
  const [budget, setBudget] = React.useState("1.5M");
  const [downtime, setDowntime] = React.useState("3일");
  const [goal, setGoal] = React.useState("이벤트 (결혼식) 2개월 후");
  const [step, setStep] = React.useState(2); // 0=체크인, 1=배경, 2=문진, 3=완료

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">01 · 환자 체크인 · 문진</div>
          <h1 className="page-title">상담 시작 — 환자 배경·니즈 프로파일링</h1>
          <p className="page-sub">
            환자 본인 또는 실장이 iPad에서 작성합니다. EMR·CRM·예약·문진 데이터가 통합되어 AI가 환자 세그먼트와 주요 니즈를 자동 태깅합니다.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-soft btn-sm"><Icons.Refresh size={13} /> 초기화</button>
          <button className="btn btn-primary" onClick={() => setRoute("capture")}>
            촬영 단계로 <Icons.Arrow size={14} />
          </button>
        </div>
      </div>

      {/* Stepper */}
      <div style={{ marginBottom: 24, display: "flex", alignItems: "center", gap: 18 }}>
        <Stepper steps={["체크인", "배경 데이터", "문진", "완료"]} current={step} />
        <span style={{ fontSize: 11.5, color: "var(--ink-4)", fontFamily: "var(--font-mono)" }}>
          STEP {String(step + 1).padStart(2, "0")} / 04
        </span>
      </div>

      <div className="grid grid-12">
        {/* LEFT — Form */}
        <div className="col-8" style={{ display: "flex", flexDirection: "column", gap: 16 }}>

          {/* Patient header card */}
          <Card pad="lg">
            <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
              <Avatar initials={persona.initials} size={56} color="var(--skin-coral)" />
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", gap: 10, alignItems: "baseline", marginBottom: 4 }}>
                  <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>{persona.nameMasked}</h2>
                  <span className="num" style={{ fontSize: 13, color: "var(--ink-3)" }}>{persona.age}세 · {persona.gender === "F" ? "여" : "남"}</span>
                  <Pill tone="skin" dot>{persona.segment}</Pill>
                </div>
                <div style={{ display: "flex", gap: 14, fontSize: 12, color: "var(--ink-3)" }}>
                  <span><span className="mono" style={{ color: "var(--ink-4)" }}>ID</span> <span className="num">{persona.id}</span></span>
                  <span>·</span>
                  <span>방문 {persona.visits}회 · 마지막 {persona.lastVisit}</span>
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="stat-label">누적 매출</div>
                <div className="num" style={{ fontSize: 22, fontWeight: 600, marginTop: 2 }}>₩{(persona.rfm.monetary / 10000).toFixed(0)}만</div>
              </div>
            </div>
          </Card>

          {/* Concerns */}
          <Card title="주요 피부 고민 (Top 3, 우선순위 자동 정렬)" action={<span className="pill pill-info"><Icons.Sparkle size={11} /> AI 자동 태깅</span>}>
            <ChipGroup options={CONCERN_OPTIONS} value={concerns} onChange={setConcerns} />
            <div className="divider" />
            <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-2)", marginBottom: 8 }}>2차 관심 영역</div>
            <ChipGroup options={CONCERN_OPTIONS} value={secondary} onChange={setSecondary} />
          </Card>

          {/* Constraints */}
          <Card title="시술 선호 조건">
            <div className="grid grid-3">
              <div className="field">
                <label className="field-label">예산 (회당 / 패키지)</label>
                <ChipGroup options={["50만 이하", "1M", "1.5M", "2M+", "유연"]} value={budget} onChange={setBudget} single />
              </div>
              <div className="field">
                <label className="field-label">허용 다운타임</label>
                <ChipGroup options={["당일", "1일", "3일", "5일+", "무관"]} value={downtime} onChange={setDowntime} single />
              </div>
              <div className="field">
                <label className="field-label">목표 / 이벤트</label>
                <input className="input" value={goal} onChange={e => setGoal(e.target.value)} />
                <span className="field-hint">예: "결혼식 2개월 후", "여름 휴가 전 1개월"</span>
              </div>
            </div>
          </Card>

          {/* Inflow + history */}
          <Card title="유입 경로 · 과거 이력 (자동 연동)">
            <div className="row" style={{ marginBottom: 12 }}>
              <span style={{ fontSize: 12.5, color: "var(--ink-3)", marginRight: 6 }}>유입</span>
              <ChipGroup options={INFLOW_OPTIONS} value={inflow} onChange={setInflow} single />
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", paddingLeft: 4 }}>
              연동된 채널: <span style={{ color: "var(--ink-1)", fontWeight: 600 }}>{persona.inflowDetail}</span>
            </div>
            <div className="divider" />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
              <Stat mini label="첫 방문" value="2025.11.02" sub="216일 전" />
              <Stat mini label="총 방문" value={`${persona.visits}회`} sub="평균 73일 간격" />
              <Stat mini label="누적 시술" value="7건" sub="RF 3, Peel 4" />
              <Stat mini label="잔여 패키지" value="2회" sub="만료 D-46" />
            </div>
          </Card>
        </div>

        {/* RIGHT — AI inferred profile */}
        <div className="col-4" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card pad="lg" style={{ background: "linear-gradient(180deg, #FFF 0%, #FAFAFA 100%)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
              <Icons.Sparkle size={16} stroke="currentColor" style={{ color: "var(--phase-tint)" }} />
              <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600, letterSpacing: "-0.005em" }}>AI 환자 프로파일</h3>
              <Pill tone="info">실시간</Pill>
            </div>

            <div style={{ fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.04em", textTransform: "uppercase", fontWeight: 600 }}>예상 세그먼트</div>
            <div style={{ fontSize: 18, fontWeight: 700, color: "var(--ink-1)", letterSpacing: "-0.02em", marginTop: 4 }}>
              {persona.segment}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.5 }}>
              유사 환자 cohort: <span className="num">142</span>명 · 평균 객단가 <span className="num">₩1.38M</span>
            </div>

            <div className="divider" />

            <div className="stat-label">RFM 분석</div>
            <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 12 }}>
              <ScoreBar label="Recency" value={Math.max(0, 100 - persona.rfm.recency)} max={100} tone="watch" />
              <ScoreBar label="Frequency" value={Math.min(100, persona.rfm.frequency * 25)} max={100} tone="good" />
              <ScoreBar label="Monetary" value={Math.min(100, persona.rfm.monetary / 50000)} max={100} />
            </div>

            <div className="divider" />

            <div className="stat-label">자동 태깅 (5)</div>
            <div className="chip-group" style={{ marginTop: 8 }}>
              {["모공-우선", "지성-T존", "재방문-활성", "패키지-유효", "후기-노출"].map(t => (
                <Pill key={t} tone="outline">{t}</Pill>
              ))}
            </div>

            <div className="divider" />

            <div className="stat-label">리스크 플래그</div>
            <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 8 }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 12, color: "var(--ink-2)" }}>
                <Icons.Warn size={14} stroke="currentColor" style={{ color: "var(--watch)", flexShrink: 0, marginTop: 2 }} />
                <span>홍조 면적이 일반 기준 대비 1.5배 — 강한 레이저 시 PIH 가능성 모니터링</span>
              </div>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 12, color: "var(--ink-2)" }}>
                <Icons.Info size={14} stroke="currentColor" style={{ color: "var(--data-blue)", flexShrink: 0, marginTop: 2 }} />
                <span>지난 시술 후 24h SMS 만족도 응답 없음 — 후속 컨택 권장</span>
              </div>
            </div>
          </Card>

          <Card pad="md">
            <div className="card-title-row">
              <h3 className="card-title"><span className="dot"></span>연계 시스템</h3>
            </div>
            {[
              { sys: "EMR (자체)",    status: "연결됨", time: "1초 전" },
              { sys: "CRM (Hubspot)", status: "연결됨", time: "12초 전" },
              { sys: "예약 (네이버)", status: "연결됨", time: "1분 전" },
              { sys: "문진 (Tally)",  status: "수신중", time: "방금" },
            ].map(s => (
              <div key={s.sys} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 12.5, borderBottom: "1px dashed var(--line-hair)" }}>
                <span style={{ color: "var(--ink-2)", fontWeight: 500 }}>{s.sys}</span>
                <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span className="pulse-dot" style={{ width: 6, height: 6 }}></span>
                  <span style={{ color: "var(--ink-3)" }}>{s.time}</span>
                </span>
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

window.IntakeScreen = IntakeScreen;
