// screens/bi.jsx — 클리닉 운영 BI Dashboard

function BIScreen() {
  const Icons = window.Icons;
  const [range, setRange] = React.useState("14d");
  const maxStaffAvg = Math.max(...STAFF.map(s => s.avg));

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">10 · 클리닉 운영 BI Dashboard</div>
          <h1 className="page-title">안양피부과 강남점 — 운영 KPI 통합</h1>
          <p className="page-sub">
            상담 전환율·객단가·재방문율·장비 utilization·package mix 등 핵심 운영 지표를 통합 관리하며 peer clinic 대비 benchmark를 제공합니다.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <Tabs tabs={[{v:"7d",l:"7일"},{v:"14d",l:"14일"},{v:"30d",l:"30일"},{v:"90d",l:"90일"}]} value={range} onChange={setRange} />
          <button className="btn btn-soft btn-sm"><Icons.Download size={13} /> 리포트</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="grid grid-4" style={{ marginBottom: 18 }}>
        {KPIS.map((k, i) => (
          <Card key={i} pad="lg">
            <Stat label={k.label} value={k.value} delta={k.delta} deltaSign={k.deltaSign} sub={k.sub} />
            <div style={{ marginTop: 12 }}>
              <Sparkline data={[42,44,41,45,48,46,50,52,49,53,55,52,57,60][i] ? WEEKLY_CONVERSION : WEEKLY_REVENUE}
                         color={i === 2 ? "var(--alert)" : "var(--phase-tint)"} w={220} h={36} />
            </div>
          </Card>
        ))}
      </div>

      <div className="grid grid-12">
        {/* Revenue trend */}
        <div className="col-8">
          <Card pad="lg" title="14일 매출 추세" action={
            <div style={{ display: "flex", gap: 8 }}>
              <Pill tone="info"><span className="dot"></span>실측</Pill>
              <Pill tone="outline"><span className="dot"></span>목표 라인</Pill>
            </div>
          }>
            <div style={{ display: "flex", alignItems: "baseline", gap: 16, marginBottom: 10 }}>
              <div>
                <div className="num" style={{ fontSize: 28, fontWeight: 700 }}>₩238M</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>14일 누적 · <span style={{ color: "var(--good)" }}>▲ 12.4%</span> vs 전기간</div>
              </div>
              <div style={{ marginLeft: "auto", display: "flex", gap: 14, fontSize: 12 }}>
                <div><div className="num" style={{ fontSize: 18, fontWeight: 600 }}>₩17.0M</div><div style={{ color: "var(--ink-4)", fontSize: 11 }}>일평균</div></div>
                <div><div className="num" style={{ fontSize: 18, fontWeight: 600 }}>₩1.42M</div><div style={{ color: "var(--ink-4)", fontSize: 11 }}>객단가</div></div>
                <div><div className="num" style={{ fontSize: 18, fontWeight: 600 }}>62.4%</div><div style={{ color: "var(--ink-4)", fontSize: 11 }}>전환율</div></div>
              </div>
            </div>
            <div style={{ width: "100%" }}>
              <LineChart data={WEEKLY_REVENUE} w={760} h={220} color="var(--phase-tint)" yUnit="M"
                         baseline={WEEKLY_REVENUE.map(() => 16)} />
            </div>
          </Card>

          {/* Staff perf */}
          <Card pad="lg" style={{ marginTop: 16 }} title="실장별 성과 (당월)">
            <table className="table">
              <thead>
                <tr>
                  <th>실장</th>
                  <th style={{ width: 90 }}>상담</th>
                  <th>전환율</th>
                  <th>객단가</th>
                  <th style={{ width: 80 }}>만족도</th>
                  <th style={{ width: 80 }}>패키지 전환</th>
                </tr>
              </thead>
              <tbody>
                {STAFF.map((s, i) => (
                  <tr key={s.name}>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <Avatar initials={s.name.slice(0,1)} size={32} color={s.color} />
                        <div>
                          <div style={{ fontWeight: 600 }}>{s.name}</div>
                          <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{s.role}</div>
                        </div>
                      </div>
                    </td>
                    <td className="num">{s.consults}건</td>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{ flex: 1, height: 6, background: "var(--bg-subtle)", borderRadius: 999, overflow: "hidden", maxWidth: 140 }}>
                          <div style={{ width: `${s.conv * 100}%`, height: "100%", background: s.color, borderRadius: 999 }}></div>
                        </div>
                        <span className="num" style={{ fontWeight: 600, fontSize: 12.5 }}>{Math.round(s.conv * 100)}%</span>
                      </div>
                    </td>
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{ flex: 1, height: 6, background: "var(--bg-subtle)", borderRadius: 999, overflow: "hidden", maxWidth: 140 }}>
                          <div style={{ width: `${(s.avg / maxStaffAvg) * 100}%`, height: "100%", background: s.color, opacity: 0.5, borderRadius: 999 }}></div>
                        </div>
                        <span className="num" style={{ fontWeight: 600, fontSize: 12.5 }}>₩{(s.avg/10000).toFixed(0)}만</span>
                      </div>
                    </td>
                    <td>
                      <span className="num" style={{ fontWeight: 600 }}>{s.sat.toFixed(1)}</span>
                      <span style={{ fontSize: 10, color: "var(--ink-4)", marginLeft: 3 }}>/5</span>
                    </td>
                    <td className="num">{Math.round(s.conv * s.consults * 0.6)}건</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>

        {/* RIGHT — Package mix, peer compare, funnel */}
        <div className="col-4" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card pad="lg" title="Package Mix (당월)">
            <div style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 4 }}>
              {/* Stacked pie via SVG */}
              <svg width="120" height="120" viewBox="0 0 36 36">
                {(() => {
                  const data = [
                    { v: 0.42, c: "var(--phase-tint)" },
                    { v: 0.28, c: "var(--data-teal)" },
                    { v: 0.18, c: "var(--data-violet)" },
                    { v: 0.08, c: "var(--data-amber)" },
                    { v: 0.04, c: "var(--ink-3)" },
                  ];
                  let acc = 0;
                  return data.map((d, i) => {
                    const start = acc * 100;
                    acc += d.v;
                    return (
                      <circle key={i} cx="18" cy="18" r="15" fill="none"
                              stroke={d.c} strokeWidth="6"
                              strokeDasharray={`${d.v * 94.25} 94.25`}
                              strokeDashoffset={-(start * 0.9425)}
                              transform="rotate(-90 18 18)" />
                    );
                  });
                })()}
                <text x="18" y="18" textAnchor="middle" fontSize="3.8" fontWeight="700" fill="var(--ink-1)" fontFamily="var(--font-num)">142</text>
                <text x="18" y="22.5" textAnchor="middle" fontSize="2.2" fill="var(--ink-3)" fontFamily="var(--font-kr)">패키지</text>
              </svg>
              <div style={{ flex: 1 }}>
                {[
                  { l: "Pore Control", v: 42, c: "var(--phase-tint)" },
                  { l: "Anti-aging", v: 28, c: "var(--data-teal)" },
                  { l: "Acne Care", v: 18, c: "var(--data-violet)" },
                  { l: "Pigment", v: 8, c: "var(--data-amber)" },
                  { l: "기타", v: 4, c: "var(--ink-3)" },
                ].map((d, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, padding: "3px 0" }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: d.c }}></span>
                    <span style={{ flex: 1, color: "var(--ink-2)" }}>{d.l}</span>
                    <span className="num" style={{ fontWeight: 600 }}>{d.v}%</span>
                  </div>
                ))}
              </div>
            </div>
          </Card>

          <Card pad="lg" title="Peer Clinic Benchmark">
            <div className="stat-label">강남구 동급 클리닉 8개 평균 대비</div>
            <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                { l: "객단가", you: 142, peer: 128, unit: "만" },
                { l: "전환율", you: 62, peer: 54, unit: "%" },
                { l: "재방문율", you: 48, peer: 41, unit: "%" },
                { l: "패키지 mix", you: 58, peer: 46, unit: "%" },
                { l: "장비 가동률", you: 49, peer: 52, unit: "%" },
              ].map((b, i) => {
                const isBetter = b.you >= b.peer;
                return (
                  <div key={i}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 4 }}>
                      <span style={{ fontWeight: 500 }}>{b.l}</span>
                      <span>
                        <span className="num" style={{ fontWeight: 600 }}>{b.you}{b.unit}</span>
                        <span className={`num stat-delta ${isBetter ? "up" : "down"}`} style={{ marginLeft: 8 }}>
                          {isBetter ? "▲" : "▼"} {Math.abs(b.you - b.peer)}{b.unit}
                        </span>
                      </span>
                    </div>
                    <div style={{ position: "relative", height: 6, background: "var(--bg-subtle)", borderRadius: 999 }}>
                      <div style={{ position: "absolute", inset: 0, left: 0, width: `${Math.min(100, (b.you / (b.you + b.peer)) * 100)}%`, background: isBetter ? "var(--good)" : "var(--watch)", borderRadius: 999 }}></div>
                      <div style={{ position: "absolute", top: -1, bottom: -1, left: `${(b.peer / (b.you + b.peer)) * 100}%`, width: 2, background: "var(--ink-2)" }}></div>
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>

          <Card pad="lg" title="상담 → 전환 Funnel (당월)">
            {[
              { l: "내원", v: 348, pct: 1.0, color: "var(--ink-2)" },
              { l: "상담 진행", v: 312, pct: 0.90, color: "var(--data-blue)" },
              { l: "패키지 제안", v: 246, pct: 0.71, color: "var(--data-teal)" },
              { l: "전환 (결제)", v: 168, pct: 0.48, color: "var(--good)" },
              { l: "재방문 (30일)", v: 80, pct: 0.23, color: "var(--phase-tint)" },
            ].map((s, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0" }}>
                <span style={{ width: 80, fontSize: 12, fontWeight: 500 }}>{s.l}</span>
                <div style={{ flex: 1, height: 18, background: "var(--bg-subtle)", borderRadius: 6, overflow: "hidden", position: "relative" }}>
                  <div style={{ position: "absolute", inset: 0, width: `${s.pct * 100}%`, background: s.color, borderRadius: 6 }}></div>
                  <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", paddingLeft: 8, fontSize: 11, color: "#FFF", fontWeight: 600 }}>{Math.round(s.pct * 100)}%</div>
                </div>
                <span className="num" style={{ width: 50, textAlign: "right", fontWeight: 600 }}>{s.v}</span>
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

window.BIScreen = BIScreen;
