// ui.jsx — Study WithU 공통 컴포넌트
// 모든 색은 CSS 토큰(var) 참조 → 다크 모드 자동 대응. hex 하드코딩 없음.

// ── 로고 ──────────────────────────────────────────────────
function Logo({ size = 22, mono = false }) {
  const ink = mono ? "currentColor" : "hsl(var(--primary))";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
      <span style={{ display: "inline-flex" }}>
        <svg width={size} height={size} viewBox="0 0 28 28" fill="none" aria-hidden="true">
          <path d="M9 5c1-2 0-3 0-4" stroke={ink} strokeWidth="2" strokeLinecap="round" opacity="0.8" />
          <path d="M15 5c1-2 0-3 0-4" stroke={ink} strokeWidth="2" strokeLinecap="round" opacity="0.8" />
          <path d="M5 11h16l-1.4 11.5A4 4 0 0 1 15.6 26H10.4a4 4 0 0 1-4-3.5z" fill={`hsl(var(--primary) / ${mono ? 0 : 0.14})`} stroke={ink} strokeWidth="2" strokeLinejoin="round" />
          <path d="M21 13c3 0 5 1.5 5 4.5S24 22 21 22" stroke={ink} strokeWidth="2" strokeLinecap="round" />
        </svg>
      </span>
      <span style={{ fontWeight: 800, fontSize: size * 0.82, letterSpacing: "-0.03em", color: "var(--c-fg)" }}>
        study<span style={{ color: ink }}>withu</span>
      </span>
    </span>
  );
}

// ── 버튼 ──────────────────────────────────────────────────
function Button({ children, variant = "primary", size = "md", icon, style, full }) {
  const sizes = {
    sm: { padding: "0 16px", height: 38, fontSize: 14 },
    md: { padding: "0 22px", height: 46, fontSize: 15.5 },
    lg: { padding: "0 30px", height: 56, fontSize: 17 },
  }[size];
  const variants = {
    primary: { background: "var(--c-primary)", color: "var(--c-primary-fg)", border: "1px solid transparent", boxShadow: "0 1px 2px hsl(var(--primary) / 0.3), 0 8px 20px hsl(var(--primary) / 0.22)" },
    secondary: { background: "var(--c-secondary)", color: "var(--c-secondary-fg)", border: "1px solid transparent", boxShadow: "0 6px 16px hsl(var(--secondary) / 0.2)" },
    ghost: { background: "transparent", color: "var(--c-fg)", border: "1px solid var(--c-border)" },
    soft: { background: "var(--c-accent)", color: "var(--accent-foreground, var(--c-fg))", border: "1px solid transparent" },
  }[variant];
  return (
    <button style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 9,
      borderRadius: "var(--r-btn)", fontFamily: "var(--font-sans)", fontWeight: 700,
      cursor: "pointer", whiteSpace: "nowrap", lineHeight: 1, transition: "transform .15s",
      width: full ? "100%" : "auto", ...sizes, ...variants, ...style,
    }}>
      {icon}{children}
    </button>
  );
}

// ── 배지 / pill ────────────────────────────────────────────
function Badge({ children, tone = "neutral", style }) {
  const tones = {
    neutral: { background: "var(--c-muted)", color: "var(--c-muted-fg)" },
    primary: { background: "hsl(var(--primary) / 0.12)", color: "var(--c-primary)" },
    secondary: { background: "hsl(var(--secondary) / 0.14)", color: "var(--c-secondary)" },
    success: { background: "hsl(var(--success) / 0.14)", color: "var(--c-success)" },
    warning: { background: "hsl(var(--warning) / 0.18)", color: "hsl(var(--warning))" },
    onPrimary: { background: "hsl(var(--primary-foreground) / 0.22)", color: "var(--c-primary-fg)" },
  }[tone];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6, borderRadius: "var(--r-pill)",
      padding: "5px 12px", fontSize: 13, fontWeight: 700, lineHeight: 1.1, whiteSpace: "nowrap", ...tones, ...style,
    }}>{children}</span>
  );
}

// ── 카드 ──────────────────────────────────────────────────
function Card({ children, variant = "default", style, pad = "var(--pad-card)" }) {
  const variants = {
    default: { background: "var(--c-card)", border: "1px solid var(--c-border)", boxShadow: "var(--shadow-card)" },
    highlight: { background: "var(--c-card)", border: "1.5px solid var(--c-primary)", boxShadow: "var(--shadow-lift)" },
    ghost: { background: "transparent", border: "1.5px dashed var(--c-border)", boxShadow: "none" },
    tinted: { background: "var(--c-accent)", border: "1px solid transparent", boxShadow: "none" },
  }[variant];
  return (
    <div style={{ borderRadius: "var(--r-card)", padding: pad, ...variants, ...style }}>{children}</div>
  );
}

