// ===== Teuanjai Radio — Player screens =====

// Top bar with member identity + live total time + logout
function TopBar({ memberName, totalMs, onLogout, subtitle }) {
  return (
    <div style={{ padding: "16px 18px 12px", display: "flex", alignItems: "center", gap: 12 }}>
      <div style={{ width: 42, height: 42, borderRadius: 14, flex: "0 0 auto", display: "grid", placeItems: "center",
        background: "linear-gradient(140deg, oklch(0.74 0.12 230), oklch(0.78 0.10 165))", color: "#fff",
        boxShadow: "0 8px 18px oklch(0.6 0.12 220 / 0.3)" }}>
        <Icon name="user" size={22} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11.5, color: "var(--ink-faint)", fontWeight: 600, marginBottom: 1 }}>{subtitle || "สวัสดี"}</div>
        <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{memberName}</div>
      </div>
      <div className="glass" style={{ borderRadius: 14, padding: "6px 11px", display: "flex", alignItems: "center", gap: 6 }}>
        <span style={{ color: "var(--accent)", display: "inline-flex" }}><Icon name="clock" size={15} /></span>
        <span style={{ fontFamily: "var(--font-disp)", fontWeight: 600, fontSize: 14, fontVariantNumeric: "tabular-nums", color: "var(--ink)" }}>{fmtClock(totalMs)}</span>
      </div>
      <button onClick={onLogout} aria-label="ออกจากระบบ" style={{ width: 42, height: 42, borderRadius: 14, display: "grid", placeItems: "center",
        background: "oklch(1 0 0 / 0.5)", border: "1px solid var(--glass-line)", color: "var(--ink-soft)" }}>
        <Icon name="logout" size={20} />
      </button>
    </div>
  );
}

function TrackRow({ track, accMs, isCurrent, isPlaying, onSelect }) {
  return (
    <button onClick={() => onSelect(track.id)} style={{
      width: "100%", display: "flex", alignItems: "center", gap: 14, padding: "10px 12px", borderRadius: 20,
      background: isCurrent ? "oklch(1 0 0 / 0.72)" : "oklch(1 0 0 / 0.32)",
      border: "1px solid " + (isCurrent ? "oklch(0.72 0.10 210 / 0.5)" : "oklch(1 0 0 / 0.45)"),
      boxShadow: isCurrent ? "0 10px 24px oklch(0.6 0.10 220 / 0.18)" : "none",
      textAlign: "left", transition: "all 0.25s",
    }}>
      <Cover track={track} size={52} radius={15} playing={isCurrent && isPlaying} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{track.title}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-faint)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{track.artist}</div>
      </div>
      <div style={{ textAlign: "right", flex: "0 0 auto" }}>
        {accMs > 0 ? (
          <div style={{ display: "flex", alignItems: "center", gap: 4, justifyContent: "flex-end", color: "var(--accent-3)" }}>
            <Icon name="clock" size={12} />
            <span style={{ fontSize: 12, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{fmtClock(accMs)}</span>
          </div>
        ) : track.live ? (
          <div style={{ display: "inline-flex", alignItems: "center", gap: 5, color: "oklch(0.55 0.16 25)" }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: "oklch(0.62 0.20 25)", animation: "livedot 1.4s ease-in-out infinite" }} />
            <span style={{ fontSize: 12, fontWeight: 700 }}>สด</span>
          </div>
        ) : (
          <span style={{ fontSize: 12, color: "var(--ink-faint)", fontVariantNumeric: "tabular-nums" }}>{fmtClock(track.sec*1000)}</span>
        )}
        <div style={{ marginTop: 4, height: 16, display: "flex", justifyContent: "flex-end", alignItems: "center" }}>
          {isCurrent
            ? <EQ playing={isPlaying} bars={4} h={14} w={2.5} gap={2.5} color="var(--accent)" />
            : <span style={{ fontSize: 11, color: "var(--ink-faint)" }}>{track.live ? "ฟังได้ตลอดวัน" : track.tag}</span>}
        </div>
      </div>
    </button>
  );
}

