// screens/devices.jsx — Connected Device Dashboard

function DevicesScreen({ setRoute }) {
  const Icons = window.Icons;
  const [selected, setSelected] = React.useState("dev-1");
  const dev = DEVICES.find(d => d.id === selected) || DEVICES[0];

  // Util history (last 14 days)
  const histMap = {
    "dev-1": [68, 72, 71, 70, 74, 76, 75, 78, 80, 76, 79, 78, 81, 78],
    "dev-2": [78, 80, 82, 81, 83, 85, 84, 86, 88, 85, 84, 86, 87, 84],
    "dev-3": [38, 42, 40, 36, 38, 42, 44, 41, 39, 45, 42, 40, 43, 41],
    "dev-4": [44, 48, 36, 28, 30, 20, 12, 4, 0, 0, 0, 0, 0, 0],
    "dev-5": [28, 32, 30, 26, 24, 28, 26, 22, 20, 18, 20, 22, 24, 22],
    "dev-6": [60, 62, 65, 63, 64, 66, 68, 67, 69, 70, 68, 67, 66, 67],
  };

  const statusColor = (s) => ({
    "운영중": "good", "정비": "alert", "유휴": "watch",
  }[s] || "outline");

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">09 · Connected Device Dashboard</div>
          <h1 className="page-title">장비 가동률·소모품 통합 모니터링</h1>
          <p className="page-sub">
            6대 장비의 실시간 가동 상태, 누적 사용 이력, 소모품 잔여량, 오류 상태를 통합 모니터링합니다. 자동 발주·정비 알림 및 peer group benchmark 분석을 제공합니다.
          </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"><Icons.Package size={13} /> 자동 발주 (2건 대기)</button>
        </div>
      </div>

      {/* Summary strip */}
      <div className="grid grid-4" style={{ marginBottom: 18 }}>
        <Card pad="lg">
          <Stat label="평균 가동률" value="48.7%" delta="+3.2pp" deltaSign="up" sub="Peer 평균 52.0%" />
        </Card>
        <Card pad="lg">
          <Stat label="당일 시술 건수" value="18" delta="+4" deltaSign="up" sub="장비 합계" />
        </Card>
        <Card pad="lg">
          <Stat label="자동 발주 대기" value="2" sub="Volnewmer Tip · Ultraformer 카트리지" />
        </Card>
        <Card pad="lg">
          <Stat label="저활용 장비 (peer -30%+)" value="2" deltaSign="down" sub="PicoSure · Volnewmer" />
        </Card>
      </div>

      <div className="grid grid-12">
        {/* LEFT — Device grid */}
        <div className="col-7">
          <Card pad="md" title="장비 인벤토리 (6)">
            <div className="grid grid-2">
              {DEVICES.map(d => (
                <button key={d.id} onClick={() => setSelected(d.id)}
                        style={{
                          textAlign: "left", padding: 14, borderRadius: 12,
                          background: selected === d.id ? "var(--bg-subtle)" : "var(--bg-surface)",
                          border: `1px solid ${selected === d.id ? "var(--ink-1)" : "var(--line-hair)"}`,
                          cursor: "pointer",
                          position: "relative",
                        }}>
                  <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 8 }}>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink-1)", letterSpacing: "-0.01em" }}>{d.name}</div>
                      <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{d.brand} · {d.category}</div>
                    </div>
                    <Pill tone={statusColor(d.status)} dot>{d.status}</Pill>
                  </div>

                  <div style={{ display: "flex", alignItems: "flex-end", gap: 8, marginTop: 10 }}>
                    <div style={{ flex: 1 }}>
                      <div className="stat-label" style={{ fontSize: 10 }}>가동률</div>
                      <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                        <span className="num" style={{ fontSize: 22, fontWeight: 700 }}>{d.utilization}</span>
                        <span style={{ fontSize: 10, color: "var(--ink-4)" }}>%</span>
                        <span className={`stat-delta ${d.utilization >= d.peer ? "up" : "down"}`} style={{ marginLeft: 6, fontSize: 10.5 }}>
                          {d.utilization >= d.peer ? "▲" : "▼"} peer {d.peer}
                        </span>
                      </div>
                    </div>
                    <MiniBars data={histMap[d.id]} w={120} h={36} color={d.utilization >= d.peer ? "var(--good)" : "var(--watch)"} />
                  </div>

                  <div className="divider" style={{ margin: "12px 0" }} />

                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5 }}>
                    <span style={{ color: "var(--ink-3)" }}>금주 {d.sessionsWeek}건 · 오늘 {d.sessionsToday}건</span>
                    <span style={{ color: d.consumable.remain < 0.2 ? "var(--alert)" : "var(--ink-3)" }}>
                      {d.consumable.name} <span className="num">{Math.round(d.consumable.remain * 100)}%</span>
                    </span>
                  </div>

                  {d.alert && (
                    <div style={{ marginTop: 10, padding: "6px 10px", background: "var(--alert-10)", borderRadius: 8, fontSize: 11, color: "var(--alert)", display: "flex", alignItems: "center", gap: 6 }}>
                      <Icons.Warn size={11} stroke="currentColor" />
                      {d.alert}
                    </div>
                  )}
                </button>
              ))}
            </div>
          </Card>
        </div>

        {/* RIGHT — Detail panel */}
        <div className="col-5" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Card pad="lg">
            <div className="card-title-row">
              <div>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em" }}>{dev.name}</h2>
                  <Pill tone={statusColor(dev.status)} dot>{dev.status}</Pill>
                </div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{dev.brand} · {dev.category} · ID {dev.id.toUpperCase()}</div>
              </div>
              <button className="btn btn-ghost btn-sm"><Icons.More size={14} /></button>
            </div>

            <div className="grid grid-3" style={{ marginTop: 14 }}>
              <Stat mini label="가동률" value={`${dev.utilization}%`} delta={`peer ${dev.peer}`} deltaSign={dev.utilization >= dev.peer ? "up" : "down"} />
              <Stat mini label="오늘 시술" value={`${dev.sessionsToday}건`} sub="평균 4.2건/일" />
              <Stat mini label="금주 시술" value={`${dev.sessionsWeek}건`} sub="목표 28건" />
            </div>

            <div className="divider" />

            <div className="stat-label" style={{ marginBottom: 8 }}>14일 가동률 추세</div>
            <LineChart data={histMap[dev.id]} w={460} h={130} color="var(--phase-tint)" yUnit="%" baseline={Array(14).fill(dev.peer)} />

            <div className="divider" />

            <div className="stat-label" style={{ marginBottom: 10 }}>소모품 상태</div>
            <div style={{ padding: 12, borderRadius: 10, background: "var(--bg-subtle)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{dev.consumable.name}</span>
                <span className="num" style={{ fontSize: 12, color: "var(--ink-3)" }}>잔여 {dev.consumable.units}개</span>
              </div>
              <div style={{ height: 10, background: "#FFF", borderRadius: 999, overflow: "hidden" }}>
                <div style={{ width: `${dev.consumable.remain * 100}%`, height: "100%",
                              background: dev.consumable.remain < 0.2 ? "var(--alert)" :
                                          dev.consumable.remain < 0.5 ? "var(--watch)" : "var(--good)",
                              borderRadius: 999, transition: "width 600ms" }}></div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 11.5, color: "var(--ink-3)" }}>
                <span>예상 소진 <span className="num" style={{ color: "var(--ink-1)", fontWeight: 600 }}>{Math.ceil(dev.consumable.units / Math.max(1, dev.sessionsWeek / 7))}일</span> 후</span>
                <button className="btn btn-soft btn-sm" style={{ height: 26, padding: "0 10px", fontSize: 11 }}>
                  <Icons.Plus size={11} /> 1-Click 발주
                </button>
              </div>
            </div>

            <div className="divider" />

            <div className="stat-label" style={{ marginBottom: 10 }}>AI 추천 · 활용도 개선</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <div style={{ display: "flex", gap: 10, padding: "10px 12px", background: "var(--bg-subtle)", borderRadius: 10 }}>
                <Icons.Sparkle size={16} stroke="var(--phase-tint)" />
                <div style={{ flex: 1, fontSize: 12.5 }}>
                  <div style={{ fontWeight: 600, color: "var(--ink-1)" }}>{dev.name} 적합 환자 24명 식별</div>
                  <div style={{ color: "var(--ink-3)", marginTop: 2 }}>지난 30일 진단 결과 기준 — 패키지 제안 시 예상 매출 +₩42M</div>
                </div>
                <button className="btn btn-soft btn-sm" style={{ alignSelf: "center" }}>리스트 보기</button>
              </div>
            </div>
          </Card>

          <Card pad="md" title="장비 포트폴리오 분석">
            <div className="stat-label" style={{ marginBottom: 10 }}>카테고리별 coverage</div>
            {[
              { c: "RF / MNRF", cov: 0.95, gap: "—" },
              { c: "HIFU / MRF", cov: 0.78, gap: "Microfocused MRF 부재" },
              { c: "Pico / Q-switch", cov: 0.62, gap: "Pico 활용도 -55%" },
              { c: "Vascular Laser", cov: 0.85, gap: "—" },
              { c: "Fractional Laser", cov: 0.88, gap: "—" },
              { c: "Body Contouring", cov: 0.20, gap: "Cryo · EMSculpt 미보유" },
            ].map((p, i) => (
              <div key={i} style={{ marginBottom: 10 }}>
                <CoverageGauge value={p.cov} label={p.c} color={p.cov >= 0.7 ? "var(--good)" : p.cov >= 0.4 ? "var(--watch)" : "var(--alert)"} />
                {p.gap !== "—" && <div style={{ fontSize: 10.5, color: "var(--ink-4)", marginTop: 2 }}>{p.gap}</div>}
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

window.DevicesScreen = DevicesScreen;