// ── Stat (라벨 + 숫자 + 변화율) ────────────────────────────
function Stat({ label, value, unit, delta, deltaDir = "up", style }) {
  const col = deltaDir === "up" ? "var(--c-success)" : "var(--c-destructive)";
  return (
    <div style={style}>
      <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--c-muted-fg)", marginBottom: 8 }}>{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
        <span className="num" style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--c-fg)" }}>{value}</span>
        {unit && <span style={{ fontSize: 16, fontWeight: 600, color: "var(--c-muted-fg)" }}>{unit}</span>}
        {delta != null && (
          <span className="num" style={{ marginLeft: 4, fontSize: 14, fontWeight: 700, color: col, display: "inline-flex", alignItems: "center", gap: 2 }}>
            {deltaDir === "up" ? "▲" : "▼"}{delta}
          </span>
        )}
      </div>
    </div>
  );
}

// ── LiveCounter (ping 점 + 동시 사용자) ────────────────────
function LiveCounter({ n = 2483, style, compact }) {
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 10, borderRadius: "var(--r-pill)",
      padding: compact ? "8px 14px" : "10px 18px", background: "var(--c-card)",
      border: "1px solid var(--c-border)", boxShadow: "var(--shadow-card)", ...style,
    }}>
      <span style={{ position: "relative", display: "inline-flex", width: 9, height: 9 }}>
        <span style={{ position: "absolute", inset: 0, borderRadius: "50%", background: "var(--c-secondary)", opacity: 0.45, animation: "swuPing 1.8s cubic-bezier(0,0,.2,1) infinite" }} />
        <span style={{ position: "absolute", inset: 0, borderRadius: "50%", background: "var(--c-secondary)" }} />
      </span>
      <span style={{ fontSize: compact ? 13.5 : 15, fontWeight: 600, color: "var(--c-fg)", whiteSpace: "nowrap" }}>
        지금 <span className="num" style={{ fontWeight: 800, color: "var(--c-secondary)" }}>{n.toLocaleString()}</span>명 함께 공부 중
      </span>
    </span>
  );
}

// ── 주간 7바 그래프 ────────────────────────────────────────
function WeekBars({ data = [62, 88, 40, 95, 70, 100, 30], days = ["월","화","수","목","금","토","일"], todayIdx = 5, barH = 72, fontSize = 12, style }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 10, ...style }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
          <div style={{ width: "100%", height: barH, display: "flex", alignItems: "flex-end" }}>
            <div style={{
              width: "100%", height: `${v}%`, borderRadius: 7,
              background: i === todayIdx ? "var(--c-primary)" : "hsl(var(--primary) / 0.18)",
              boxShadow: i === todayIdx ? "0 4px 12px hsl(var(--primary) / 0.3)" : "none",
            }} />
          </div>
          <span style={{ fontSize, fontWeight: 600, color: i === todayIdx ? "var(--c-primary)" : "var(--c-muted-fg)" }}>{days[i]}</span>
        </div>
      ))}
    </div>
  );
}

// ── FocusCard (연속일 + 오늘 집중 + 주간 그래프) ───────────
function FocusCard({ style }) {
  return (
    <Card style={{ ...style }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 22 }}>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--c-muted-fg)", marginBottom: 8 }}>오늘 집중 시간</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 4, whiteSpace: "nowrap" }}>
            <span className="num" style={{ fontSize: 46, fontWeight: 700, letterSpacing: "-0.03em", lineHeight: 1 }}>4</span>
            <span style={{ fontSize: 20, fontWeight: 600, color: "var(--c-muted-fg)", marginRight: 4 }}>시간</span>
            <span className="num" style={{ fontSize: 46, fontWeight: 700, letterSpacing: "-0.03em", lineHeight: 1 }}>12</span>
            <span style={{ fontSize: 20, fontWeight: 600, color: "var(--c-muted-fg)" }}>분</span>
          </div>
        </div>
        <Badge tone="warning" style={{ fontSize: 13 }}>🔥 12일 연속</Badge>
      </div>
      <WeekBars />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 22, paddingTop: 20, borderTop: "1px solid var(--c-border)" }}>
        <span style={{ fontSize: 14, color: "var(--c-muted-fg)", whiteSpace: "nowrap" }}>이번 주 누적</span>
        <span className="num" style={{ fontSize: 17, fontWeight: 700, whiteSpace: "nowrap" }}>26시간 48분 <span style={{ color: "var(--c-success)", fontSize: 14 }}>▲ 18%</span></span>
      </div>
    </Card>
  );
}