function LibraryView({ tracks, perTrackMs, currentTrackId, isPlaying, totalMs, onSelect, greeting, memberName, hasJoined }) {
  const greetGrad = greeting && greeting.icon === "moon"
    ? "linear-gradient(145deg, oklch(0.66 0.12 285), oklch(0.62 0.11 255))"
    : greeting && greeting.icon === "sunset"
    ? "linear-gradient(145deg, oklch(0.82 0.13 65), oklch(0.74 0.14 30))"
    : "linear-gradient(145deg, oklch(0.86 0.14 95), oklch(0.80 0.13 60))";
  const greetGlow = greeting && greeting.icon === "moon"
    ? "oklch(0.64 0.12 270 / 0.45)"
    : greeting && greeting.icon === "sunset"
    ? "oklch(0.76 0.14 45 / 0.5)"
    : "oklch(0.82 0.14 80 / 0.5)";
  return (
    <div className="scroll" style={{ flex: 1, padding: "4px 16px 160px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "8px 4px 22px" }}>
        <span style={{ width: 44, height: 44, borderRadius: "50%", flex: "0 0 auto", display: "grid", placeItems: "center", color: "#fff",
          position: "relative", background: greetGrad,
          boxShadow: "0 8px 22px " + greetGlow + ", inset 0 1px 2px rgba(255,255,255,.65), inset 0 -3px 6px oklch(0.4 0.1 60 / 0.12)" }}>
          <span style={{ position: "absolute", inset: 0, borderRadius: "50%", background: "radial-gradient(120% 80% at 32% 22%, rgba(255,255,255,.55), transparent 60%)" }} />
          <span style={{ position: "absolute", inset: -4, borderRadius: "50%", border: "1px solid oklch(1 0 0 / 0.45)", opacity: 0.7 }} />
          <Icon name={greeting ? greeting.icon : "sun"} size={21} stroke={2.1} />
        </span>
        <div style={{ lineHeight: 1.5 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ink)", letterSpacing: "-0.01em" }}>{greeting ? greeting.text : "สวัสดี"}</div>
          <div style={{ fontSize: 12.5, color: "var(--ink-faint)", marginTop: 1 }}>ยินดีต้อนรับกลับมา</div>
        </div>
      </div>

      <div className="glass" style={{ borderRadius: 22, padding: "18px 20px", marginBottom: 20,
        background: "linear-gradient(135deg, oklch(0.96 0.03 220 / 0.7), oklch(0.96 0.03 175 / 0.6))" }}>
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)", fontWeight: 600, marginBottom: 6 }}>เวลาเข้าร่วมสะสมวันนี้</div>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 10 }}>
          <div style={{ fontFamily: "var(--font-disp)", fontSize: 34, fontWeight: 700, lineHeight: 1, color: "var(--ink)", fontVariantNumeric: "tabular-nums" }}>{fmtClock(totalMs)}</div>
          <div style={{ fontSize: 12.5, fontWeight: 600, paddingBottom: 3, display: "inline-flex", alignItems: "center", gap: 6,
            color: hasJoined ? "oklch(0.55 0.14 160)" : "var(--ink-faint)" }}>
            {hasJoined && <span style={{ width: 7, height: 7, borderRadius: "50%", background: "oklch(0.62 0.18 150)", animation: isPlaying ? "livedot 1.4s ease-in-out infinite" : "none" }} />}
            {hasJoined ? "เข้าร่วมแล้วตอนนี้" : "ยังไม่ได้เข้าร่วมสตรีม"}
          </div>
        </div>
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "2px 4px 10px" }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: "var(--ink)" }}>รายการเสียง</div>
        <Chip>{tracks.length} รายการ</Chip>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {tracks.map((t) => (
          <TrackRow key={t.id} track={t} accMs={perTrackMs[t.id] || 0}
            isCurrent={t.id === currentTrackId} isPlaying={isPlaying} onSelect={onSelect} />
        ))}
      </div>
    </div>
  );
}

