// ===== Teuanjai Radio — History / Summary =====

function StatCard({ label, value, icon, accent }) {
  return (
    <div className="glass" style={{ borderRadius: 18, padding: "14px 14px", flex: 1, minWidth: 0 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 7, color: accent || "var(--accent)", marginBottom: 8 }}>
        <Icon name={icon} size={16} />
        <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--ink-faint)" }}>{label}</span>
      </div>
      <div style={{ fontFamily: "var(--font-disp)", fontSize: 19, fontWeight: 700, color: "var(--ink)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{value}</div>
    </div>
  );
}

function HistoryView({ session, totalMs, perTrackMs, log, sessionMs, joinCount }) {
  const ranked = TRACKS
    .map((t) => ({ t, ms: perTrackMs[t.id] || 0 }))
    .filter((x) => x.ms > 0)
    .sort((a, b) => b.ms - a.ms);
  const maxMs = ranked.length ? ranked[0].ms : 1;

  return (
    <div className="scroll" style={{ flex: 1, padding: "4px 16px 160px" }}>
      {/* hero summary */}
      <div className="glass" style={{ borderRadius: 24, padding: "20px 20px",
        background: "linear-gradient(140deg, oklch(0.95 0.04 230 / 0.78), oklch(0.95 0.04 165 / 0.66))", marginBottom: 14 }}>
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)", fontWeight: 600 }}>เวลาเข้าร่วมกิจกรรมรวม</div>
        <div style={{ fontFamily: "var(--font-disp)", fontSize: 42, fontWeight: 700, lineHeight: 1.05, color: "var(--ink)", fontVariantNumeric: "tabular-nums", margin: "4px 0 2px" }}>{fmtClock(totalMs)}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>{fmtThaiDuration(totalMs)} · ฟังจริงขณะเปิดเล่น</div>
      </div>

      {/* check in/out */}
      <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
        <StatCard label="เช็คอิน" value={fmtTimeOnly(session.checkInTime)} icon="check" accent="var(--accent-3)" />
        <StatCard label="อยู่ในระบบ" value={fmtClock(sessionMs)} icon="clock" />
      </div>

      {/* per-track breakdown */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "4px 4px 10px" }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: "var(--ink)" }}>เวลาเข้าร่วมสตรีม</div>
        <Chip>เข้าฟัง {joinCount || 0} ครั้ง</Chip>
      </div>

      {ranked.length === 0 ? (
        <div className="glass" style={{ borderRadius: 18, padding: "22px 16px", textAlign: "center", color: "var(--ink-faint)", fontSize: 13.5 }}>
          ยังไม่มีการฟัง — กลับไปที่หน้า “ฟังเพลง” เพื่อเริ่มบันทึกเวลา
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {ranked.map(({ t, ms }) => (
            <div key={t.id} className="glass" style={{ borderRadius: 18, padding: "10px 12px", display: "flex", alignItems: "center", gap: 12 }}>
              <Cover track={t} size={44} radius={13} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", justifyContent: "space-between", gap: 8, marginBottom: 7 }}>
                  <span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.title}</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: "var(--accent-deep)", fontVariantNumeric: "tabular-nums", flex: "0 0 auto" }}>{fmtClock(ms)}</span>
                </div>
                <Bar progress={ms / maxMs} h={5} />
              </div>
            </div>
          ))}
        </div>
      )}

      {/* activity log */}
      <div style={{ padding: "20px 4px 10px", fontSize: 15, fontWeight: 700, color: "var(--ink)" }}>บันทึกการเข้าชม</div>
      <div className="glass" style={{ borderRadius: 20, padding: "6px 0" }}>
        {log.slice().reverse().slice(0, 12).map((e, i, arr) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px",
            borderBottom: i < arr.length - 1 ? "1px solid oklch(0.6 0.02 250 / 0.1)" : "none" }}>
            <span style={{ width: 30, height: 30, borderRadius: 10, flex: "0 0 auto", display: "grid", placeItems: "center",
              color: logMeta(e.type).color, background: logMeta(e.type).bg }}>
              <Icon name={logMeta(e.type).icon} size={15} />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{logLabel(e)}</div>
            </div>
            <span style={{ fontSize: 12, color: "var(--ink-faint)", fontVariantNumeric: "tabular-nums", flex: "0 0 auto" }}>{fmtTimeOnly(e.time)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function logMeta(type) {
  switch (type) {
    case "checkin": return { icon: "check", color: "var(--accent-3)", bg: "oklch(0.9 0.06 165 / 0.5)" };
    case "play":    return { icon: "play",  color: "var(--accent)",   bg: "oklch(0.9 0.06 220 / 0.5)" };
    case "pause":   return { icon: "pause", color: "var(--ink-faint)",bg: "oklch(0.92 0.01 250 / 0.6)" };
    case "checkout":return { icon: "logout",color: "var(--accent-deep)",bg: "oklch(0.9 0.06 200 / 0.5)" };
    default:        return { icon: "dot",   color: "var(--ink-faint)",bg: "oklch(0.92 0.01 250 / 0.6)" };
  }
}
function logLabel(e) {
  const t = e.trackId ? trackById(e.trackId) : null;
  switch (e.type) {
    case "checkin":  return "เช็คอินเข้าร่วมกิจกรรม";
    case "play":     return "เริ่มเล่น · " + (t ? t.title : "");
    case "pause":    return "หยุดเล่น · " + (t ? t.title : "");
    case "checkout": return "เช็คเอาท์ออกจากระบบ";
    default:         return e.type;
  }
}

// Logout confirmation / summary modal
function LogoutSummary({ session, totalMs, sessionMs, perTrackMs, onConfirm, onCancel }) {
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 60, display: "flex", flexDirection: "column", justifyContent: "flex-end",
      background: "oklch(0.4 0.04 250 / 0.34)", backdropFilter: "blur(4px)", animation: "fadeIn 0.3s both" }}>
      <div onClick={onCancel} style={{ flex: 1 }} />
      <div className="glass" style={{ borderRadius: "28px 28px 0 0", padding: "10px 22px calc(22px + env(safe-area-inset-bottom))",
        background: "oklch(0.98 0.012 220 / 0.82)", animation: "slideUp 0.4s cubic-bezier(0.22,1,0.36,1)" }}>
        <div style={{ width: 44, height: 5, borderRadius: 5, background: "oklch(0.7 0.02 250 / 0.3)", margin: "4px auto 18px" }} />
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
          <div style={{ width: 48, height: 48, borderRadius: 15, display: "grid", placeItems: "center", color: "#fff", flex: "0 0 auto",
            background: "linear-gradient(140deg, var(--accent), var(--accent-3))" }}><Icon name="check" size={26} /></div>
          <div>
            <div style={{ fontFamily: "var(--font-disp)", fontSize: 19, fontWeight: 700, color: "var(--ink)" }}>สรุปการเข้าร่วม</div>
            <div style={{ fontSize: 13, color: "var(--ink-soft)" }}>{session.memberName}</div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
          <SummaryStat label="เวลาฟังรวม" value={fmtClock(totalMs)} />
          <SummaryStat label="อยู่ในระบบ" value={fmtClock(sessionMs)} />
          <SummaryStat label="เช็คอิน" value={fmtTimeOnly(session.checkInTime)} />
          <SummaryStat label="เช็คเอาท์" value={fmtTimeOnly(Date.now())} />
        </div>
        <div style={{ textAlign: "center", fontSize: 12.5, color: "var(--ink-faint)", margin: "6px 0 18px" }}>เข้าร่วมสตรีม · {fmtThaiDuration(totalMs)}</div>

        <button onClick={onConfirm} style={btnPrimary}>ยืนยันออกจากระบบ</button>
        <button onClick={onCancel} style={{ ...btnGhost, marginTop: 10 }}>กลับไปฟังต่อ</button>
      </div>
    </div>
  );
}
function SummaryStat({ label, value }) {
  return (
    <div style={{ background: "oklch(1 0 0 / 0.55)", border: "1px solid var(--glass-line)", borderRadius: 14, padding: "10px 12px" }}>
      <div style={{ fontSize: 11.5, color: "var(--ink-faint)", fontWeight: 600, marginBottom: 3 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-disp)", fontSize: 18, fontWeight: 700, color: "var(--ink)", fontVariantNumeric: "tabular-nums" }}>{value}</div>
    </div>
  );
}

(function(){ if(document.getElementById("tj-fade"))return; const s=document.createElement("style"); s.id="tj-fade";
  s.textContent="@keyframes fadeIn{from{opacity:0}to{opacity:1}}";
  document.head.appendChild(s); })();

Object.assign(window, { HistoryView, LogoutSummary });