// ── EmptyState (일러스트 + 메시지 + CTA) ───────────────────
function EmptyState({ illust, title, desc, action, sub, style }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", padding: "8px 24px", ...style }}>
      <div style={{ marginBottom: 18 }}>{illust}</div>
      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 8 }}>{title}</div>
      <div style={{ fontSize: 15.5, color: "var(--c-muted-fg)", lineHeight: 1.55, maxWidth: 380, marginBottom: 22, textWrap: "pretty" }}>{desc}</div>
      <div style={{ display: "flex", gap: 10, alignItems: "center" }}>{action}{sub}</div>
    </div>
  );
}

// ── 아바타 (이니셜) ────────────────────────────────────────
function Avatar({ label = "U", tone = "primary", size = 36 }) {
  const tones = {
    primary: { background: "hsl(var(--primary) / 0.16)", color: "var(--c-primary)" },
    secondary: { background: "hsl(var(--secondary) / 0.18)", color: "var(--c-secondary)" },
    muted: { background: "var(--c-muted)", color: "var(--c-muted-fg)" },
  }[tone];
  return (
    <span style={{ width: size, height: size, borderRadius: "50%", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: size * 0.4, ...tones }}>{label}</span>
  );
}

// ── 토글 스위치 ────────────────────────────────────────────
function Toggle({ on = false }) {
  return (
    <span style={{
      width: 50, height: 30, borderRadius: 999, padding: 3, display: "inline-flex",
      background: on ? "var(--c-primary)" : "var(--c-muted)", transition: "background .2s", flexShrink: 0,
    }}>
      <span style={{ width: 24, height: 24, borderRadius: "50%", background: "#fff", boxShadow: "0 1px 3px rgb(0 0 0 / 0.2)", marginLeft: on ? 20 : 0, transition: "margin .2s" }} />
    </span>
  );
}

// ── 세그먼트 컨트롤 ────────────────────────────────────────
function SegTabs({ items, active = 0 }) {
  return (
    <div style={{ display: "inline-flex", gap: 2, padding: 4, background: "var(--c-muted)", borderRadius: "var(--r-pill)" }}>
      {items.map((it, i) => (
        <span key={it} style={{
          padding: "8px 18px", borderRadius: "var(--r-pill)", fontSize: 14.5, fontWeight: 700, cursor: "pointer", whiteSpace: "nowrap",
          color: i === active ? "var(--c-fg)" : "var(--c-muted-fg)",
          background: i === active ? "var(--c-card)" : "transparent",
          boxShadow: i === active ? "var(--shadow-card)" : "none",
        }}>{it}</span>
      ))}
    </div>
  );
}

// ── 테마 토글 (라이트/다크/시스템) ─────────────────────────
function ThemeToggle({ value = "light", onChange }) {
  const opts = [
    ["light", <svg key="s" width="17" height="17" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><circle cx="9" cy="9" r="3.4"/><path d="M9 1.5v2M9 14.5v2M1.5 9h2M14.5 9h2M3.7 3.7l1.4 1.4M12.9 12.9l1.4 1.4M14.3 3.7l-1.4 1.4M5.1 12.9l-1.4 1.4"/></svg>, "라이트"],
    ["dark", <svg key="m" width="17" height="17" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M15 10.5A6.5 6.5 0 0 1 7.5 3a6.5 6.5 0 1 0 7.5 7.5z"/></svg>, "다크"],
    ["system", <svg key="y" width="17" height="17" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2.5" y="3" width="13" height="9" rx="1.5"/><path d="M6.5 15.5h5M9 12.5v3"/></svg>, "시스템"],
  ];
  return (
    <span style={{ display: "inline-flex", gap: 2, padding: 3, borderRadius: "var(--r-pill)", background: "var(--c-muted)", border: "1px solid var(--c-border)" }}>
      {opts.map(([key, icon, label]) => {
        const on = value === key;
        return (
          <button key={key} title={label} onClick={onChange ? () => onChange(key) : undefined} style={{
            width: 32, height: 32, borderRadius: "var(--r-pill)", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", border: "none",
            background: on ? "var(--c-card)" : "transparent", color: on ? "var(--c-primary)" : "var(--c-muted-fg)",
            boxShadow: on ? "var(--shadow-card)" : "none",
          }}>{icon}</button>
        );
      })}
    </span>
  );
}

Object.assign(window, { Logo, Button, Badge, Card, Stat, LiveCounter, WeekBars, FocusCard, EmptyState, Avatar, Toggle, SegTabs, ThemeToggle });