// Full Now-Playing screen
function NowPlayingView({ track, progress, posMs, isPlaying, accMs, onToggle, onNext, onPrev, onClose, muted, onToggleMute, live, streamError, streamLoading }) {
  if (!track) return null;
  const Disc = (
    <div style={{ position: "relative", width: 196, height: 196, borderRadius: "50%", overflow: "hidden",
      background: `linear-gradient(140deg, ${track.g[0]}, ${track.g[1]})`,
      boxShadow: "inset 0 2px 6px rgba(255,255,255,.5), 0 18px 40px oklch(0.6 0.1 220 / 0.3)",
      display: "grid", placeItems: "center", animation: isPlaying ? "spin 22s linear infinite" : "none" }}>
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(120% 80% at 30% 0%, rgba(255,255,255,.4), transparent 55%)" }} />
      <div style={{ width: 46, height: 46, borderRadius: "50%", background: "oklch(0.97 0.01 220)", boxShadow: "inset 0 0 0 4px rgba(255,255,255,.6)" }} />
    </div>
  );
  return (
    <div className="screen" style={{ padding: "10px 24px 120px", alignItems: "center" }}>
      <div style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "6px 0 4px" }}>
        <button onClick={onClose} aria-label="ย่อ" style={{ width: 40, height: 40, borderRadius: 13, display: "grid", placeItems: "center",
          background: "oklch(1 0 0 / 0.5)", border: "1px solid var(--glass-line)", color: "var(--ink-soft)" }}>
          <Icon name="chevron-down" size={22} />
        </button>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontSize: 11.5, color: "var(--ink-faint)", fontWeight: 600 }}>กำลังรับฟัง</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>{live ? "ถ่ายทอดสด" : track.tag}</div>
        </div>
        <button onClick={onToggleMute} aria-label={muted ? "เปิดเสียง" : "ปิดเสียง"} style={{ width: 40, height: 40, borderRadius: 13, display: "grid", placeItems: "center",
          background: muted ? "oklch(0.9 0.04 30 / 0.5)" : "oklch(1 0 0 / 0.5)", border: "1px solid var(--glass-line)", color: muted ? "oklch(0.6 0.12 30)" : "var(--ink-soft)" }}>
          <Icon name={muted ? "mute" : "volume"} size={20} />
        </button>
      </div>

      <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", width: "100%" }}>
        {live
          ? <LiveRing size={244} stroke={7} isPlaying={isPlaying}>{Disc}</LiveRing>
          : <ProgressRing progress={progress} size={244} stroke={7}>{Disc}</ProgressRing>}

        <h2 style={{ margin: "26px 0 4px", fontFamily: "var(--font-disp)", fontSize: 24, fontWeight: 700, color: "var(--ink)", textAlign: "center" }}>{track.title}</h2>
        <div style={{ fontSize: 14.5, color: "var(--ink-soft)" }}>{track.artist}</div>

        {live ? (
          <div style={{ marginTop: 22, display: "flex", flexDirection: "column", alignItems: "center", gap: 12 }}>
            <LivePill playing={isPlaying && !streamError} />
            {streamError ? (
              <div style={{ fontSize: 12.5, color: "oklch(0.55 0.15 30)", textAlign: "center", maxWidth: 280, lineHeight: 1.55 }}>
                เชื่อมต่อสตรีมไม่ได้ — หากเปิดบนหน้าเว็บแบบ https เบราว์เซอร์อาจบล็อกสตรีม (http) กรุณาเปิดผ่านลิงก์ http โดยตรง
              </div>
            ) : streamLoading && isPlaying ? (
              <div style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>กำลังเชื่อมต่อสตรีม…</div>
            ) : (
              <div style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>ออกอากาศต่อเนื่อง · ฟังได้ตลอดทั้งวัน</div>
            )}
          </div>
        ) : (
          <div style={{ width: "100%", marginTop: 22 }}>
            <Bar progress={progress} h={6} />
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 7, fontSize: 12, color: "var(--ink-faint)", fontVariantNumeric: "tabular-nums" }}>
              <span>{fmtClock(posMs)}</span>
              <span>{fmtClock(track.sec*1000)}</span>
            </div>
          </div>
        )}

        {/* accumulated badge */}
        <div className="glass" style={{ marginTop: 16, borderRadius: 14, padding: "8px 14px", display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ color: "var(--accent-3)", display: "inline-flex" }}><Icon name="clock" size={15} /></span>
          <span style={{ fontSize: 12.5, color: "var(--ink-soft)" }}>{live ? "เข้าร่วมสตรีมสะสม" : "ฟังคลิปนี้สะสม"}</span>
          <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", fontVariantNumeric: "tabular-nums" }}>{fmtClock(accMs)}</span>
        </div>

        {/* controls */}
        <div style={{ marginTop: 26, display: "flex", alignItems: "center", gap: 26 }}>
          {!live && <button onClick={onPrev} aria-label="ก่อนหน้า" style={ctrlGhost}><Icon name="prev" size={26} /></button>}
          <button onClick={onToggle} aria-label={isPlaying ? "หยุด" : "เล่น"} style={{ ...ctrlMain, animation: isPlaying ? "pulse 2.4s infinite" : "none" }}>
            <Icon name={isPlaying ? "pause" : "play"} size={30} />
          </button>
          {!live && <button onClick={onNext} aria-label="ถัดไป" style={ctrlGhost}><Icon name="next" size={26} /></button>}
        </div>
      </div>
    </div>
  );
}

// Mini player above bottom nav
function MiniPlayer({ track, progress, isPlaying, onToggle, onExpand, live }) {
  if (!track) return null;
  return (
    <div onClick={onExpand} style={{ position: "absolute", left: 12, right: 12, bottom: "calc(90px + env(safe-area-inset-bottom))", zIndex: 20,
      borderRadius: 20, overflow: "hidden", cursor: "pointer", animation: "slideUp 0.4s cubic-bezier(0.22,1,0.36,1)" }}>
      <div className="glass" style={{ borderRadius: 20, padding: "9px 10px", display: "flex", alignItems: "center", gap: 12 }}>
        <Cover track={track} size={44} radius={13} playing={isPlaying} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{track.title}</div>
          {live ? (
            <div style={{ marginTop: 4, display: "inline-flex", alignItems: "center", gap: 5, color: "oklch(0.55 0.16 25)" }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "oklch(0.62 0.20 25)", animation: isPlaying ? "livedot 1.4s ease-in-out infinite" : "none" }} />
              <span style={{ fontSize: 11.5, fontWeight: 700 }}>{isPlaying ? "กำลังถ่ายทอดสด" : "ถ่ายทอดสด · หยุดชั่วคราว"}</span>
            </div>
          ) : (
            <div style={{ marginTop: 5 }}><Bar progress={progress} h={3} /></div>
          )}
        </div>
        <button onClick={(e) => { e.stopPropagation(); onToggle(); }} aria-label={isPlaying ? "หยุด" : "เล่น"}
          style={{ width: 42, height: 42, borderRadius: "50%", flex: "0 0 auto", display: "grid", placeItems: "center", color: "#fff",
            background: "linear-gradient(120deg, var(--accent), var(--accent-2))", boxShadow: "0 6px 14px oklch(0.6 0.12 215 / 0.4)" }}>
          <Icon name={isPlaying ? "pause" : "play"} size={20} />
        </button>
      </div>
    </div>
  );
}

function BottomNav({ active, onNav }) {
  const items = [
    { id: "library", icon: "library", label: "ฟังเพลง" },
    { id: "history", icon: "clock", label: "ประวัติ" },
  ];
  return (
    <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, zIndex: 25, padding: "8px 16px calc(10px + env(safe-area-inset-bottom))" }}>
      <div className="glass" style={{ borderRadius: 22, padding: 6, display: "flex", gap: 6 }}>
        {items.map((it) => {
          const on = active === it.id;
          return (
            <button key={it.id} onClick={() => onNav(it.id)} style={{ flex: 1, height: 50, borderRadius: 16, display: "flex",
              alignItems: "center", justifyContent: "center", gap: 8, fontSize: 14, fontWeight: 600,
              color: on ? "#fff" : "var(--ink-soft)",
              background: on ? "linear-gradient(120deg, var(--accent), var(--accent-2))" : "transparent",
              boxShadow: on ? "0 8px 18px oklch(0.6 0.12 215 / 0.32)" : "none", transition: "all 0.25s" }}>
              <Icon name={it.icon} size={19} />{it.label}
            </button>
          );
        })}
      </div>
    </div>
  );
}

const ctrlGhost = { width: 56, height: 56, borderRadius: "50%", display: "grid", placeItems: "center", color: "var(--ink-soft)",
  background: "oklch(1 0 0 / 0.5)", border: "1px solid var(--glass-line)" };
const ctrlMain = { width: 76, height: 76, borderRadius: "50%", display: "grid", placeItems: "center", color: "#fff",
  background: "linear-gradient(120deg, oklch(0.66 0.13 232), oklch(0.72 0.12 190))",
  boxShadow: "0 16px 34px oklch(0.6 0.12 215 / 0.42), inset 0 1px 2px rgba(255,255,255,.4)" };

(function(){ if(document.getElementById("tj-spin"))return; const s=document.createElement("style"); s.id="tj-spin";
  s.textContent="@keyframes spin{from{transform:rotate(0)}to{transform:rotate(360deg)}}@media (prefers-reduced-motion: reduce){@keyframes spin{from{transform:none}to{transform:none}}}";
  document.head.appendChild(s); })();

Object.assign(window, { TopBar, LibraryView, NowPlayingView, MiniPlayer, BottomNav });
