Added checks to ensure OAuth response is from Twitch and not Supabase magic links.
3168 lines
105 KiB
HTML
3168 lines
105 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>STREAM LOG // Personal Game Tracker</title>
|
||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||
<link href="https://fonts.googleapis.com/css2?family=VT323&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
|
||
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
|
||
<style>
|
||
:root {
|
||
--bg: #0e0f12;
|
||
--bg-elev: #15171c;
|
||
--bg-elev-2: #1c1f26;
|
||
--border: #2a2e38;
|
||
--text: #e6e7ea;
|
||
--text-dim: #8a8f9c;
|
||
--text-faint: #525762;
|
||
--phosphor: #7cff6b;
|
||
--phosphor-dim: #3d7a35;
|
||
--amber: #ffb43b;
|
||
--amber-dim: #7a5218;
|
||
--red: #ff5b5b;
|
||
--blue: #5bb8ff;
|
||
--purple: #c77cff;
|
||
--font-display: 'VT323', monospace;
|
||
--font-body: 'JetBrains Mono', ui-monospace, monospace;
|
||
}
|
||
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
|
||
html, body {
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
font-family: var(--font-body);
|
||
font-size: 14px;
|
||
line-height: 1.5;
|
||
min-height: 100vh;
|
||
overflow-x: hidden;
|
||
}
|
||
|
||
/* CRT scanline overlay */
|
||
body::before {
|
||
content: '';
|
||
position: fixed;
|
||
inset: 0;
|
||
background: repeating-linear-gradient(
|
||
0deg,
|
||
rgba(0,0,0,0.15) 0px,
|
||
rgba(0,0,0,0.15) 1px,
|
||
transparent 1px,
|
||
transparent 3px
|
||
);
|
||
pointer-events: none;
|
||
z-index: 9999;
|
||
opacity: 0.35;
|
||
}
|
||
|
||
/* Subtle vignette */
|
||
body::after {
|
||
content: '';
|
||
position: fixed;
|
||
inset: 0;
|
||
background: radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.45) 100%);
|
||
pointer-events: none;
|
||
z-index: 9998;
|
||
}
|
||
|
||
.app {
|
||
max-width: 1400px;
|
||
margin: 0 auto;
|
||
padding: 32px 24px 80px;
|
||
position: relative;
|
||
z-index: 1;
|
||
}
|
||
|
||
/* === HEADER === */
|
||
header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: flex-end;
|
||
padding-bottom: 24px;
|
||
margin-bottom: 32px;
|
||
border-bottom: 1px dashed var(--border);
|
||
gap: 24px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
.brand h1 {
|
||
font-family: var(--font-display);
|
||
font-size: 64px;
|
||
line-height: 0.9;
|
||
color: var(--phosphor);
|
||
text-shadow: 0 0 8px rgba(124, 255, 107, 0.4), 0 0 20px rgba(124, 255, 107, 0.15);
|
||
letter-spacing: 2px;
|
||
}
|
||
|
||
.brand .blink::after {
|
||
content: '_';
|
||
animation: blink 1s steps(2, start) infinite;
|
||
}
|
||
|
||
@keyframes blink { to { visibility: hidden; } }
|
||
|
||
.brand p {
|
||
font-size: 11px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 3px;
|
||
text-transform: uppercase;
|
||
margin-top: 4px;
|
||
}
|
||
|
||
.header-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
align-items: center;
|
||
}
|
||
|
||
.conn-status {
|
||
font-size: 10px;
|
||
padding: 6px 10px;
|
||
border: 1px solid var(--border);
|
||
background: var(--bg-elev);
|
||
color: var(--text-dim);
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
}
|
||
|
||
.conn-dot {
|
||
width: 8px; height: 8px;
|
||
border-radius: 50%;
|
||
background: var(--red);
|
||
box-shadow: 0 0 6px currentColor;
|
||
}
|
||
.conn-status.ok .conn-dot { background: var(--phosphor); }
|
||
|
||
/* === BUTTONS === */
|
||
.btn {
|
||
font-family: var(--font-body);
|
||
font-size: 12px;
|
||
font-weight: 500;
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
padding: 10px 18px;
|
||
border: 1px solid var(--border);
|
||
background: var(--bg-elev);
|
||
color: var(--text);
|
||
cursor: pointer;
|
||
transition: all 0.15s ease;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
}
|
||
.btn:hover {
|
||
border-color: var(--phosphor);
|
||
color: var(--phosphor);
|
||
box-shadow: 0 0 12px rgba(124,255,107,0.15), inset 0 0 12px rgba(124,255,107,0.05);
|
||
}
|
||
.btn-primary {
|
||
background: var(--phosphor);
|
||
color: var(--bg);
|
||
border-color: var(--phosphor);
|
||
font-weight: 700;
|
||
}
|
||
.btn-primary:hover {
|
||
background: #9dff8c;
|
||
color: var(--bg);
|
||
box-shadow: 0 0 20px rgba(124,255,107,0.5);
|
||
}
|
||
.btn-danger:hover { border-color: var(--red); color: var(--red); box-shadow: 0 0 12px rgba(255,91,91,0.2); }
|
||
.btn-ghost { background: transparent; }
|
||
.btn-sm { padding: 6px 10px; font-size: 10px; }
|
||
|
||
/* === STATS DASHBOARD === */
|
||
.stats {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||
gap: 2px;
|
||
margin-bottom: 32px;
|
||
background: var(--border);
|
||
border: 1px solid var(--border);
|
||
}
|
||
.stat {
|
||
background: var(--bg-elev);
|
||
padding: 20px;
|
||
position: relative;
|
||
}
|
||
.stat-label {
|
||
font-size: 10px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 2px;
|
||
text-transform: uppercase;
|
||
margin-bottom: 8px;
|
||
}
|
||
.stat-value {
|
||
font-family: var(--font-display);
|
||
font-size: 44px;
|
||
line-height: 1;
|
||
color: var(--phosphor);
|
||
text-shadow: 0 0 6px rgba(124,255,107,0.3);
|
||
}
|
||
.stat-value.amber { color: var(--amber); text-shadow: 0 0 6px rgba(255,180,59,0.3); }
|
||
.stat-value.blue { color: var(--blue); text-shadow: 0 0 6px rgba(91,184,255,0.3); }
|
||
.stat-value.purple { color: var(--purple); text-shadow: 0 0 6px rgba(199,124,255,0.3); }
|
||
.stat-sub {
|
||
font-size: 10px;
|
||
color: var(--text-dim);
|
||
margin-top: 4px;
|
||
letter-spacing: 1px;
|
||
}
|
||
|
||
/* === TOOLBAR === */
|
||
.toolbar {
|
||
display: flex;
|
||
gap: 12px;
|
||
margin-bottom: 20px;
|
||
flex-wrap: wrap;
|
||
align-items: center;
|
||
}
|
||
.search {
|
||
flex: 1;
|
||
min-width: 220px;
|
||
position: relative;
|
||
}
|
||
.search input {
|
||
width: 100%;
|
||
background: var(--bg-elev);
|
||
border: 1px solid var(--border);
|
||
color: var(--text);
|
||
font-family: var(--font-body);
|
||
font-size: 13px;
|
||
padding: 10px 14px 10px 36px;
|
||
letter-spacing: 0.5px;
|
||
}
|
||
.search input:focus {
|
||
outline: none;
|
||
border-color: var(--phosphor);
|
||
box-shadow: 0 0 0 1px var(--phosphor), 0 0 12px rgba(124,255,107,0.15);
|
||
}
|
||
.search::before {
|
||
content: '>';
|
||
position: absolute;
|
||
left: 14px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
color: var(--phosphor);
|
||
font-family: var(--font-display);
|
||
font-size: 18px;
|
||
}
|
||
select.filter {
|
||
background: var(--bg-elev);
|
||
border: 1px solid var(--border);
|
||
color: var(--text);
|
||
font-family: var(--font-body);
|
||
font-size: 12px;
|
||
padding: 10px 14px;
|
||
letter-spacing: 1px;
|
||
text-transform: uppercase;
|
||
cursor: pointer;
|
||
}
|
||
select.filter:focus { outline: none; border-color: var(--phosphor); }
|
||
|
||
/* === STATUS FILTER PILLS === */
|
||
.status-filter {
|
||
display: flex;
|
||
gap: 6px;
|
||
margin-bottom: 20px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.pill {
|
||
font-size: 10px;
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
padding: 6px 12px;
|
||
border: 1px solid var(--border);
|
||
background: transparent;
|
||
color: var(--text-dim);
|
||
cursor: pointer;
|
||
font-family: var(--font-body);
|
||
transition: all 0.15s;
|
||
}
|
||
.pill:hover { color: var(--text); border-color: var(--text-dim); }
|
||
.pill.active {
|
||
background: var(--phosphor);
|
||
color: var(--bg);
|
||
border-color: var(--phosphor);
|
||
font-weight: 700;
|
||
}
|
||
.pill .count {
|
||
margin-left: 6px;
|
||
opacity: 0.7;
|
||
}
|
||
|
||
/* === GAME GRID === */
|
||
.games {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||
gap: 16px;
|
||
}
|
||
.card {
|
||
background: var(--bg-elev);
|
||
border: 1px solid var(--border);
|
||
overflow: hidden;
|
||
cursor: pointer;
|
||
transition: all 0.2s ease;
|
||
display: flex;
|
||
flex-direction: column;
|
||
position: relative;
|
||
}
|
||
.card:hover {
|
||
border-color: var(--phosphor);
|
||
transform: translateY(-2px);
|
||
box-shadow: 0 4px 20px rgba(124,255,107,0.08);
|
||
}
|
||
.cover {
|
||
aspect-ratio: 3 / 4;
|
||
background: linear-gradient(135deg, var(--bg-elev-2), var(--bg));
|
||
position: relative;
|
||
overflow: hidden;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
}
|
||
.cover img {
|
||
width: 100%; height: 100%;
|
||
object-fit: cover;
|
||
display: block;
|
||
}
|
||
.cover .no-cover {
|
||
font-family: var(--font-display);
|
||
font-size: 48px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 4px;
|
||
}
|
||
.cover::after {
|
||
content: '';
|
||
position: absolute;
|
||
inset: 0;
|
||
background: repeating-linear-gradient(0deg, rgba(0,0,0,0.08) 0px, rgba(0,0,0,0.08) 1px, transparent 1px, transparent 3px);
|
||
pointer-events: none;
|
||
}
|
||
.status-badge {
|
||
position: absolute;
|
||
top: 8px;
|
||
left: 8px;
|
||
font-size: 9px;
|
||
padding: 4px 8px;
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
font-weight: 700;
|
||
background: var(--bg);
|
||
border: 1px solid currentColor;
|
||
}
|
||
.status-playing { color: var(--phosphor); }
|
||
.status-completed { color: var(--blue); }
|
||
.status-dropped { color: var(--red); }
|
||
.status-hold { color: var(--amber); }
|
||
.status-variety { color: var(--purple); }
|
||
.status-planned { color: var(--text-dim); }
|
||
|
||
.card-body {
|
||
padding: 12px 14px;
|
||
flex: 1;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 6px;
|
||
}
|
||
.card-title {
|
||
font-family: var(--font-display);
|
||
font-size: 22px;
|
||
line-height: 1.1;
|
||
color: var(--text);
|
||
letter-spacing: 1px;
|
||
}
|
||
.card-meta {
|
||
font-size: 10px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
display: flex;
|
||
gap: 12px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.card-meta span::before {
|
||
content: '■ ';
|
||
color: var(--phosphor-dim);
|
||
}
|
||
|
||
.empty {
|
||
grid-column: 1 / -1;
|
||
padding: 60px 20px;
|
||
text-align: center;
|
||
color: var(--text-faint);
|
||
border: 1px dashed var(--border);
|
||
}
|
||
.empty h3 {
|
||
font-family: var(--font-display);
|
||
font-size: 32px;
|
||
color: var(--text-dim);
|
||
margin-bottom: 8px;
|
||
letter-spacing: 2px;
|
||
}
|
||
|
||
/* === MODAL === */
|
||
.modal-backdrop {
|
||
position: fixed;
|
||
inset: 0;
|
||
background: rgba(0,0,0,0.8);
|
||
backdrop-filter: blur(4px);
|
||
display: none;
|
||
align-items: flex-start;
|
||
justify-content: center;
|
||
padding: 40px 20px;
|
||
z-index: 1000;
|
||
overflow-y: auto;
|
||
}
|
||
.modal-backdrop.open { display: flex; }
|
||
.modal {
|
||
background: var(--bg-elev);
|
||
border: 1px solid var(--border);
|
||
max-width: 720px;
|
||
width: 100%;
|
||
padding: 0;
|
||
position: relative;
|
||
animation: modalIn 0.2s ease;
|
||
}
|
||
@keyframes modalIn {
|
||
from { opacity: 0; transform: translateY(-20px); }
|
||
to { opacity: 1; transform: translateY(0); }
|
||
}
|
||
.modal-head {
|
||
padding: 16px 20px;
|
||
border-bottom: 1px solid var(--border);
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
background: var(--bg-elev-2);
|
||
}
|
||
.modal-head h2 {
|
||
font-family: var(--font-display);
|
||
font-size: 28px;
|
||
color: var(--phosphor);
|
||
letter-spacing: 2px;
|
||
text-shadow: 0 0 6px rgba(124,255,107,0.3);
|
||
}
|
||
.close-x {
|
||
background: none;
|
||
border: none;
|
||
color: var(--text-dim);
|
||
font-family: var(--font-display);
|
||
font-size: 28px;
|
||
cursor: pointer;
|
||
line-height: 1;
|
||
padding: 0 8px;
|
||
}
|
||
.close-x:hover { color: var(--red); }
|
||
.modal-body { padding: 20px; }
|
||
|
||
/* === FORMS === */
|
||
.field { margin-bottom: 16px; }
|
||
.field label {
|
||
display: block;
|
||
font-size: 10px;
|
||
letter-spacing: 2px;
|
||
text-transform: uppercase;
|
||
color: var(--text-dim);
|
||
margin-bottom: 6px;
|
||
}
|
||
.field input, .field textarea, .field select {
|
||
width: 100%;
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
color: var(--text);
|
||
font-family: var(--font-body);
|
||
font-size: 13px;
|
||
padding: 10px 12px;
|
||
}
|
||
.field input:focus, .field textarea:focus, .field select:focus {
|
||
outline: none;
|
||
border-color: var(--phosphor);
|
||
box-shadow: 0 0 0 1px var(--phosphor);
|
||
}
|
||
.field textarea { min-height: 80px; resize: vertical; font-family: var(--font-body); }
|
||
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||
@media (max-width: 500px) { .field-row { grid-template-columns: 1fr; } }
|
||
|
||
.form-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
justify-content: flex-end;
|
||
margin-top: 20px;
|
||
padding-top: 16px;
|
||
border-top: 1px dashed var(--border);
|
||
}
|
||
|
||
/* === SESSIONS (in detail modal) === */
|
||
.sessions-head {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
margin: 24px 0 12px;
|
||
padding-bottom: 8px;
|
||
border-bottom: 1px dashed var(--border);
|
||
}
|
||
.sessions-head h3 {
|
||
font-family: var(--font-display);
|
||
font-size: 22px;
|
||
color: var(--amber);
|
||
letter-spacing: 2px;
|
||
}
|
||
.session {
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
padding: 12px;
|
||
margin-bottom: 8px;
|
||
display: grid;
|
||
grid-template-columns: auto 1fr auto;
|
||
gap: 12px;
|
||
align-items: start;
|
||
}
|
||
.session-date {
|
||
font-family: var(--font-display);
|
||
font-size: 24px;
|
||
color: var(--amber);
|
||
line-height: 1;
|
||
}
|
||
.session-date small {
|
||
display: block;
|
||
font-family: var(--font-body);
|
||
font-size: 9px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 1px;
|
||
margin-top: 4px;
|
||
}
|
||
.session-info {
|
||
font-size: 12px;
|
||
color: var(--text-dim);
|
||
line-height: 1.5;
|
||
}
|
||
.session-info strong { color: var(--text); margin-right: 8px; }
|
||
.session-info .session-notes {
|
||
margin-top: 4px;
|
||
color: var(--text);
|
||
font-size: 12px;
|
||
}
|
||
|
||
.detail-grid {
|
||
display: grid;
|
||
grid-template-columns: 120px 1fr;
|
||
gap: 16px;
|
||
margin-bottom: 16px;
|
||
}
|
||
.detail-cover {
|
||
aspect-ratio: 3 / 4;
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
overflow: hidden;
|
||
}
|
||
.detail-cover img { width: 100%; height: 100%; object-fit: cover; }
|
||
.detail-info .detail-title {
|
||
font-family: var(--font-display);
|
||
font-size: 36px;
|
||
color: var(--text);
|
||
letter-spacing: 2px;
|
||
margin-bottom: 6px;
|
||
line-height: 1;
|
||
}
|
||
.detail-meta {
|
||
font-size: 11px;
|
||
color: var(--text-dim);
|
||
letter-spacing: 1px;
|
||
display: flex;
|
||
gap: 16px;
|
||
flex-wrap: wrap;
|
||
margin-bottom: 10px;
|
||
}
|
||
.detail-notes {
|
||
font-size: 13px;
|
||
color: var(--text);
|
||
white-space: pre-wrap;
|
||
background: var(--bg);
|
||
padding: 10px 12px;
|
||
border-left: 2px solid var(--phosphor);
|
||
}
|
||
|
||
/* === SETUP SCREEN === */
|
||
.setup {
|
||
max-width: 600px;
|
||
margin: 60px auto;
|
||
padding: 40px;
|
||
background: var(--bg-elev);
|
||
border: 1px solid var(--border);
|
||
}
|
||
.setup h2 {
|
||
font-family: var(--font-display);
|
||
font-size: 40px;
|
||
color: var(--amber);
|
||
letter-spacing: 2px;
|
||
margin-bottom: 8px;
|
||
}
|
||
.setup p { color: var(--text-dim); margin-bottom: 20px; font-size: 13px; }
|
||
.setup code {
|
||
background: var(--bg);
|
||
padding: 2px 6px;
|
||
color: var(--phosphor);
|
||
font-size: 12px;
|
||
}
|
||
.setup pre {
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
padding: 12px;
|
||
overflow-x: auto;
|
||
font-size: 11px;
|
||
color: var(--text-dim);
|
||
margin: 12px 0;
|
||
line-height: 1.6;
|
||
}
|
||
.setup pre .kw { color: var(--purple); }
|
||
.setup pre .str { color: var(--amber); }
|
||
|
||
.rawg-search-field { position: relative; }
|
||
.rawg-hint {
|
||
font-size: 9px;
|
||
color: var(--text-faint);
|
||
margin-left: 6px;
|
||
text-transform: none;
|
||
letter-spacing: 0.5px;
|
||
}
|
||
.rawg-hint.missing { color: var(--amber); }
|
||
.rawg-input-wrap { position: relative; }
|
||
.rawg-spinner {
|
||
position: absolute;
|
||
right: 12px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
color: var(--phosphor);
|
||
font-family: var(--font-display);
|
||
font-size: 16px;
|
||
animation: spin 0.6s linear infinite;
|
||
}
|
||
@keyframes spin { to { transform: translateY(-50%) rotate(360deg); } }
|
||
.rawg-results {
|
||
position: absolute;
|
||
top: 100%;
|
||
left: 0;
|
||
right: 0;
|
||
background: var(--bg-elev-2);
|
||
border: 1px solid var(--phosphor);
|
||
max-height: 280px;
|
||
overflow-y: auto;
|
||
z-index: 10;
|
||
display: none;
|
||
box-shadow: 0 4px 20px rgba(0,0,0,0.6);
|
||
}
|
||
.rawg-results.open { display: block; }
|
||
.rawg-result {
|
||
display: flex;
|
||
gap: 10px;
|
||
padding: 8px 10px;
|
||
cursor: pointer;
|
||
border-bottom: 1px solid var(--border);
|
||
align-items: center;
|
||
}
|
||
.rawg-result:last-child { border-bottom: none; }
|
||
.rawg-result:hover { background: var(--bg); }
|
||
.rawg-result img {
|
||
width: 44px;
|
||
height: 58px;
|
||
object-fit: cover;
|
||
background: var(--bg);
|
||
flex-shrink: 0;
|
||
}
|
||
.rawg-result-info { flex: 1; min-width: 0; }
|
||
.rawg-result-title {
|
||
font-size: 13px;
|
||
color: var(--text);
|
||
white-space: nowrap;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
}
|
||
.rawg-result-meta {
|
||
font-size: 10px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 1px;
|
||
text-transform: uppercase;
|
||
margin-top: 2px;
|
||
}
|
||
.rawg-empty, .rawg-setup-prompt {
|
||
padding: 16px;
|
||
text-align: center;
|
||
font-size: 11px;
|
||
color: var(--text-dim);
|
||
letter-spacing: 1px;
|
||
}
|
||
.rawg-setup-prompt { color: var(--amber); }
|
||
.rawg-setup-prompt a { color: var(--phosphor); text-decoration: underline; }
|
||
.rawg-setup-prompt button { margin-top: 8px; }
|
||
|
||
/* Cover image uploader */
|
||
.cover-uploader {
|
||
display: grid;
|
||
grid-template-columns: 100px 1fr;
|
||
gap: 12px;
|
||
align-items: stretch;
|
||
}
|
||
.cover-preview {
|
||
aspect-ratio: 3 / 4;
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
position: relative;
|
||
overflow: hidden;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
}
|
||
.cover-preview img {
|
||
width: 100%;
|
||
height: 100%;
|
||
object-fit: cover;
|
||
}
|
||
.cover-placeholder {
|
||
font-family: var(--font-display);
|
||
font-size: 14px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 2px;
|
||
text-transform: uppercase;
|
||
}
|
||
.cover-clear-btn {
|
||
position: absolute;
|
||
top: 4px;
|
||
right: 4px;
|
||
background: var(--bg);
|
||
border: 1px solid var(--red);
|
||
color: var(--red);
|
||
width: 22px;
|
||
height: 22px;
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
line-height: 1;
|
||
padding: 0;
|
||
}
|
||
.cover-clear-btn:hover { background: var(--red); color: var(--bg); }
|
||
|
||
.cover-drop {
|
||
background: var(--bg);
|
||
border: 1px dashed var(--border);
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
text-align: center;
|
||
padding: 16px 12px;
|
||
transition: all 0.15s;
|
||
color: var(--text-dim);
|
||
font-size: 12px;
|
||
line-height: 1.5;
|
||
}
|
||
.cover-drop.dragover {
|
||
border-color: var(--phosphor);
|
||
background: rgba(124,255,107,0.05);
|
||
color: var(--phosphor);
|
||
box-shadow: inset 0 0 20px rgba(124,255,107,0.1);
|
||
}
|
||
.cover-pick-btn {
|
||
background: none;
|
||
border: none;
|
||
color: var(--phosphor);
|
||
text-decoration: underline;
|
||
cursor: pointer;
|
||
font-family: var(--font-body);
|
||
font-size: 12px;
|
||
padding: 0;
|
||
}
|
||
.cover-pick-btn:hover { color: #9dff8c; }
|
||
.cover-uploading {
|
||
text-align: center;
|
||
color: var(--phosphor);
|
||
font-size: 11px;
|
||
letter-spacing: 1px;
|
||
text-transform: uppercase;
|
||
}
|
||
.cover-spinner {
|
||
font-family: var(--font-display);
|
||
font-size: 24px;
|
||
animation: spin 0.6s linear infinite;
|
||
margin-bottom: 6px;
|
||
}
|
||
|
||
/* Twitch VOD list */
|
||
#twitchBtn.connected { color: #c77cff; border-color: #6d3a9a; }
|
||
.vod-item {
|
||
display: grid;
|
||
grid-template-columns: 80px 1fr 220px;
|
||
gap: 12px;
|
||
padding: 10px;
|
||
border: 1px solid var(--border);
|
||
background: var(--bg-elev);
|
||
margin-bottom: 6px;
|
||
align-items: center;
|
||
}
|
||
.vod-item.imported { opacity: 0.55; }
|
||
.vod-thumb {
|
||
width: 80px;
|
||
height: 45px;
|
||
object-fit: cover;
|
||
background: var(--bg);
|
||
}
|
||
.vod-info { min-width: 0; }
|
||
.vod-title {
|
||
font-size: 12px;
|
||
color: var(--text);
|
||
white-space: nowrap;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
margin-bottom: 4px;
|
||
}
|
||
.vod-meta {
|
||
font-size: 10px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 1px;
|
||
text-transform: uppercase;
|
||
display: flex;
|
||
gap: 10px;
|
||
}
|
||
.vod-pick select {
|
||
width: 100%;
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
color: var(--text);
|
||
font-family: var(--font-body);
|
||
font-size: 11px;
|
||
padding: 6px 8px;
|
||
}
|
||
.vod-pick .imported-tag {
|
||
font-size: 9px;
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
color: var(--phosphor);
|
||
text-align: center;
|
||
padding: 6px;
|
||
border: 1px dashed var(--phosphor-dim);
|
||
}
|
||
|
||
/* Genre tag chips */
|
||
.genre-tags {
|
||
display: flex;
|
||
gap: 6px;
|
||
flex-wrap: wrap;
|
||
min-height: 24px;
|
||
padding: 4px;
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
}
|
||
.genre-tags:empty::before {
|
||
content: 'No genres yet';
|
||
color: var(--text-faint);
|
||
font-size: 11px;
|
||
letter-spacing: 1px;
|
||
padding: 2px 6px;
|
||
}
|
||
.genre-chip {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
background: var(--bg-elev-2);
|
||
border: 1px solid var(--phosphor-dim);
|
||
color: var(--phosphor);
|
||
font-size: 10px;
|
||
letter-spacing: 1px;
|
||
text-transform: uppercase;
|
||
padding: 3px 8px;
|
||
}
|
||
.genre-chip button {
|
||
background: none;
|
||
border: none;
|
||
color: var(--text-faint);
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
line-height: 1;
|
||
padding: 0;
|
||
}
|
||
.genre-chip button:hover { color: var(--red); }
|
||
|
||
/* Platform badge */
|
||
.platform-badge {
|
||
position: absolute;
|
||
top: 8px;
|
||
right: 8px;
|
||
font-size: 9px;
|
||
padding: 4px 8px;
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
font-weight: 700;
|
||
background: var(--bg);
|
||
border: 1px solid var(--amber-dim);
|
||
color: var(--amber);
|
||
}
|
||
|
||
/* Card genre tags (small, inline) */
|
||
.card-genres {
|
||
display: flex;
|
||
gap: 4px;
|
||
flex-wrap: wrap;
|
||
margin-top: 4px;
|
||
}
|
||
.card-genre {
|
||
font-size: 8px;
|
||
letter-spacing: 1px;
|
||
text-transform: uppercase;
|
||
color: var(--text-dim);
|
||
background: var(--bg);
|
||
padding: 2px 6px;
|
||
border: 1px solid var(--border);
|
||
}
|
||
|
||
.toast {
|
||
position: fixed;
|
||
bottom: 24px;
|
||
right: 24px;
|
||
background: var(--bg-elev);
|
||
border: 1px solid var(--phosphor);
|
||
color: var(--phosphor);
|
||
padding: 12px 18px;
|
||
font-size: 11px;
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
z-index: 2000;
|
||
box-shadow: 0 0 20px rgba(124,255,107,0.2);
|
||
animation: toastIn 0.2s ease;
|
||
}
|
||
.toast.error { border-color: var(--red); color: var(--red); box-shadow: 0 0 20px rgba(255,91,91,0.2); }
|
||
@keyframes toastIn { from { opacity: 0; transform: translateY(10px); } }
|
||
|
||
/* === VIEW TOGGLE === */
|
||
.view-toggle {
|
||
display: flex;
|
||
gap: 0;
|
||
margin-bottom: 20px;
|
||
border: 1px solid var(--border);
|
||
background: var(--bg-elev);
|
||
width: fit-content;
|
||
}
|
||
.view-toggle button {
|
||
font-family: var(--font-body);
|
||
font-size: 11px;
|
||
letter-spacing: 2px;
|
||
text-transform: uppercase;
|
||
padding: 8px 18px;
|
||
border: none;
|
||
background: transparent;
|
||
color: var(--text-dim);
|
||
cursor: pointer;
|
||
transition: all 0.15s ease;
|
||
border-right: 1px solid var(--border);
|
||
}
|
||
.view-toggle button:last-child { border-right: none; }
|
||
.view-toggle button:hover { color: var(--text); }
|
||
.view-toggle button.active {
|
||
background: var(--phosphor);
|
||
color: var(--bg);
|
||
font-weight: 700;
|
||
}
|
||
|
||
/* === CALENDAR === */
|
||
.calendar-wrap {
|
||
border: 1px solid var(--border);
|
||
background: var(--bg-elev);
|
||
}
|
||
.cal-head {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
padding: 14px 18px;
|
||
border-bottom: 1px solid var(--border);
|
||
background: var(--bg-elev-2);
|
||
gap: 12px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.cal-month-title {
|
||
font-family: var(--font-display);
|
||
font-size: 32px;
|
||
color: var(--phosphor);
|
||
letter-spacing: 3px;
|
||
text-shadow: 0 0 6px rgba(124,255,107,0.3);
|
||
line-height: 1;
|
||
}
|
||
.cal-month-title small {
|
||
font-family: var(--font-body);
|
||
font-size: 11px;
|
||
color: var(--text-dim);
|
||
letter-spacing: 1.5px;
|
||
margin-left: 12px;
|
||
text-transform: uppercase;
|
||
}
|
||
.cal-nav {
|
||
display: flex;
|
||
gap: 6px;
|
||
align-items: center;
|
||
}
|
||
.cal-nav button {
|
||
font-family: var(--font-body);
|
||
font-size: 11px;
|
||
letter-spacing: 1.5px;
|
||
text-transform: uppercase;
|
||
padding: 6px 12px;
|
||
border: 1px solid var(--border);
|
||
background: var(--bg);
|
||
color: var(--text-dim);
|
||
cursor: pointer;
|
||
transition: all 0.15s;
|
||
}
|
||
.cal-nav button:hover {
|
||
border-color: var(--phosphor);
|
||
color: var(--phosphor);
|
||
box-shadow: 0 0 8px rgba(124,255,107,0.15);
|
||
}
|
||
.cal-nav .arrow {
|
||
font-family: var(--font-display);
|
||
font-size: 18px;
|
||
padding: 2px 12px;
|
||
line-height: 1;
|
||
}
|
||
|
||
.cal-weekdays {
|
||
display: grid;
|
||
grid-template-columns: repeat(7, 1fr);
|
||
background: var(--bg-elev-2);
|
||
border-bottom: 1px solid var(--border);
|
||
}
|
||
.cal-weekday {
|
||
padding: 8px 10px;
|
||
font-size: 10px;
|
||
color: var(--text-faint);
|
||
letter-spacing: 2px;
|
||
text-transform: uppercase;
|
||
text-align: left;
|
||
border-right: 1px solid var(--border);
|
||
}
|
||
.cal-weekday:last-child { border-right: none; }
|
||
|
||
.cal-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(7, 1fr);
|
||
background: var(--border);
|
||
gap: 1px;
|
||
}
|
||
.cal-day {
|
||
background: var(--bg-elev);
|
||
min-height: 110px;
|
||
padding: 6px 8px;
|
||
position: relative;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 4px;
|
||
cursor: default;
|
||
transition: background 0.15s;
|
||
}
|
||
.cal-day.has-sessions { cursor: pointer; }
|
||
.cal-day.has-sessions:hover {
|
||
background: var(--bg-elev-2);
|
||
}
|
||
.cal-day.other-month {
|
||
background: var(--bg);
|
||
opacity: 0.5;
|
||
}
|
||
.cal-day.other-month .cal-day-num { color: var(--text-faint); }
|
||
.cal-day.today {
|
||
background: var(--bg-elev-2);
|
||
box-shadow: inset 0 0 0 1px var(--phosphor), inset 0 0 12px rgba(124,255,107,0.08);
|
||
}
|
||
.cal-day.today .cal-day-num {
|
||
color: var(--phosphor);
|
||
text-shadow: 0 0 6px rgba(124,255,107,0.5);
|
||
}
|
||
.cal-day-num {
|
||
font-family: var(--font-display);
|
||
font-size: 20px;
|
||
color: var(--text-dim);
|
||
line-height: 1;
|
||
letter-spacing: 1px;
|
||
}
|
||
.cal-day.has-sessions .cal-day-num { color: var(--text); }
|
||
.cal-day-hours {
|
||
position: absolute;
|
||
top: 8px;
|
||
right: 8px;
|
||
font-size: 9px;
|
||
color: var(--amber);
|
||
letter-spacing: 1px;
|
||
font-family: var(--font-body);
|
||
}
|
||
.cal-games {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 2px;
|
||
margin-top: 2px;
|
||
overflow: hidden;
|
||
}
|
||
.cal-game {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
padding: 2px 4px;
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
border-left: 2px solid var(--phosphor-dim);
|
||
cursor: pointer;
|
||
transition: all 0.12s;
|
||
min-width: 0;
|
||
}
|
||
.cal-game:hover {
|
||
border-left-color: var(--phosphor);
|
||
background: var(--bg-elev-2);
|
||
box-shadow: 0 0 6px rgba(124,255,107,0.1);
|
||
}
|
||
.cal-game-cover {
|
||
width: 16px;
|
||
height: 16px;
|
||
object-fit: cover;
|
||
flex-shrink: 0;
|
||
background: var(--bg-elev-2);
|
||
}
|
||
.cal-game-cover-fallback {
|
||
width: 16px;
|
||
height: 16px;
|
||
flex-shrink: 0;
|
||
background: var(--bg-elev-2);
|
||
color: var(--text-faint);
|
||
font-family: var(--font-display);
|
||
font-size: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
line-height: 1;
|
||
}
|
||
.cal-game-title {
|
||
font-size: 10px;
|
||
color: var(--text);
|
||
white-space: nowrap;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
letter-spacing: 0.3px;
|
||
flex: 1;
|
||
min-width: 0;
|
||
}
|
||
.cal-more {
|
||
font-size: 9px;
|
||
color: var(--text-dim);
|
||
letter-spacing: 1px;
|
||
text-transform: uppercase;
|
||
padding: 1px 4px;
|
||
cursor: pointer;
|
||
}
|
||
.cal-more:hover { color: var(--phosphor); }
|
||
|
||
/* Empty state inside the calendar */
|
||
.cal-empty {
|
||
grid-column: 1 / -1;
|
||
padding: 60px 20px;
|
||
text-align: center;
|
||
color: var(--text-faint);
|
||
background: var(--bg-elev);
|
||
}
|
||
|
||
/* Day detail modal session list reuses .session styles */
|
||
.day-detail-empty {
|
||
padding: 30px;
|
||
text-align: center;
|
||
color: var(--text-faint);
|
||
border: 1px dashed var(--border);
|
||
}
|
||
|
||
@media (max-width: 800px) {
|
||
.cal-day { min-height: 84px; padding: 4px 5px; }
|
||
.cal-day-num { font-size: 16px; }
|
||
.cal-day-hours { font-size: 8px; top: 5px; right: 5px; }
|
||
.cal-game-title { font-size: 9px; }
|
||
.cal-game-cover, .cal-game-cover-fallback { width: 12px; height: 12px; }
|
||
.cal-game-cover-fallback { font-size: 10px; }
|
||
.cal-weekday { font-size: 9px; padding: 6px 5px; letter-spacing: 1px; }
|
||
.cal-month-title { font-size: 24px; }
|
||
}
|
||
@media (max-width: 500px) {
|
||
.cal-game-title { display: none; }
|
||
.cal-games { flex-direction: row; flex-wrap: wrap; }
|
||
.cal-game { padding: 1px; border-left-width: 2px; }
|
||
}
|
||
|
||
@media (max-width: 600px) {
|
||
.brand h1 { font-size: 44px; }
|
||
.detail-grid { grid-template-columns: 1fr; }
|
||
.detail-cover { max-width: 160px; }
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<div id="loginScreen" class="setup" style="display:none">
|
||
<h2>STREAM LOG</h2>
|
||
<p>Sign in to access your stream tracker. We'll email you a magic link — click it and you're in. No password to remember.</p>
|
||
|
||
<div class="field">
|
||
<label>Email</label>
|
||
<input id="loginEmail" type="email" placeholder="you@example.com" autocomplete="email">
|
||
</div>
|
||
|
||
<div class="form-actions">
|
||
<button class="btn btn-primary" id="loginBtn" onclick="sendMagicLink()">Send Magic Link →</button>
|
||
</div>
|
||
|
||
<div id="loginStatus" style="margin-top: 20px; display: none;"></div>
|
||
|
||
<p style="margin-top: 28px; font-size: 11px; color: var(--text-faint);">First time on a device? You'll get an email with a sign-in link. Sessions stay valid for ~30 days, so you only need to do this occasionally.</p>
|
||
</div>
|
||
|
||
<div id="setupScreen" class="setup" style="display:none">
|
||
<h2>INITIAL SETUP</h2>
|
||
<p>To connect this tracker to your Supabase project, you need your project URL and anon key. Paste them below — they'll be saved in this browser.</p>
|
||
|
||
<div class="field">
|
||
<label>Supabase URL</label>
|
||
<input id="setupUrl" type="text" placeholder="https://xxxxx.supabase.co">
|
||
</div>
|
||
<div class="field">
|
||
<label>Anon / Public Key</label>
|
||
<input id="setupKey" type="text" placeholder="eyJhbGci...">
|
||
</div>
|
||
|
||
<p style="margin-top: 24px;"><strong style="color: var(--text);">First time?</strong> Run this SQL in your Supabase SQL editor to create the tables:</p>
|
||
<pre>
|
||
<span class="kw">create table</span> games (
|
||
id uuid <span class="kw">primary key default</span> gen_random_uuid(),
|
||
title text <span class="kw">not null</span>,
|
||
cover_url text,
|
||
status text <span class="kw">not null default</span> <span class="str">'planned'</span>,
|
||
platform text,
|
||
genres text[],
|
||
started_on date,
|
||
notes text,
|
||
created_at timestamptz <span class="kw">default</span> now()
|
||
);
|
||
|
||
<span class="kw">create table</span> sessions (
|
||
id uuid <span class="kw">primary key default</span> gen_random_uuid(),
|
||
game_id uuid <span class="kw">references</span> games(id) <span class="kw">on delete cascade</span>,
|
||
streamed_on date <span class="kw">not null</span>,
|
||
duration_minutes <span class="kw">int</span>,
|
||
peak_viewers <span class="kw">int</span>,
|
||
notes text,
|
||
created_at timestamptz <span class="kw">default</span> now()
|
||
);
|
||
|
||
<span class="kw">alter table</span> games <span class="kw">enable row level security</span>;
|
||
<span class="kw">alter table</span> sessions <span class="kw">enable row level security</span>;
|
||
|
||
<span class="kw">create policy</span> <span class="str">"public all"</span> <span class="kw">on</span> games <span class="kw">for all using</span> (<span class="kw">true</span>) <span class="kw">with check</span> (<span class="kw">true</span>);
|
||
<span class="kw">create policy</span> <span class="str">"public all"</span> <span class="kw">on</span> sessions <span class="kw">for all using</span> (<span class="kw">true</span>) <span class="kw">with check</span> (<span class="kw">true</span>);</pre>
|
||
<p style="font-size: 11px; color: var(--text-faint);">Note: this uses an open policy since it's a personal log. If you want real auth later, we can add it.</p>
|
||
|
||
<div class="form-actions">
|
||
<button class="btn btn-primary" onclick="saveSetup()">Connect</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="app" class="app" style="display:none">
|
||
<header>
|
||
<div class="brand">
|
||
<h1><span>STREAM LOG</span><span class="blink"></span></h1>
|
||
<p>// Personal Game Tracker — Session Database</p>
|
||
</div>
|
||
<div class="header-actions">
|
||
<div id="connStatus" class="conn-status"><span class="conn-dot"></span><span id="connText">connecting</span></div>
|
||
<span id="userChip" class="conn-status" style="border-color:var(--border);color:var(--text-dim)" title="">—</span>
|
||
<button class="btn btn-ghost btn-sm" id="twitchBtn" onclick="onTwitchButtonClick()">🟣 Twitch</button>
|
||
<button class="btn btn-ghost btn-sm" onclick="logout()" title="Sign out">↪ Sign Out</button>
|
||
<button class="btn btn-primary" onclick="openGameModal()">+ New Game</button>
|
||
</div>
|
||
</header>
|
||
|
||
<div class="stats">
|
||
<div class="stat">
|
||
<div class="stat-label">Total Games</div>
|
||
<div class="stat-value" id="statTotal">0</div>
|
||
<div class="stat-sub" id="statTotalSub">in database</div>
|
||
</div>
|
||
<div class="stat">
|
||
<div class="stat-label">Hours Streamed</div>
|
||
<div class="stat-value amber" id="statHours">0</div>
|
||
<div class="stat-sub" id="statSessions">0 sessions</div>
|
||
</div>
|
||
<div class="stat">
|
||
<div class="stat-label">Peak Viewers</div>
|
||
<div class="stat-value blue" id="statPeak">0</div>
|
||
<div class="stat-sub" id="statPeakGame">—</div>
|
||
</div>
|
||
<div class="stat">
|
||
<div class="stat-label">Currently Playing</div>
|
||
<div class="stat-value purple" id="statActive">0</div>
|
||
<div class="stat-sub" id="statActiveSub">active games</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="toolbar">
|
||
<div class="search"><input type="text" id="searchInput" placeholder="Search titles..." oninput="render()"></div>
|
||
<select class="filter" id="sortBy" onchange="render()">
|
||
<option value="recent">Recently Added</option>
|
||
<option value="streamed">Most Streamed</option>
|
||
<option value="title">Title A-Z</option>
|
||
<option value="last-stream">Last Streamed</option>
|
||
</select>
|
||
<button class="btn btn-sm" onclick="openExportMenu()" title="Export data">⬇ Export</button>
|
||
</div>
|
||
|
||
<div class="view-toggle" id="viewToggle">
|
||
<button id="viewLibraryBtn" class="active" onclick="setView('library')">▦ Library</button>
|
||
<button id="viewCalendarBtn" onclick="setView('calendar')">▤ Calendar</button>
|
||
</div>
|
||
|
||
<div id="libraryView">
|
||
<div class="status-filter" id="statusFilter"></div>
|
||
<div class="status-filter" id="platformFilter" style="margin-top:-8px"></div>
|
||
|
||
<div class="games" id="gameGrid"></div>
|
||
</div>
|
||
|
||
<div id="calendarView" style="display:none">
|
||
<div class="calendar-wrap">
|
||
<div class="cal-head">
|
||
<div class="cal-month-title">
|
||
<span id="calMonthLabel">—</span>
|
||
<small id="calMonthSummary"></small>
|
||
</div>
|
||
<div class="cal-nav">
|
||
<button class="arrow" onclick="prevMonth()" title="Previous month">◀</button>
|
||
<button onclick="goToToday()">Today</button>
|
||
<button class="arrow" onclick="nextMonth()" title="Next month">▶</button>
|
||
</div>
|
||
</div>
|
||
<div class="cal-weekdays" id="calWeekdays"></div>
|
||
<div class="cal-grid" id="calGrid"></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Export menu -->
|
||
<div class="modal-backdrop" id="exportModal" onclick="if(event.target===this)closeExportMenu()">
|
||
<div class="modal" style="max-width:480px">
|
||
<div class="modal-head">
|
||
<h2>EXPORT DATA</h2>
|
||
<button class="close-x" onclick="closeExportMenu()">×</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<p style="color:var(--text-dim);font-size:12px;margin-bottom:16px">Download your stream log data. Files save with today's date in the filename.</p>
|
||
<div style="display:flex;flex-direction:column;gap:8px">
|
||
<button class="btn" onclick="exportCSV('games')">⬇ Games (CSV)</button>
|
||
<button class="btn" onclick="exportCSV('sessions')">⬇ Sessions (CSV)</button>
|
||
<button class="btn" onclick="exportCSV('combined')">⬇ Sessions + Game Info (CSV)</button>
|
||
<button class="btn" onclick="exportJSON()">⬇ Full Backup (JSON)</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Twitch setup modal -->
|
||
<div class="modal-backdrop" id="twitchSetupModal" onclick="if(event.target===this)closeTwitchSetup()">
|
||
<div class="modal" style="max-width:560px">
|
||
<div class="modal-head">
|
||
<h2 style="color:#c77cff">🟣 CONNECT TWITCH</h2>
|
||
<button class="close-x" onclick="closeTwitchSetup()">×</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<p style="color:var(--text-dim);font-size:12px;margin-bottom:16px">One-time setup. Create a Twitch app, paste your Client ID, authorize. Then you can import past VODs as sessions with two clicks.</p>
|
||
|
||
<div style="background:var(--bg);border:1px solid var(--border);padding:12px;margin-bottom:16px;font-size:12px;line-height:1.7">
|
||
<div style="color:var(--phosphor);letter-spacing:1.5px;text-transform:uppercase;font-size:10px;margin-bottom:6px">Step 1 — Create Twitch App</div>
|
||
<div style="color:var(--text-dim)">
|
||
Go to <a href="https://dev.twitch.tv/console/apps/create" target="_blank" style="color:var(--phosphor)">dev.twitch.tv/console/apps/create</a><br>
|
||
• Name: anything (e.g. "Stream Log")<br>
|
||
• OAuth Redirect URL: <code id="redirectUrlDisplay" style="background:var(--bg-elev-2);padding:2px 6px;color:var(--amber);font-size:11px;user-select:all"></code> <button class="btn btn-sm" style="padding:2px 8px;font-size:9px;margin-left:4px" onclick="copyRedirect()">copy</button><br>
|
||
• Category: Application Integration<br>
|
||
• Client Type: <strong style="color:var(--phosphor)">Public</strong> (important — no secret needed)<br>
|
||
After creating, click "Manage" on the app to see your <strong>Client ID</strong>.
|
||
</div>
|
||
</div>
|
||
|
||
<div class="field">
|
||
<label>Twitch Client ID</label>
|
||
<input id="twitchClientId" type="text" placeholder="abc123xyz...">
|
||
</div>
|
||
<div class="field">
|
||
<label>Your Twitch Username</label>
|
||
<input id="twitchUsername" type="text" placeholder="kevinburchell">
|
||
</div>
|
||
|
||
<div class="form-actions">
|
||
<button class="btn btn-ghost" id="twitchDisconnectBtn" onclick="twitchDisconnect()" style="display:none">Disconnect</button>
|
||
<button class="btn btn-ghost" onclick="closeTwitchSetup()">Cancel</button>
|
||
<button class="btn btn-primary" onclick="twitchAuthorize()" style="background:#c77cff;border-color:#c77cff">Authorize with Twitch →</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Twitch import modal -->
|
||
<div class="modal-backdrop" id="twitchImportModal" onclick="if(event.target===this)closeTwitchImport()">
|
||
<div class="modal" style="max-width:780px">
|
||
<div class="modal-head">
|
||
<h2 style="color:#c77cff">🟣 IMPORT FROM TWITCH</h2>
|
||
<button class="close-x" onclick="closeTwitchImport()">×</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<p style="color:var(--text-dim);font-size:12px;margin-bottom:12px">
|
||
Your recent VODs (broadcasts). Pick a game from your library for each one you want to import, then click Import.
|
||
Already-imported VODs are marked and skipped automatically.
|
||
</p>
|
||
<div id="twitchVodList" style="max-height:440px;overflow-y:auto;border:1px solid var(--border);padding:8px;background:var(--bg)"></div>
|
||
<div class="form-actions">
|
||
<button class="btn btn-ghost" onclick="closeTwitchImport()">Cancel</button>
|
||
<button class="btn btn-primary" id="twitchImportBtn" onclick="twitchImportSelected()" style="background:#c77cff;border-color:#c77cff">Import Selected</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- === GAME MODAL (Add/Edit) === -->
|
||
<div class="modal-backdrop" id="gameModal" onclick="if(event.target===this)closeGameModal()">
|
||
<div class="modal">
|
||
<div class="modal-head">
|
||
<h2 id="gameModalTitle">NEW GAME</h2>
|
||
<button class="close-x" onclick="closeGameModal()">×</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<div class="field rawg-search-field">
|
||
<label>Search Game Database <span class="rawg-hint" id="rawgHint">(RAWG)</span></label>
|
||
<div class="rawg-input-wrap">
|
||
<input id="rawgSearch" type="text" placeholder="Start typing to search..." autocomplete="off">
|
||
<span class="rawg-spinner" id="rawgSpinner" style="display:none">⣾</span>
|
||
</div>
|
||
<div class="rawg-results" id="rawgResults"></div>
|
||
</div>
|
||
<div class="field">
|
||
<label>Title *</label>
|
||
<input id="gameTitle" type="text" placeholder="Baldur's Gate 3">
|
||
</div>
|
||
<div class="field-row">
|
||
<div class="field">
|
||
<label>Status</label>
|
||
<select id="gameStatus">
|
||
<option value="planned">Planned</option>
|
||
<option value="playing">Playing Now</option>
|
||
<option value="completed">Completed</option>
|
||
<option value="hold">On Hold</option>
|
||
<option value="dropped">Dropped</option>
|
||
<option value="variety">One-off / Variety</option>
|
||
</select>
|
||
</div>
|
||
<div class="field">
|
||
<label>Platform</label>
|
||
<select id="gamePlatform">
|
||
<option value="">— none —</option>
|
||
<option value="PC">PC</option>
|
||
<option value="PlayStation">PlayStation</option>
|
||
<option value="Xbox">Xbox</option>
|
||
<option value="Nintendo Switch">Nintendo Switch</option>
|
||
<option value="Mobile">Mobile</option>
|
||
<option value="Other">Other</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
<div class="field">
|
||
<label>Genres</label>
|
||
<div class="genre-tags" id="genreTags"></div>
|
||
<input id="genreInput" type="text" placeholder="Type and press Enter to add a genre" style="margin-top: 6px">
|
||
</div>
|
||
<div class="field-row">
|
||
<div class="field">
|
||
<label>Started Streaming On</label>
|
||
<input id="gameStartedOn" type="date">
|
||
</div>
|
||
<div class="field">
|
||
<label>Cover Image URL</label>
|
||
<input id="gameCover" type="text" placeholder="https://...">
|
||
</div>
|
||
</div>
|
||
<div class="field">
|
||
<label>Cover Image</label>
|
||
<div class="cover-uploader" id="coverUploader">
|
||
<div class="cover-preview" id="coverPreview">
|
||
<span class="cover-placeholder" id="coverPlaceholder">No cover</span>
|
||
<img id="coverPreviewImg" style="display:none">
|
||
<button type="button" class="cover-clear-btn" id="coverClearBtn" onclick="clearCoverImage()" style="display:none" title="Remove cover">×</button>
|
||
</div>
|
||
<div class="cover-drop" id="coverDrop">
|
||
<div class="cover-drop-prompt">
|
||
<div style="font-size:24px;color:var(--phosphor);margin-bottom:4px">⬆</div>
|
||
<div>Drag image here or <button type="button" class="cover-pick-btn" onclick="document.getElementById('coverFileInput').click()">choose file</button></div>
|
||
<div style="font-size:9px;color:var(--text-faint);letter-spacing:1.5px;margin-top:6px">JPG · PNG · WEBP · max 5MB</div>
|
||
</div>
|
||
<div class="cover-uploading" id="coverUploading" style="display:none">
|
||
<div class="cover-spinner">⣾</div>
|
||
<div id="coverUploadStatus">Uploading...</div>
|
||
</div>
|
||
</div>
|
||
<input type="file" id="coverFileInput" accept="image/jpeg,image/png,image/webp,image/gif" style="display:none">
|
||
</div>
|
||
</div>
|
||
<div class="field">
|
||
<label>Notes</label>
|
||
<textarea id="gameNotes" placeholder="General thoughts, plan, memorable moments..."></textarea>
|
||
</div>
|
||
<div class="form-actions">
|
||
<button class="btn btn-ghost btn-danger" id="deleteGameBtn" onclick="deleteGame()" style="display:none">Delete</button>
|
||
<button class="btn btn-ghost" onclick="closeGameModal()">Cancel</button>
|
||
<button class="btn btn-primary" onclick="saveGame()">Save</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- === GAME DETAIL MODAL === -->
|
||
<div class="modal-backdrop" id="detailModal" onclick="if(event.target===this)closeDetail()">
|
||
<div class="modal">
|
||
<div class="modal-head">
|
||
<h2>DETAILS</h2>
|
||
<button class="close-x" onclick="closeDetail()">×</button>
|
||
</div>
|
||
<div class="modal-body" id="detailBody"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- === SESSION MODAL === -->
|
||
<div class="modal-backdrop" id="sessionModal" onclick="if(event.target===this)closeSessionModal()">
|
||
<div class="modal">
|
||
<div class="modal-head">
|
||
<h2 id="sessionModalTitle">LOG SESSION</h2>
|
||
<button class="close-x" onclick="closeSessionModal()">×</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<div class="field">
|
||
<label>Date Streamed *</label>
|
||
<input id="sessionDate" type="date">
|
||
</div>
|
||
<div class="field-row">
|
||
<div class="field">
|
||
<label>Duration (minutes)</label>
|
||
<input id="sessionDuration" type="number" min="0" placeholder="180">
|
||
</div>
|
||
<div class="field">
|
||
<label>Peak Viewers</label>
|
||
<input id="sessionPeak" type="number" min="0" placeholder="0">
|
||
</div>
|
||
</div>
|
||
<div class="field">
|
||
<label>Session Notes</label>
|
||
<textarea id="sessionNotes" placeholder="Highlights, moments, observations..."></textarea>
|
||
</div>
|
||
<div class="form-actions">
|
||
<button class="btn btn-ghost btn-danger" id="deleteSessionBtn" onclick="deleteSession()" style="display:none">Delete</button>
|
||
<button class="btn btn-ghost" onclick="closeSessionModal()">Cancel</button>
|
||
<button class="btn btn-primary" onclick="saveSession()">Save</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- === DAY DETAIL MODAL === -->
|
||
<div class="modal-backdrop" id="dayModal" onclick="if(event.target===this)closeDayModal()">
|
||
<div class="modal">
|
||
<div class="modal-head">
|
||
<h2 id="dayModalTitle">DAY</h2>
|
||
<button class="close-x" onclick="closeDayModal()">×</button>
|
||
</div>
|
||
<div class="modal-body" id="dayModalBody"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<script>
|
||
// ============================================================
|
||
// CONFIG — hardcoded so all devices auto-connect
|
||
// ============================================================
|
||
const SUPABASE_URL = 'PASTE_YOUR_SUPABASE_URL_HERE';
|
||
const SUPABASE_ANON_KEY = 'PASTE_YOUR_ANON_KEY_HERE';
|
||
|
||
// ============================================================
|
||
// STATE
|
||
// ============================================================
|
||
const STATUS_OPTS = [
|
||
{ key: 'all', label: 'All' },
|
||
{ key: 'playing', label: 'Playing' },
|
||
{ key: 'completed', label: 'Completed' },
|
||
{ key: 'hold', label: 'On Hold' },
|
||
{ key: 'dropped', label: 'Dropped' },
|
||
{ key: 'variety', label: 'Variety' },
|
||
{ key: 'planned', label: 'Planned' }
|
||
];
|
||
|
||
let sb = null;
|
||
let currentUser = null;
|
||
let games = [];
|
||
let sessions = [];
|
||
let editingGameId = null;
|
||
let rawgSearchTimer = null;
|
||
let rawgLastQuery = '';
|
||
let currentGenres = [];
|
||
let editingSessionId = null;
|
||
let currentDetailGameId = null;
|
||
let activeStatus = 'all';
|
||
let activePlatform = 'all';
|
||
let currentView = 'library'; // 'library' | 'calendar'
|
||
let calendarMonth = startOfMonth(new Date()); // first day of currently-shown month
|
||
|
||
function startOfMonth(d) {
|
||
return new Date(d.getFullYear(), d.getMonth(), 1);
|
||
}
|
||
|
||
// ============================================================
|
||
// SETUP
|
||
// ============================================================
|
||
function safeGet(k) { try { return localStorage.getItem(k); } catch(e) { return null; } }
|
||
function safeSet(k, v) { try { localStorage.setItem(k, v); return true; } catch(e) { return false; } }
|
||
function safeRemove(k) { try { localStorage.removeItem(k); } catch(e) {} }
|
||
|
||
function showLogin() {
|
||
document.getElementById('loginScreen').style.display = 'block';
|
||
document.getElementById('setupScreen').style.display = 'none';
|
||
document.getElementById('app').style.display = 'none';
|
||
}
|
||
function showSetup() {
|
||
document.getElementById('loginScreen').style.display = 'none';
|
||
document.getElementById('setupScreen').style.display = 'block';
|
||
document.getElementById('app').style.display = 'none';
|
||
}
|
||
function showApp() {
|
||
document.getElementById('loginScreen').style.display = 'none';
|
||
document.getElementById('setupScreen').style.display = 'none';
|
||
document.getElementById('app').style.display = 'block';
|
||
}
|
||
|
||
async function init() {
|
||
// Detect missing/template config
|
||
const credsConfigured = SUPABASE_URL && SUPABASE_URL !== 'PASTE_YOUR_SUPABASE_URL_HERE'
|
||
&& SUPABASE_ANON_KEY && SUPABASE_ANON_KEY !== 'PASTE_YOUR_ANON_KEY_HERE';
|
||
|
||
if (!credsConfigured) {
|
||
// Fallback to old setup screen so dev/early-version still works
|
||
const url = safeGet('sb_url');
|
||
const key = safeGet('sb_key');
|
||
if (!url || !key) { showSetup(); return; }
|
||
try {
|
||
sb = window.supabase.createClient(url, key, {
|
||
auth: { autoRefreshToken: true, persistSession: true, detectSessionInUrl: true }
|
||
});
|
||
} catch (e) {
|
||
toast('Failed to connect: ' + e.message, true);
|
||
showSetup();
|
||
return;
|
||
}
|
||
} else {
|
||
if (!window.supabase || !window.supabase.createClient) {
|
||
toast('Supabase library failed to load — check internet', true);
|
||
return;
|
||
}
|
||
try {
|
||
sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
|
||
auth: { autoRefreshToken: true, persistSession: true, detectSessionInUrl: true }
|
||
});
|
||
} catch (e) {
|
||
toast('Failed to connect: ' + e.message, true);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// Set up auth listener (handles magic-link callback automatically)
|
||
sb.auth.onAuthStateChange((event, session) => {
|
||
if (session && session.user) {
|
||
if (!currentUser || currentUser.id !== session.user.id) {
|
||
currentUser = session.user;
|
||
showApp();
|
||
renderUserChip();
|
||
renderStatusFilter();
|
||
loadAll();
|
||
}
|
||
} else if (event === 'SIGNED_OUT') {
|
||
currentUser = null;
|
||
games = [];
|
||
sessions = [];
|
||
showLogin();
|
||
}
|
||
});
|
||
|
||
// Check for existing session
|
||
const { data } = await sb.auth.getSession();
|
||
if (data.session && data.session.user) {
|
||
currentUser = data.session.user;
|
||
showApp();
|
||
renderUserChip();
|
||
renderStatusFilter();
|
||
loadAll();
|
||
} else {
|
||
showLogin();
|
||
}
|
||
}
|
||
|
||
async function sendMagicLink() {
|
||
const email = document.getElementById('loginEmail').value.trim();
|
||
const status = document.getElementById('loginStatus');
|
||
const btn = document.getElementById('loginBtn');
|
||
if (!email || !email.includes('@')) {
|
||
status.style.display = 'block';
|
||
status.style.color = 'var(--red)';
|
||
status.textContent = 'Please enter a valid email address.';
|
||
return;
|
||
}
|
||
btn.disabled = true;
|
||
btn.textContent = 'Sending...';
|
||
status.style.display = 'block';
|
||
status.style.color = 'var(--text-dim)';
|
||
status.textContent = 'Sending magic link...';
|
||
try {
|
||
const { error } = await sb.auth.signInWithOtp({
|
||
email,
|
||
options: { emailRedirectTo: location.origin + location.pathname }
|
||
});
|
||
if (error) throw error;
|
||
status.style.color = 'var(--phosphor)';
|
||
status.innerHTML = `✓ Check your inbox at <strong>${escapeHtml(email)}</strong>.<br>Click the link to sign in. You can close this tab.`;
|
||
btn.textContent = 'Link Sent';
|
||
} catch (e) {
|
||
status.style.color = 'var(--red)';
|
||
status.textContent = 'Failed: ' + e.message;
|
||
btn.disabled = false;
|
||
btn.textContent = 'Send Magic Link →';
|
||
}
|
||
}
|
||
|
||
async function logout() {
|
||
if (!confirm('Sign out of Stream Log?')) return;
|
||
await sb.auth.signOut();
|
||
// onAuthStateChange will handle UI swap
|
||
}
|
||
|
||
function renderUserChip() {
|
||
const el = document.getElementById('userChip');
|
||
if (!el || !currentUser) return;
|
||
const email = currentUser.email || 'signed in';
|
||
el.textContent = email.length > 22 ? email.slice(0, 20) + '…' : email;
|
||
el.title = email;
|
||
}
|
||
|
||
function saveSetup() {
|
||
const url = document.getElementById('setupUrl').value.trim();
|
||
const key = document.getElementById('setupKey').value.trim();
|
||
if (!url || !key) { toast('Both fields required', true); return; }
|
||
if (!safeSet('sb_url', url) || !safeSet('sb_key', key)) {
|
||
toast('Could not save to localStorage (is it disabled?)', true);
|
||
return;
|
||
}
|
||
location.reload();
|
||
}
|
||
|
||
function openSettings() {
|
||
// Now used to log out
|
||
logout();
|
||
}
|
||
|
||
// ============================================================
|
||
// DATA
|
||
// ============================================================
|
||
async function loadAll() {
|
||
setConn('connecting', false);
|
||
try {
|
||
const [g, s] = await Promise.all([
|
||
sb.from('games').select('*').order('created_at', { ascending: false }),
|
||
sb.from('sessions').select('*').order('streamed_on', { ascending: false })
|
||
]);
|
||
if (g.error) throw g.error;
|
||
if (s.error) throw s.error;
|
||
games = g.data || [];
|
||
sessions = s.data || [];
|
||
setConn('online', true);
|
||
render();
|
||
} catch (e) {
|
||
setConn('offline', false);
|
||
toast('Load failed: ' + e.message, true);
|
||
}
|
||
}
|
||
|
||
function setConn(text, ok) {
|
||
const el = document.getElementById('connStatus');
|
||
document.getElementById('connText').textContent = text;
|
||
el.classList.toggle('ok', ok);
|
||
}
|
||
|
||
// ============================================================
|
||
// RENDERING
|
||
// ============================================================
|
||
function render() {
|
||
renderStats();
|
||
renderStatusFilter();
|
||
renderPlatformFilter();
|
||
renderGames();
|
||
renderCalendar();
|
||
}
|
||
|
||
// ============================================================
|
||
// VIEW TOGGLE (Library / Calendar)
|
||
// ============================================================
|
||
function setView(v) {
|
||
currentView = v;
|
||
document.getElementById('libraryView').style.display = (v === 'library') ? '' : 'none';
|
||
document.getElementById('calendarView').style.display = (v === 'calendar') ? '' : 'none';
|
||
document.getElementById('viewLibraryBtn').classList.toggle('active', v === 'library');
|
||
document.getElementById('viewCalendarBtn').classList.toggle('active', v === 'calendar');
|
||
|
||
// First time switching to calendar — jump to the most recent month with sessions
|
||
if (v === 'calendar' && !calendarMonth.__userMoved) {
|
||
const newest = sessions
|
||
.map(s => s.streamed_on)
|
||
.filter(Boolean)
|
||
.sort()
|
||
.pop();
|
||
if (newest) {
|
||
const d = new Date(newest + 'T00:00:00');
|
||
calendarMonth = startOfMonth(d);
|
||
}
|
||
}
|
||
renderCalendar();
|
||
}
|
||
|
||
function prevMonth() {
|
||
calendarMonth = new Date(calendarMonth.getFullYear(), calendarMonth.getMonth() - 1, 1);
|
||
calendarMonth.__userMoved = true;
|
||
renderCalendar();
|
||
}
|
||
|
||
function nextMonth() {
|
||
calendarMonth = new Date(calendarMonth.getFullYear(), calendarMonth.getMonth() + 1, 1);
|
||
calendarMonth.__userMoved = true;
|
||
renderCalendar();
|
||
}
|
||
|
||
function goToToday() {
|
||
calendarMonth = startOfMonth(new Date());
|
||
calendarMonth.__userMoved = true;
|
||
renderCalendar();
|
||
}
|
||
|
||
// Build a YYYY-MM-DD string from a Date in local time (avoids UTC drift)
|
||
function isoDay(d) {
|
||
return d.getFullYear() + '-' +
|
||
String(d.getMonth() + 1).padStart(2, '0') + '-' +
|
||
String(d.getDate()).padStart(2, '0');
|
||
}
|
||
|
||
function renderCalendar() {
|
||
const grid = document.getElementById('calGrid');
|
||
const weekdaysEl = document.getElementById('calWeekdays');
|
||
const labelEl = document.getElementById('calMonthLabel');
|
||
const summaryEl = document.getElementById('calMonthSummary');
|
||
if (!grid || !weekdaysEl) return;
|
||
|
||
// Weekday header (Sun-first)
|
||
const weekdays = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
|
||
weekdaysEl.innerHTML = weekdays.map(w => `<div class="cal-weekday">${w}</div>`).join('');
|
||
|
||
// Month label
|
||
const monthName = calendarMonth.toLocaleString('en', { month: 'long' }).toUpperCase();
|
||
const yr = calendarMonth.getFullYear();
|
||
labelEl.textContent = `${monthName} ${yr}`;
|
||
|
||
// Apply search filter to which sessions are shown
|
||
const q = (document.getElementById('searchInput').value || '').trim().toLowerCase();
|
||
|
||
// Group sessions by day for this month (and any spillover days shown in grid)
|
||
// Build a map: 'YYYY-MM-DD' -> [ { session, game } ]
|
||
const byDay = {};
|
||
sessions.forEach(s => {
|
||
if (!s.streamed_on) return;
|
||
const g = games.find(x => x.id === s.game_id);
|
||
if (q && !(g && g.title.toLowerCase().includes(q))) return;
|
||
if (!byDay[s.streamed_on]) byDay[s.streamed_on] = [];
|
||
byDay[s.streamed_on].push({ session: s, game: g });
|
||
});
|
||
|
||
// Compute month-range stats for the summary
|
||
const monthYearMo = calendarMonth.getFullYear() * 12 + calendarMonth.getMonth();
|
||
let monthSessions = 0, monthMin = 0, monthGameSet = new Set();
|
||
Object.entries(byDay).forEach(([day, items]) => {
|
||
const dt = new Date(day + 'T00:00:00');
|
||
if (dt.getFullYear() * 12 + dt.getMonth() === monthYearMo) {
|
||
monthSessions += items.length;
|
||
items.forEach(it => {
|
||
monthMin += (it.session.duration_minutes || 0);
|
||
if (it.game) monthGameSet.add(it.game.id);
|
||
});
|
||
}
|
||
});
|
||
if (monthSessions === 0) {
|
||
summaryEl.textContent = q ? '· no matches this month' : '· no streams this month';
|
||
} else {
|
||
summaryEl.textContent = `· ${monthSessions} session${monthSessions===1?'':'s'} · ${(monthMin/60).toFixed(1)}h · ${monthGameSet.size} game${monthGameSet.size===1?'':'s'}`;
|
||
}
|
||
|
||
// Calendar grid: start from the Sunday on/before the 1st, end on the Saturday on/after the last
|
||
const firstOfMonth = new Date(calendarMonth);
|
||
const startDay = new Date(firstOfMonth);
|
||
startDay.setDate(startDay.getDate() - startDay.getDay()); // back to Sunday
|
||
|
||
const lastOfMonth = new Date(calendarMonth.getFullYear(), calendarMonth.getMonth() + 1, 0);
|
||
const endDay = new Date(lastOfMonth);
|
||
endDay.setDate(endDay.getDate() + (6 - endDay.getDay())); // forward to Saturday
|
||
|
||
const todayStr = isoDay(new Date());
|
||
const cells = [];
|
||
const cursor = new Date(startDay);
|
||
while (cursor <= endDay) {
|
||
const dayStr = isoDay(cursor);
|
||
const isOtherMonth = cursor.getMonth() !== calendarMonth.getMonth();
|
||
const isToday = dayStr === todayStr;
|
||
const items = byDay[dayStr] || [];
|
||
cells.push(buildDayCell(dayStr, cursor.getDate(), isOtherMonth, isToday, items));
|
||
cursor.setDate(cursor.getDate() + 1);
|
||
}
|
||
|
||
grid.innerHTML = cells.join('');
|
||
}
|
||
|
||
// One day cell HTML
|
||
function buildDayCell(dayStr, dayNum, isOtherMonth, isToday, items) {
|
||
const classes = ['cal-day'];
|
||
if (isOtherMonth) classes.push('other-month');
|
||
if (isToday) classes.push('today');
|
||
if (items.length) classes.push('has-sessions');
|
||
|
||
const totalMin = items.reduce((acc, it) => acc + (it.session.duration_minutes || 0), 0);
|
||
const hoursLabel = totalMin > 0 ? `${(totalMin/60).toFixed(1)}h` : '';
|
||
|
||
// Show up to 3 game pills, then "+N more"
|
||
const MAX = 3;
|
||
const shown = items.slice(0, MAX);
|
||
const extra = items.length - shown.length;
|
||
|
||
const gamesHtml = shown.map(it => {
|
||
const g = it.game;
|
||
const title = g ? g.title : '(deleted)';
|
||
const cover = g && g.cover_url
|
||
? `<img class="cal-game-cover" src="${escapeAttr(g.cover_url)}" onerror="this.outerHTML='<span class="cal-game-cover-fallback">?</span>'">`
|
||
: `<span class="cal-game-cover-fallback">?</span>`;
|
||
const gid = g ? g.id : '';
|
||
const click = gid
|
||
? `event.stopPropagation();openDetail('${gid}')`
|
||
: `event.stopPropagation()`;
|
||
return `<div class="cal-game" onclick="${click}" title="${escapeAttr(title)}">
|
||
${cover}<span class="cal-game-title">${escapeHtml(title)}</span>
|
||
</div>`;
|
||
}).join('');
|
||
|
||
const moreHtml = extra > 0
|
||
? `<div class="cal-more" onclick="event.stopPropagation();openDayDetail('${dayStr}')">+${extra} more</div>`
|
||
: '';
|
||
|
||
const cellClick = items.length
|
||
? ` onclick="openDayDetail('${dayStr}')"`
|
||
: '';
|
||
|
||
return `<div class="${classes.join(' ')}"${cellClick}>
|
||
<div class="cal-day-num">${dayNum}</div>
|
||
${hoursLabel ? `<div class="cal-day-hours">${hoursLabel}</div>` : ''}
|
||
${items.length ? `<div class="cal-games">${gamesHtml}${moreHtml}</div>` : ''}
|
||
</div>`;
|
||
}
|
||
|
||
// ============================================================
|
||
// DAY DETAIL MODAL
|
||
// ============================================================
|
||
function openDayDetail(dayStr) {
|
||
const dt = new Date(dayStr + 'T00:00:00');
|
||
const pretty = dt.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
|
||
const titleEl = document.getElementById('dayModalTitle');
|
||
const bodyEl = document.getElementById('dayModalBody');
|
||
|
||
titleEl.textContent = pretty.toUpperCase();
|
||
|
||
const items = sessions
|
||
.filter(s => s.streamed_on === dayStr)
|
||
.map(s => ({ session: s, game: games.find(g => g.id === s.game_id) }))
|
||
.sort((a, b) => {
|
||
// Sort by game title for stable ordering
|
||
const at = (a.game && a.game.title) || '';
|
||
const bt = (b.game && b.game.title) || '';
|
||
return at.localeCompare(bt);
|
||
});
|
||
|
||
if (!items.length) {
|
||
bodyEl.innerHTML = '<div class="day-detail-empty">No sessions logged on this day.</div>';
|
||
} else {
|
||
const totalMin = items.reduce((m, it) => m + (it.session.duration_minutes || 0), 0);
|
||
const peak = items.reduce((m, it) => Math.max(m, it.session.peak_viewers || 0), 0);
|
||
const summary = `<div class="detail-meta" style="margin-bottom:14px">
|
||
<span>▶ ${items.length} session${items.length===1?'':'s'}</span>
|
||
<span>⏱ ${(totalMin/60).toFixed(1)}h total</span>
|
||
${peak ? `<span>👁 peak ${peak}</span>` : ''}
|
||
</div>`;
|
||
|
||
const sessionList = items.map(it => {
|
||
const s = it.session;
|
||
const g = it.game;
|
||
const title = g ? g.title : '(deleted game)';
|
||
const cover = g && g.cover_url
|
||
? `<img src="${escapeAttr(g.cover_url)}" style="width:48px;height:64px;object-fit:cover;background:var(--bg);flex-shrink:0;border:1px solid var(--border)" onerror="this.style.display='none'">`
|
||
: `<div style="width:48px;height:64px;background:var(--bg);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-size:24px;color:var(--text-faint);flex-shrink:0">?</div>`;
|
||
const gameClick = g ? `onclick="closeDayModal();openDetail('${g.id}')"` : '';
|
||
const cursor = g ? 'cursor:pointer;' : '';
|
||
return `<div class="session" style="grid-template-columns:auto auto 1fr auto">
|
||
${cover}
|
||
<div class="session-date" style="align-self:center">${(s.duration_minutes ? (s.duration_minutes/60).toFixed(1) : '—')}<small>HOURS</small></div>
|
||
<div class="session-info" style="${cursor}" ${gameClick}>
|
||
<strong style="color:var(--phosphor);font-family:var(--font-display);font-size:18px;letter-spacing:1px;display:block;margin-bottom:4px">${escapeHtml(title)}</strong>
|
||
${g && g.platform ? `<span style="font-size:10px;color:var(--text-faint);letter-spacing:1.5px;text-transform:uppercase">${escapeHtml(g.platform)}</span>` : ''}
|
||
${s.peak_viewers ? `<span style="margin-left:10px;font-size:10px;color:var(--blue);letter-spacing:1px">👁 ${s.peak_viewers}</span>` : ''}
|
||
${s.notes ? `<div class="session-notes">${escapeHtml(s.notes)}</div>` : ''}
|
||
</div>
|
||
<button class="btn btn-sm btn-ghost" onclick="event.stopPropagation();closeDayModal();${g ? `openSessionModal('${g.id}','${s.id}')` : ''}" ${g?'':'disabled'}>✎</button>
|
||
</div>`;
|
||
}).join('');
|
||
|
||
bodyEl.innerHTML = summary + sessionList;
|
||
}
|
||
|
||
document.getElementById('dayModal').classList.add('open');
|
||
}
|
||
|
||
function closeDayModal() {
|
||
document.getElementById('dayModal').classList.remove('open');
|
||
}
|
||
|
||
function renderStats() {
|
||
document.getElementById('statTotal').textContent = games.length;
|
||
const totalMin = sessions.reduce((s, x) => s + (x.duration_minutes || 0), 0);
|
||
document.getElementById('statHours').textContent = (totalMin / 60).toFixed(1);
|
||
document.getElementById('statSessions').textContent = sessions.length + ' session' + (sessions.length === 1 ? '' : 's');
|
||
|
||
let peak = 0, peakGame = '—';
|
||
sessions.forEach(s => {
|
||
if ((s.peak_viewers || 0) > peak) {
|
||
peak = s.peak_viewers;
|
||
const g = games.find(gg => gg.id === s.game_id);
|
||
peakGame = g ? g.title : '—';
|
||
}
|
||
});
|
||
document.getElementById('statPeak').textContent = peak;
|
||
document.getElementById('statPeakGame').textContent = peakGame.length > 24 ? peakGame.slice(0,22)+'…' : peakGame;
|
||
|
||
const active = games.filter(g => g.status === 'playing').length;
|
||
document.getElementById('statActive').textContent = active;
|
||
}
|
||
|
||
function renderStatusFilter() {
|
||
const counts = {};
|
||
games.forEach(g => { counts[g.status] = (counts[g.status] || 0) + 1; });
|
||
const html = STATUS_OPTS.map(opt => {
|
||
const c = opt.key === 'all' ? games.length : (counts[opt.key] || 0);
|
||
return `<button class="pill ${opt.key === activeStatus ? 'active' : ''}" onclick="setStatus('${opt.key}')">${opt.label}<span class="count">${c}</span></button>`;
|
||
}).join('');
|
||
document.getElementById('statusFilter').innerHTML = html;
|
||
}
|
||
|
||
function setStatus(s) { activeStatus = s; render(); }
|
||
function setPlatform(p) { activePlatform = p; render(); }
|
||
|
||
function renderPlatformFilter() {
|
||
const el = document.getElementById('platformFilter');
|
||
if (!el) return;
|
||
const counts = {};
|
||
let hasUnknown = 0;
|
||
games.forEach(g => {
|
||
if (g.platform) counts[g.platform] = (counts[g.platform] || 0) + 1;
|
||
else hasUnknown++;
|
||
});
|
||
const platforms = Object.keys(counts).sort();
|
||
// Hide the row entirely if no games have platforms set
|
||
if (platforms.length === 0 && hasUnknown === games.length) {
|
||
el.innerHTML = '';
|
||
return;
|
||
}
|
||
let html = `<button class="pill ${activePlatform === 'all' ? 'active' : ''}" onclick="setPlatform('all')">All Platforms<span class="count">${games.length}</span></button>`;
|
||
platforms.forEach(p => {
|
||
html += `<button class="pill ${activePlatform === p ? 'active' : ''}" onclick="setPlatform('${escapeAttr(p)}')">${escapeHtml(p)}<span class="count">${counts[p]}</span></button>`;
|
||
});
|
||
if (hasUnknown > 0) {
|
||
html += `<button class="pill ${activePlatform === '__none__' ? 'active' : ''}" onclick="setPlatform('__none__')">No Platform<span class="count">${hasUnknown}</span></button>`;
|
||
}
|
||
el.innerHTML = html;
|
||
}
|
||
|
||
function renderGames() {
|
||
const q = document.getElementById('searchInput').value.trim().toLowerCase();
|
||
const sortBy = document.getElementById('sortBy').value;
|
||
|
||
let list = games.slice();
|
||
if (activeStatus !== 'all') list = list.filter(g => g.status === activeStatus);
|
||
if (activePlatform !== 'all') {
|
||
if (activePlatform === '__none__') list = list.filter(g => !g.platform);
|
||
else list = list.filter(g => g.platform === activePlatform);
|
||
}
|
||
if (q) list = list.filter(g => g.title.toLowerCase().includes(q));
|
||
|
||
// stats per game
|
||
const bg = {};
|
||
sessions.forEach(s => {
|
||
if (!bg[s.game_id]) bg[s.game_id] = { count: 0, last: null, min: 0 };
|
||
bg[s.game_id].count++;
|
||
bg[s.game_id].min += (s.duration_minutes || 0);
|
||
if (!bg[s.game_id].last || s.streamed_on > bg[s.game_id].last) bg[s.game_id].last = s.streamed_on;
|
||
});
|
||
|
||
if (sortBy === 'streamed') list.sort((a,b) => (bg[b.id]?.count||0) - (bg[a.id]?.count||0));
|
||
else if (sortBy === 'title') list.sort((a,b) => a.title.localeCompare(b.title));
|
||
else if (sortBy === 'last-stream') list.sort((a,b) => (bg[b.id]?.last||'').localeCompare(bg[a.id]?.last||''));
|
||
// 'recent' is the DB order
|
||
|
||
const grid = document.getElementById('gameGrid');
|
||
if (list.length === 0) {
|
||
grid.innerHTML = `<div class="empty"><h3>NO GAMES FOUND</h3><p>${games.length === 0 ? 'Click "New Game" to start tracking.' : 'Try a different filter or search.'}</p></div>`;
|
||
return;
|
||
}
|
||
|
||
grid.innerHTML = list.map(g => {
|
||
const st = bg[g.id] || { count: 0, last: null, min: 0 };
|
||
const hrs = (st.min/60).toFixed(1);
|
||
const gs = Array.isArray(g.genres) ? g.genres : [];
|
||
return `
|
||
<div class="card" onclick="openDetail('${g.id}')">
|
||
<div class="cover">
|
||
${g.cover_url ? `<img src="${escapeAttr(g.cover_url)}" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">` : ''}
|
||
<div class="no-cover" style="${g.cover_url ? 'display:none' : ''}">?</div>
|
||
<div class="status-badge status-${g.status}">${statusLabel(g.status)}</div>
|
||
${g.platform ? `<div class="platform-badge">${escapeHtml(g.platform)}</div>` : ''}
|
||
</div>
|
||
<div class="card-body">
|
||
<div class="card-title">${escapeHtml(g.title)}</div>
|
||
<div class="card-meta">
|
||
<span>${st.count} stream${st.count===1?'':'s'}</span>
|
||
<span>${hrs}h</span>
|
||
</div>
|
||
${gs.length ? `<div class="card-genres">${gs.slice(0,3).map(x => `<span class="card-genre">${escapeHtml(x)}</span>`).join('')}</div>` : ''}
|
||
</div>
|
||
</div>
|
||
`;
|
||
}).join('');
|
||
}
|
||
|
||
// ============================================================
|
||
// GAME MODAL
|
||
// ============================================================
|
||
function openGameModal(id) {
|
||
editingGameId = id || null;
|
||
const modal = document.getElementById('gameModal');
|
||
const title = document.getElementById('gameModalTitle');
|
||
const delBtn = document.getElementById('deleteGameBtn');
|
||
|
||
// Reset RAWG search
|
||
document.getElementById('rawgSearch').value = '';
|
||
document.getElementById('rawgResults').classList.remove('open');
|
||
document.getElementById('rawgResults').innerHTML = '';
|
||
updateRawgHint();
|
||
|
||
if (id) {
|
||
const g = games.find(x => x.id === id);
|
||
if (!g) return;
|
||
title.textContent = 'EDIT GAME';
|
||
document.getElementById('gameTitle').value = g.title || '';
|
||
document.getElementById('gameStatus').value = g.status || 'planned';
|
||
document.getElementById('gamePlatform').value = g.platform || '';
|
||
document.getElementById('gameStartedOn').value = g.started_on || '';
|
||
document.getElementById('gameCover').value = g.cover_url || '';
|
||
document.getElementById('gameNotes').value = g.notes || '';
|
||
currentGenres = Array.isArray(g.genres) ? [...g.genres] : [];
|
||
delBtn.style.display = 'inline-flex';
|
||
} else {
|
||
title.textContent = 'NEW GAME';
|
||
document.getElementById('gameTitle').value = '';
|
||
document.getElementById('gameStatus').value = 'planned';
|
||
document.getElementById('gamePlatform').value = '';
|
||
document.getElementById('gameStartedOn').value = '';
|
||
document.getElementById('gameCover').value = '';
|
||
document.getElementById('gameNotes').value = '';
|
||
currentGenres = [];
|
||
delBtn.style.display = 'none';
|
||
}
|
||
renderGenreTags();
|
||
document.getElementById('genreInput').value = '';
|
||
showCoverPreview(document.getElementById('gameCover').value || null);
|
||
modal.classList.add('open');
|
||
setTimeout(() => {
|
||
const input = id ? document.getElementById('gameTitle') : document.getElementById('rawgSearch');
|
||
input.focus();
|
||
}, 50);
|
||
}
|
||
|
||
function closeGameModal() {
|
||
document.getElementById('gameModal').classList.remove('open');
|
||
document.getElementById('rawgResults').classList.remove('open');
|
||
editingGameId = null;
|
||
}
|
||
|
||
// ============================================================
|
||
// RAWG GAME DATABASE SEARCH
|
||
// ============================================================
|
||
function getRawgKey() { return safeGet('rawg_key') || ''; }
|
||
function setRawgKey(k) { safeSet('rawg_key', k); }
|
||
|
||
function updateRawgHint() {
|
||
const hint = document.getElementById('rawgHint');
|
||
if (!hint) return;
|
||
if (getRawgKey()) {
|
||
hint.textContent = '(RAWG · connected)';
|
||
hint.classList.remove('missing');
|
||
} else {
|
||
hint.innerHTML = '(RAWG · <a href="#" onclick="promptRawgKey();return false" style="color:var(--amber);text-decoration:underline">add free API key</a>)';
|
||
hint.classList.add('missing');
|
||
}
|
||
}
|
||
|
||
function promptRawgKey() {
|
||
const current = getRawgKey();
|
||
const msg = 'Enter your RAWG API key (get one free at rawg.io/apidocs):';
|
||
const k = prompt(msg, current);
|
||
if (k !== null) {
|
||
setRawgKey(k.trim());
|
||
updateRawgHint();
|
||
if (k.trim()) toast('RAWG key saved');
|
||
}
|
||
}
|
||
|
||
function onRawgInput(e) {
|
||
const q = e.target.value.trim();
|
||
clearTimeout(rawgSearchTimer);
|
||
const results = document.getElementById('rawgResults');
|
||
|
||
if (!q) {
|
||
results.classList.remove('open');
|
||
results.innerHTML = '';
|
||
return;
|
||
}
|
||
|
||
if (!getRawgKey()) {
|
||
results.innerHTML = `<div class="rawg-setup-prompt">
|
||
No RAWG API key saved.<br>
|
||
<button class="btn btn-sm" onclick="promptRawgKey()">Add Free API Key</button>
|
||
</div>`;
|
||
results.classList.add('open');
|
||
return;
|
||
}
|
||
|
||
// Debounce
|
||
rawgSearchTimer = setTimeout(() => doRawgSearch(q), 350);
|
||
}
|
||
|
||
async function doRawgSearch(q) {
|
||
if (q === rawgLastQuery) return;
|
||
rawgLastQuery = q;
|
||
const spinner = document.getElementById('rawgSpinner');
|
||
const results = document.getElementById('rawgResults');
|
||
spinner.style.display = 'block';
|
||
|
||
try {
|
||
const url = `https://api.rawg.io/api/games?key=${encodeURIComponent(getRawgKey())}&search=${encodeURIComponent(q)}&page_size=8`;
|
||
const res = await fetch(url);
|
||
if (!res.ok) throw new Error('HTTP ' + res.status + (res.status === 401 ? ' — invalid API key' : ''));
|
||
const data = await res.json();
|
||
renderRawgResults(data.results || []);
|
||
} catch (e) {
|
||
results.innerHTML = `<div class="rawg-empty" style="color:var(--red)">Search failed: ${escapeHtml(e.message)}</div>`;
|
||
results.classList.add('open');
|
||
} finally {
|
||
spinner.style.display = 'none';
|
||
}
|
||
}
|
||
|
||
function renderRawgResults(list) {
|
||
const results = document.getElementById('rawgResults');
|
||
if (!list.length) {
|
||
results.innerHTML = '<div class="rawg-empty">No matches — enter title manually below</div>';
|
||
results.classList.add('open');
|
||
return;
|
||
}
|
||
results.innerHTML = list.map(g => {
|
||
const year = g.released ? g.released.slice(0,4) : '—';
|
||
const platforms = (g.parent_platforms || []).map(p => p.platform.name).slice(0, 3).join(' · ');
|
||
const img = g.background_image || '';
|
||
const payload = encodeURIComponent(JSON.stringify({
|
||
title: g.name,
|
||
cover: img,
|
||
genres: (g.genres || []).map(x => x.name)
|
||
}));
|
||
return `<div class="rawg-result" onclick="pickRawgGame('${payload}')">
|
||
${img ? `<img src="${escapeAttr(img)}" onerror="this.style.visibility='hidden'">` : '<img>'}
|
||
<div class="rawg-result-info">
|
||
<div class="rawg-result-title">${escapeHtml(g.name)}</div>
|
||
<div class="rawg-result-meta">${year}${platforms ? ' · ' + escapeHtml(platforms) : ''}</div>
|
||
</div>
|
||
</div>`;
|
||
}).join('');
|
||
results.classList.add('open');
|
||
}
|
||
|
||
function pickRawgGame(payload) {
|
||
const g = JSON.parse(decodeURIComponent(payload));
|
||
document.getElementById('gameTitle').value = g.title || '';
|
||
document.getElementById('gameCover').value = g.cover || '';
|
||
showCoverPreview(g.cover || null);
|
||
if (Array.isArray(g.genres) && g.genres.length) {
|
||
// Merge, dedupe
|
||
g.genres.forEach(x => {
|
||
if (!currentGenres.some(y => y.toLowerCase() === x.toLowerCase())) {
|
||
currentGenres.push(x);
|
||
}
|
||
});
|
||
renderGenreTags();
|
||
}
|
||
document.getElementById('rawgSearch').value = '';
|
||
document.getElementById('rawgResults').classList.remove('open');
|
||
rawgLastQuery = '';
|
||
toast('Game imported');
|
||
}
|
||
|
||
// ============================================================
|
||
// GENRE TAGS
|
||
// ============================================================
|
||
function renderGenreTags() {
|
||
const el = document.getElementById('genreTags');
|
||
if (!el) return;
|
||
el.innerHTML = currentGenres.map((g, i) =>
|
||
`<span class="genre-chip">${escapeHtml(g)}<button type="button" onclick="removeGenre(${i})" title="Remove">×</button></span>`
|
||
).join('');
|
||
}
|
||
function addGenre(name) {
|
||
const clean = (name || '').trim();
|
||
if (!clean) return;
|
||
if (currentGenres.some(g => g.toLowerCase() === clean.toLowerCase())) return;
|
||
currentGenres.push(clean);
|
||
renderGenreTags();
|
||
}
|
||
function removeGenre(i) {
|
||
currentGenres.splice(i, 1);
|
||
renderGenreTags();
|
||
}
|
||
function onGenreKeydown(e) {
|
||
if (e.key === 'Enter' || e.key === ',') {
|
||
e.preventDefault();
|
||
addGenre(e.target.value);
|
||
e.target.value = '';
|
||
} else if (e.key === 'Backspace' && !e.target.value && currentGenres.length) {
|
||
currentGenres.pop();
|
||
renderGenreTags();
|
||
}
|
||
}
|
||
|
||
async function saveGame() {
|
||
const title = document.getElementById('gameTitle').value.trim();
|
||
if (!title) { toast('Title required', true); return; }
|
||
const payload = {
|
||
title,
|
||
status: document.getElementById('gameStatus').value,
|
||
platform: document.getElementById('gamePlatform').value || null,
|
||
genres: currentGenres.length ? currentGenres : null,
|
||
started_on: document.getElementById('gameStartedOn').value || null,
|
||
cover_url: document.getElementById('gameCover').value.trim() || null,
|
||
notes: document.getElementById('gameNotes').value.trim() || null
|
||
};
|
||
try {
|
||
if (editingGameId) {
|
||
const { error } = await sb.from('games').update(payload).eq('id', editingGameId);
|
||
if (error) throw error;
|
||
toast('Game updated');
|
||
} else {
|
||
const { error } = await sb.from('games').insert({ ...payload, user_id: currentUser.id });
|
||
if (error) throw error;
|
||
toast('Game added');
|
||
}
|
||
closeGameModal();
|
||
await loadAll();
|
||
} catch (e) { toast('Save failed: ' + e.message, true); }
|
||
}
|
||
|
||
async function deleteGame() {
|
||
if (!editingGameId) return;
|
||
if (!confirm('Delete this game and all its sessions? This cannot be undone.')) return;
|
||
try {
|
||
const { error } = await sb.from('games').delete().eq('id', editingGameId);
|
||
if (error) throw error;
|
||
toast('Deleted');
|
||
closeGameModal();
|
||
closeDetail();
|
||
await loadAll();
|
||
} catch (e) { toast('Delete failed: ' + e.message, true); }
|
||
}
|
||
|
||
// ============================================================
|
||
// DETAIL MODAL
|
||
// ============================================================
|
||
function openDetail(id) {
|
||
const g = games.find(x => x.id === id);
|
||
if (!g) return;
|
||
currentDetailGameId = id;
|
||
const mySessions = sessions.filter(s => s.game_id === id)
|
||
.sort((a,b) => b.streamed_on.localeCompare(a.streamed_on));
|
||
|
||
const totalMin = mySessions.reduce((s,x) => s + (x.duration_minutes||0), 0);
|
||
const peak = mySessions.reduce((m,x) => Math.max(m, x.peak_viewers||0), 0);
|
||
|
||
document.getElementById('detailBody').innerHTML = `
|
||
<div class="detail-grid">
|
||
<div class="detail-cover">
|
||
${g.cover_url ? `<img src="${escapeAttr(g.cover_url)}" onerror="this.parentElement.innerHTML='<div style=\\'display:flex;height:100%;align-items:center;justify-content:center;font-family:var(--font-display);font-size:48px;color:var(--text-faint)\\'>?</div>'">` : `<div style="display:flex;height:100%;align-items:center;justify-content:center;font-family:var(--font-display);font-size:48px;color:var(--text-faint)">?</div>`}
|
||
</div>
|
||
<div class="detail-info">
|
||
<div class="detail-title">${escapeHtml(g.title)}</div>
|
||
<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px">
|
||
<span class="status-badge status-${g.status}" style="position:static">${statusLabel(g.status)}</span>
|
||
${g.platform ? `<span class="platform-badge" style="position:static">${escapeHtml(g.platform)}</span>` : ''}
|
||
</div>
|
||
<div class="detail-meta">
|
||
<span>▶ ${mySessions.length} session${mySessions.length===1?'':'s'}</span>
|
||
<span>⏱ ${(totalMin/60).toFixed(1)}h</span>
|
||
<span>👁 peak ${peak}</span>
|
||
${g.started_on ? `<span>📅 started ${formatDate(g.started_on)}</span>` : ''}
|
||
</div>
|
||
${Array.isArray(g.genres) && g.genres.length ? `<div class="card-genres" style="margin-bottom:10px">${g.genres.map(x => `<span class="card-genre">${escapeHtml(x)}</span>`).join('')}</div>` : ''}
|
||
${g.notes ? `<div class="detail-notes">${escapeHtml(g.notes)}</div>` : ''}
|
||
<div style="margin-top:12px;display:flex;gap:6px">
|
||
<button class="btn btn-sm" onclick="openGameModal('${g.id}')">Edit Game</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="sessions-head">
|
||
<h3>STREAM SESSIONS</h3>
|
||
<button class="btn btn-primary btn-sm" onclick="openSessionModal('${g.id}')">+ Log Session</button>
|
||
</div>
|
||
${mySessions.length === 0 ? '<div class="empty" style="padding:30px"><p>No sessions logged yet.</p></div>' : mySessions.map(s => {
|
||
const d = new Date(s.streamed_on + 'T00:00:00');
|
||
const day = d.getDate();
|
||
const mon = d.toLocaleString('en', { month: 'short' }).toUpperCase();
|
||
const yr = d.getFullYear();
|
||
return `
|
||
<div class="session">
|
||
<div class="session-date">${day}<small>${mon} ${yr}</small></div>
|
||
<div class="session-info">
|
||
${s.duration_minutes ? `<strong>${(s.duration_minutes/60).toFixed(1)}h</strong>` : ''}
|
||
${s.peak_viewers ? `<strong>👁 ${s.peak_viewers}</strong>` : ''}
|
||
${s.notes ? `<div class="session-notes">${escapeHtml(s.notes)}</div>` : ''}
|
||
</div>
|
||
<button class="btn btn-sm btn-ghost" onclick="openSessionModal('${g.id}','${s.id}')">✎</button>
|
||
</div>
|
||
`;
|
||
}).join('')}
|
||
`;
|
||
document.getElementById('detailModal').classList.add('open');
|
||
}
|
||
|
||
function closeDetail() {
|
||
document.getElementById('detailModal').classList.remove('open');
|
||
currentDetailGameId = null;
|
||
}
|
||
|
||
// ============================================================
|
||
// SESSION MODAL
|
||
// ============================================================
|
||
function openSessionModal(gameId, sessionId) {
|
||
editingSessionId = sessionId || null;
|
||
currentDetailGameId = gameId;
|
||
const title = document.getElementById('sessionModalTitle');
|
||
const delBtn = document.getElementById('deleteSessionBtn');
|
||
|
||
if (sessionId) {
|
||
const s = sessions.find(x => x.id === sessionId);
|
||
if (!s) return;
|
||
title.textContent = 'EDIT SESSION';
|
||
document.getElementById('sessionDate').value = s.streamed_on;
|
||
document.getElementById('sessionDuration').value = s.duration_minutes || '';
|
||
document.getElementById('sessionPeak').value = s.peak_viewers || '';
|
||
document.getElementById('sessionNotes').value = s.notes || '';
|
||
delBtn.style.display = 'inline-flex';
|
||
} else {
|
||
title.textContent = 'LOG SESSION';
|
||
document.getElementById('sessionDate').value = new Date().toISOString().slice(0,10);
|
||
document.getElementById('sessionDuration').value = '';
|
||
document.getElementById('sessionPeak').value = '';
|
||
document.getElementById('sessionNotes').value = '';
|
||
delBtn.style.display = 'none';
|
||
}
|
||
document.getElementById('sessionModal').classList.add('open');
|
||
}
|
||
|
||
function closeSessionModal() {
|
||
document.getElementById('sessionModal').classList.remove('open');
|
||
editingSessionId = null;
|
||
}
|
||
|
||
async function saveSession() {
|
||
const date = document.getElementById('sessionDate').value;
|
||
if (!date) { toast('Date required', true); return; }
|
||
const dur = document.getElementById('sessionDuration').value;
|
||
const peak = document.getElementById('sessionPeak').value;
|
||
const payload = {
|
||
game_id: currentDetailGameId,
|
||
streamed_on: date,
|
||
duration_minutes: dur ? parseInt(dur) : null,
|
||
peak_viewers: peak ? parseInt(peak) : null,
|
||
notes: document.getElementById('sessionNotes').value.trim() || null
|
||
};
|
||
try {
|
||
if (editingSessionId) {
|
||
const { error } = await sb.from('sessions').update(payload).eq('id', editingSessionId);
|
||
if (error) throw error;
|
||
toast('Session updated');
|
||
} else {
|
||
const { error } = await sb.from('sessions').insert({ ...payload, user_id: currentUser.id });
|
||
if (error) throw error;
|
||
// Auto-fill started_on if this is the first session and the field is empty
|
||
const g = games.find(x => x.id === currentDetailGameId);
|
||
const existingSessions = sessions.filter(s => s.game_id === currentDetailGameId);
|
||
if (g && !g.started_on && existingSessions.length === 0) {
|
||
await sb.from('games').update({ started_on: date }).eq('id', currentDetailGameId);
|
||
}
|
||
toast('Session logged');
|
||
}
|
||
closeSessionModal();
|
||
await loadAll();
|
||
if (currentDetailGameId) openDetail(currentDetailGameId);
|
||
} catch (e) { toast('Save failed: ' + e.message, true); }
|
||
}
|
||
|
||
async function deleteSession() {
|
||
if (!editingSessionId) return;
|
||
if (!confirm('Delete this session?')) return;
|
||
try {
|
||
const { error } = await sb.from('sessions').delete().eq('id', editingSessionId);
|
||
if (error) throw error;
|
||
toast('Session deleted');
|
||
closeSessionModal();
|
||
await loadAll();
|
||
if (currentDetailGameId) openDetail(currentDetailGameId);
|
||
} catch (e) { toast('Delete failed: ' + e.message, true); }
|
||
}
|
||
|
||
// ============================================================
|
||
// UTILS
|
||
// ============================================================
|
||
function statusLabel(s) {
|
||
return ({
|
||
playing: 'Playing',
|
||
completed: 'Completed',
|
||
dropped: 'Dropped',
|
||
hold: 'On Hold',
|
||
variety: 'Variety',
|
||
planned: 'Planned'
|
||
})[s] || s;
|
||
}
|
||
|
||
function formatDate(d) {
|
||
if (!d) return '';
|
||
const dt = new Date(d + 'T00:00:00');
|
||
return dt.toLocaleDateString('en', { month: 'short', day: 'numeric', year: 'numeric' });
|
||
}
|
||
|
||
// ============================================================
|
||
// COVER IMAGE UPLOAD
|
||
// ============================================================
|
||
const COVER_BUCKET = 'covers';
|
||
const COVER_MAX_BYTES = 5 * 1024 * 1024; // 5MB
|
||
const COVER_RESIZE_MAX = 800; // resize down to max 800px on longest edge
|
||
|
||
function showCoverPreview(url) {
|
||
const img = document.getElementById('coverPreviewImg');
|
||
const ph = document.getElementById('coverPlaceholder');
|
||
const clearBtn = document.getElementById('coverClearBtn');
|
||
if (url) {
|
||
img.src = url;
|
||
img.style.display = 'block';
|
||
ph.style.display = 'none';
|
||
clearBtn.style.display = 'block';
|
||
} else {
|
||
img.style.display = 'none';
|
||
img.removeAttribute('src');
|
||
ph.style.display = 'block';
|
||
clearBtn.style.display = 'none';
|
||
}
|
||
}
|
||
|
||
function clearCoverImage() {
|
||
document.getElementById('gameCover').value = '';
|
||
showCoverPreview(null);
|
||
}
|
||
|
||
// Sync URL input → preview as user types/pastes a URL
|
||
function onCoverUrlInput() {
|
||
const v = document.getElementById('gameCover').value.trim();
|
||
showCoverPreview(v || null);
|
||
}
|
||
|
||
// Resize image client-side to keep uploads small
|
||
async function resizeImageFile(file, maxEdge) {
|
||
return new Promise((resolve, reject) => {
|
||
const img = new Image();
|
||
const url = URL.createObjectURL(file);
|
||
img.onload = () => {
|
||
URL.revokeObjectURL(url);
|
||
let { width: w, height: h } = img;
|
||
if (Math.max(w, h) > maxEdge) {
|
||
const scale = maxEdge / Math.max(w, h);
|
||
w = Math.round(w * scale);
|
||
h = Math.round(h * scale);
|
||
}
|
||
const canvas = document.createElement('canvas');
|
||
canvas.width = w;
|
||
canvas.height = h;
|
||
const ctx = canvas.getContext('2d');
|
||
ctx.drawImage(img, 0, 0, w, h);
|
||
// Keep PNG for transparency, otherwise convert to JPEG for smaller size
|
||
const isPng = file.type === 'image/png';
|
||
const mime = isPng ? 'image/png' : 'image/jpeg';
|
||
const ext = isPng ? 'png' : 'jpg';
|
||
canvas.toBlob(blob => {
|
||
if (!blob) { reject(new Error('Resize failed')); return; }
|
||
resolve({ blob, ext, mime });
|
||
}, mime, 0.85);
|
||
};
|
||
img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('Could not read image')); };
|
||
img.src = url;
|
||
});
|
||
}
|
||
|
||
async function uploadCoverFile(file) {
|
||
if (!currentUser) { toast('Sign in first', true); return; }
|
||
if (!file || !file.type.startsWith('image/')) { toast('Not an image file', true); return; }
|
||
if (file.size > COVER_MAX_BYTES) { toast('Image too large (>5MB)', true); return; }
|
||
|
||
const drop = document.getElementById('coverDrop');
|
||
const prompt = drop.querySelector('.cover-drop-prompt');
|
||
const uploading = document.getElementById('coverUploading');
|
||
const status = document.getElementById('coverUploadStatus');
|
||
prompt.style.display = 'none';
|
||
uploading.style.display = 'block';
|
||
status.textContent = 'Resizing...';
|
||
|
||
try {
|
||
// Resize to keep storage small
|
||
const { blob, ext, mime } = await resizeImageFile(file, COVER_RESIZE_MAX);
|
||
status.textContent = 'Uploading...';
|
||
|
||
// Path: <user_id>/<timestamp>-<random>.<ext> → keeps each user's images in their own folder
|
||
const filename = `${currentUser.id}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
||
|
||
const { error: uploadError } = await sb.storage
|
||
.from(COVER_BUCKET)
|
||
.upload(filename, blob, { contentType: mime, cacheControl: '31536000', upsert: false });
|
||
if (uploadError) throw uploadError;
|
||
|
||
// Get public URL
|
||
const { data: urlData } = sb.storage.from(COVER_BUCKET).getPublicUrl(filename);
|
||
const publicUrl = urlData?.publicUrl;
|
||
if (!publicUrl) throw new Error('Could not get public URL');
|
||
|
||
document.getElementById('gameCover').value = publicUrl;
|
||
showCoverPreview(publicUrl);
|
||
toast('Cover uploaded');
|
||
} catch (e) {
|
||
toast('Upload failed: ' + (e.message || e), true);
|
||
} finally {
|
||
uploading.style.display = 'none';
|
||
prompt.style.display = 'block';
|
||
}
|
||
}
|
||
|
||
function setupCoverDropZone() {
|
||
const drop = document.getElementById('coverDrop');
|
||
const fileInput = document.getElementById('coverFileInput');
|
||
if (!drop || !fileInput || drop.dataset.wired) return;
|
||
drop.dataset.wired = '1';
|
||
|
||
fileInput.addEventListener('change', e => {
|
||
const f = e.target.files && e.target.files[0];
|
||
if (f) uploadCoverFile(f);
|
||
e.target.value = ''; // reset so same file can be picked again
|
||
});
|
||
|
||
['dragenter', 'dragover'].forEach(ev => {
|
||
drop.addEventListener(ev, e => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
drop.classList.add('dragover');
|
||
});
|
||
});
|
||
['dragleave', 'dragend'].forEach(ev => {
|
||
drop.addEventListener(ev, e => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
drop.classList.remove('dragover');
|
||
});
|
||
});
|
||
drop.addEventListener('drop', e => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
drop.classList.remove('dragover');
|
||
const f = e.dataTransfer?.files && e.dataTransfer.files[0];
|
||
if (f) uploadCoverFile(f);
|
||
});
|
||
|
||
// Wire URL input → preview
|
||
const urlInput = document.getElementById('gameCover');
|
||
if (urlInput) urlInput.addEventListener('input', onCoverUrlInput);
|
||
}
|
||
|
||
// ============================================================
|
||
// EXPORT
|
||
// ============================================================
|
||
function openExportMenu() { document.getElementById('exportModal').classList.add('open'); }
|
||
function closeExportMenu() { document.getElementById('exportModal').classList.remove('open'); }
|
||
|
||
function csvCell(v) {
|
||
if (v === null || v === undefined) return '';
|
||
let s = Array.isArray(v) ? v.join('; ') : String(v);
|
||
// Quote if contains comma, quote, newline, or leading/trailing space
|
||
if (/[",\n\r]/.test(s) || s !== s.trim()) {
|
||
s = '"' + s.replace(/"/g, '""') + '"';
|
||
}
|
||
return s;
|
||
}
|
||
|
||
function csvRows(rows, headers) {
|
||
const headerLine = headers.map(csvCell).join(',');
|
||
const lines = rows.map(r => headers.map(h => csvCell(r[h])).join(','));
|
||
return [headerLine, ...lines].join('\n');
|
||
}
|
||
|
||
function download(filename, content, mime) {
|
||
const blob = new Blob([content], { type: mime || 'text/plain;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = filename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
setTimeout(() => {
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
}, 100);
|
||
}
|
||
|
||
function dateStamp() {
|
||
const d = new Date();
|
||
return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
|
||
}
|
||
|
||
function exportCSV(kind) {
|
||
const ds = dateStamp();
|
||
if (kind === 'games') {
|
||
const rows = games.map(g => {
|
||
const mySessions = sessions.filter(s => s.game_id === g.id);
|
||
const totalMin = mySessions.reduce((a,s) => a + (s.duration_minutes||0), 0);
|
||
const peak = mySessions.reduce((m,s) => Math.max(m, s.peak_viewers||0), 0);
|
||
const lastStream = mySessions.map(s=>s.streamed_on).sort().pop() || '';
|
||
return {
|
||
title: g.title,
|
||
status: g.status,
|
||
platform: g.platform || '',
|
||
genres: g.genres || [],
|
||
started_on: g.started_on || '',
|
||
session_count: mySessions.length,
|
||
total_hours: (totalMin/60).toFixed(2),
|
||
peak_viewers: peak,
|
||
last_streamed: lastStream,
|
||
notes: g.notes || '',
|
||
cover_url: g.cover_url || '',
|
||
created_at: g.created_at
|
||
};
|
||
});
|
||
const headers = ['title','status','platform','genres','started_on','session_count','total_hours','peak_viewers','last_streamed','notes','cover_url','created_at'];
|
||
download(`stream-log-games-${ds}.csv`, csvRows(rows, headers), 'text/csv;charset=utf-8');
|
||
toast('Games exported');
|
||
} else if (kind === 'sessions') {
|
||
const rows = sessions.map(s => {
|
||
const g = games.find(x => x.id === s.game_id);
|
||
return {
|
||
streamed_on: s.streamed_on,
|
||
game_title: g ? g.title : '(unknown)',
|
||
duration_minutes: s.duration_minutes || '',
|
||
duration_hours: s.duration_minutes ? (s.duration_minutes/60).toFixed(2) : '',
|
||
peak_viewers: s.peak_viewers || '',
|
||
notes: s.notes || '',
|
||
created_at: s.created_at
|
||
};
|
||
});
|
||
// Sort by date descending
|
||
rows.sort((a,b) => (b.streamed_on||'').localeCompare(a.streamed_on||''));
|
||
const headers = ['streamed_on','game_title','duration_minutes','duration_hours','peak_viewers','notes','created_at'];
|
||
download(`stream-log-sessions-${ds}.csv`, csvRows(rows, headers), 'text/csv;charset=utf-8');
|
||
toast('Sessions exported');
|
||
} else if (kind === 'combined') {
|
||
const rows = sessions.map(s => {
|
||
const g = games.find(x => x.id === s.game_id) || {};
|
||
return {
|
||
streamed_on: s.streamed_on,
|
||
game_title: g.title || '(unknown)',
|
||
status: g.status || '',
|
||
platform: g.platform || '',
|
||
genres: g.genres || [],
|
||
duration_minutes: s.duration_minutes || '',
|
||
duration_hours: s.duration_minutes ? (s.duration_minutes/60).toFixed(2) : '',
|
||
peak_viewers: s.peak_viewers || '',
|
||
session_notes: s.notes || '',
|
||
game_notes: g.notes || ''
|
||
};
|
||
});
|
||
rows.sort((a,b) => (b.streamed_on||'').localeCompare(a.streamed_on||''));
|
||
const headers = ['streamed_on','game_title','status','platform','genres','duration_minutes','duration_hours','peak_viewers','session_notes','game_notes'];
|
||
download(`stream-log-combined-${ds}.csv`, csvRows(rows, headers), 'text/csv;charset=utf-8');
|
||
toast('Combined export saved');
|
||
}
|
||
closeExportMenu();
|
||
}
|
||
|
||
function exportJSON() {
|
||
const ds = dateStamp();
|
||
const data = {
|
||
exported_at: new Date().toISOString(),
|
||
version: 1,
|
||
games: games,
|
||
sessions: sessions
|
||
};
|
||
download(`stream-log-backup-${ds}.json`, JSON.stringify(data, null, 2), 'application/json');
|
||
toast('Backup saved');
|
||
closeExportMenu();
|
||
}
|
||
|
||
// ============================================================
|
||
// TWITCH INTEGRATION
|
||
// ============================================================
|
||
const TWITCH_AUTH_URL = 'https://id.twitch.tv/oauth2/authorize';
|
||
const TWITCH_API = 'https://api.twitch.tv/helix';
|
||
|
||
function twitchGet(k) { return safeGet('twitch_' + k) || ''; }
|
||
function twitchSet(k, v) { return safeSet('twitch_' + k, v); }
|
||
function twitchRemove(k) { safeRemove('twitch_' + k); }
|
||
|
||
function twitchRedirectUri() {
|
||
// Use location.origin + pathname (strip query/hash for a clean redirect target)
|
||
return location.origin + location.pathname;
|
||
}
|
||
|
||
function twitchConnected() {
|
||
return !!(twitchGet('client_id') && twitchGet('token') && twitchGet('user_id'));
|
||
}
|
||
|
||
function refreshTwitchButton() {
|
||
const btn = document.getElementById('twitchBtn');
|
||
if (!btn) return;
|
||
if (twitchConnected()) {
|
||
btn.classList.add('connected');
|
||
btn.textContent = '🟣 Import VODs';
|
||
} else {
|
||
btn.classList.remove('connected');
|
||
btn.textContent = '🟣 Twitch';
|
||
}
|
||
}
|
||
|
||
function onTwitchButtonClick() {
|
||
if (twitchConnected()) openTwitchImport();
|
||
else openTwitchSetup();
|
||
}
|
||
|
||
function openTwitchSetup() {
|
||
document.getElementById('redirectUrlDisplay').textContent = twitchRedirectUri();
|
||
document.getElementById('twitchClientId').value = twitchGet('client_id');
|
||
document.getElementById('twitchUsername').value = twitchGet('username');
|
||
document.getElementById('twitchDisconnectBtn').style.display = twitchConnected() ? 'inline-flex' : 'none';
|
||
document.getElementById('twitchSetupModal').classList.add('open');
|
||
}
|
||
function closeTwitchSetup() { document.getElementById('twitchSetupModal').classList.remove('open'); }
|
||
|
||
function copyRedirect() {
|
||
const url = twitchRedirectUri();
|
||
navigator.clipboard?.writeText(url).then(() => toast('Redirect URL copied'), () => toast('Copy failed — select manually', true));
|
||
}
|
||
|
||
function twitchAuthorize() {
|
||
const clientId = document.getElementById('twitchClientId').value.trim();
|
||
const username = document.getElementById('twitchUsername').value.trim().toLowerCase();
|
||
if (!clientId) { toast('Client ID required', true); return; }
|
||
if (!username) { toast('Username required', true); return; }
|
||
twitchSet('client_id', clientId);
|
||
twitchSet('username', username);
|
||
twitchSet('pending_auth', '1');
|
||
// Implicit grant flow — no scopes needed to read public VOD list
|
||
const state = Math.random().toString(36).slice(2);
|
||
twitchSet('oauth_state', state);
|
||
const params = new URLSearchParams({
|
||
client_id: clientId,
|
||
redirect_uri: twitchRedirectUri(),
|
||
response_type: 'token',
|
||
scope: '',
|
||
state: state,
|
||
force_verify: 'false'
|
||
});
|
||
location.href = `${TWITCH_AUTH_URL}?${params.toString()}`;
|
||
}
|
||
|
||
function twitchDisconnect() {
|
||
if (!confirm('Disconnect from Twitch? Your imported sessions stay, but you\'ll need to re-authorize to import more.')) return;
|
||
['client_id','username','token','user_id','oauth_state','pending_auth'].forEach(twitchRemove);
|
||
closeTwitchSetup();
|
||
refreshTwitchButton();
|
||
toast('Twitch disconnected');
|
||
}
|
||
|
||
async function handleTwitchRedirect() {
|
||
// Check URL hash for OAuth response
|
||
if (!location.hash || !location.hash.includes('access_token=')) return false;
|
||
|
||
// IMPORTANT: Supabase magic-link login also lands here with #access_token=...
|
||
// Only treat the hash as a Twitch redirect if we actually initiated a Twitch
|
||
// OAuth flow (pending_auth flag set) AND the hash contains a 'state' param
|
||
// (Twitch implicit grant always includes one; Supabase magic links don't).
|
||
if (!twitchGet('pending_auth')) return false;
|
||
const params = new URLSearchParams(location.hash.slice(1));
|
||
if (!params.has('state')) return false;
|
||
|
||
const token = params.get('access_token');
|
||
const state = params.get('state');
|
||
const expectedState = twitchGet('oauth_state');
|
||
|
||
// Clear hash immediately so it doesn't stick around
|
||
history.replaceState(null, '', location.pathname + location.search);
|
||
|
||
if (!token) return false;
|
||
if (expectedState && state !== expectedState) {
|
||
toast('Twitch OAuth state mismatch — try again', true);
|
||
return false;
|
||
}
|
||
twitchSet('token', token);
|
||
twitchRemove('oauth_state');
|
||
twitchRemove('pending_auth');
|
||
|
||
// Resolve user_id from username
|
||
try {
|
||
const user = await twitchApi('/users?login=' + encodeURIComponent(twitchGet('username')));
|
||
if (user.data && user.data.length) {
|
||
twitchSet('user_id', user.data[0].id);
|
||
toast('Twitch connected');
|
||
refreshTwitchButton();
|
||
return true;
|
||
} else {
|
||
toast('Twitch username not found', true);
|
||
twitchRemove('token');
|
||
}
|
||
} catch (e) {
|
||
toast('Twitch connect failed: ' + e.message, true);
|
||
twitchRemove('token');
|
||
}
|
||
return false;
|
||
}
|
||
|
||
async function twitchApi(path) {
|
||
const res = await fetch(TWITCH_API + path, {
|
||
headers: {
|
||
'Authorization': 'Bearer ' + twitchGet('token'),
|
||
'Client-Id': twitchGet('client_id')
|
||
}
|
||
});
|
||
if (res.status === 401) {
|
||
// Token expired
|
||
twitchRemove('token');
|
||
twitchRemove('user_id');
|
||
refreshTwitchButton();
|
||
throw new Error('Twitch token expired — reconnect');
|
||
}
|
||
if (!res.ok) throw new Error('Twitch API ' + res.status);
|
||
return await res.json();
|
||
}
|
||
|
||
// Parse "6h26m14s" → minutes
|
||
function twitchDurationToMin(str) {
|
||
if (!str) return 0;
|
||
let mins = 0;
|
||
const h = str.match(/(\d+)h/); if (h) mins += parseInt(h[1]) * 60;
|
||
const m = str.match(/(\d+)m/); if (m) mins += parseInt(m[1]);
|
||
const s = str.match(/(\d+)s/); if (s) mins += Math.round(parseInt(s[1]) / 60);
|
||
return mins;
|
||
}
|
||
|
||
function twitchThumbUrl(url, w, h) {
|
||
// Twitch thumbnail URLs have {width}x{height} placeholders (literally with percent-encoded braces)
|
||
if (!url) return '';
|
||
return url.replace(/%\{width\}/g, w).replace(/%\{height\}/g, h).replace(/\{width\}/g, w).replace(/\{height\}/g, h);
|
||
}
|
||
|
||
let pendingVods = [];
|
||
|
||
async function openTwitchImport() {
|
||
document.getElementById('twitchImportModal').classList.add('open');
|
||
document.getElementById('twitchVodList').innerHTML = '<div class="rawg-empty" style="padding:30px">Loading VODs…</div>';
|
||
try {
|
||
const resp = await twitchApi('/videos?user_id=' + encodeURIComponent(twitchGet('user_id')) + '&type=archive&first=20');
|
||
pendingVods = resp.data || [];
|
||
renderVodList();
|
||
} catch (e) {
|
||
document.getElementById('twitchVodList').innerHTML = `<div class="rawg-empty" style="color:var(--red);padding:30px">${escapeHtml(e.message)}<br><br><button class="btn btn-sm" onclick="closeTwitchImport();openTwitchSetup()">Reconnect</button></div>`;
|
||
}
|
||
}
|
||
|
||
function closeTwitchImport() {
|
||
document.getElementById('twitchImportModal').classList.remove('open');
|
||
pendingVods = [];
|
||
}
|
||
|
||
function renderVodList() {
|
||
const importedVodIds = new Set(sessions.filter(s => s.twitch_vod_id).map(s => s.twitch_vod_id));
|
||
const gameOptions = games
|
||
.slice()
|
||
.sort((a,b) => a.title.localeCompare(b.title))
|
||
.map(g => `<option value="${g.id}">${escapeHtml(g.title)}</option>`).join('');
|
||
|
||
if (!pendingVods.length) {
|
||
document.getElementById('twitchVodList').innerHTML = '<div class="rawg-empty" style="padding:30px">No VODs found on your channel.</div>';
|
||
return;
|
||
}
|
||
|
||
document.getElementById('twitchVodList').innerHTML = pendingVods.map(v => {
|
||
const alreadyImported = importedVodIds.has(v.id);
|
||
const date = v.created_at ? v.created_at.slice(0,10) : '';
|
||
const durMin = twitchDurationToMin(v.duration);
|
||
const hrs = (durMin/60).toFixed(1);
|
||
const thumb = twitchThumbUrl(v.thumbnail_url, 160, 90);
|
||
return `
|
||
<div class="vod-item ${alreadyImported ? 'imported' : ''}" data-vod-id="${escapeAttr(v.id)}">
|
||
${thumb ? `<img class="vod-thumb" src="${escapeAttr(thumb)}" onerror="this.style.visibility='hidden'">` : '<div class="vod-thumb"></div>'}
|
||
<div class="vod-info">
|
||
<div class="vod-title" title="${escapeAttr(v.title || '')}">${escapeHtml(v.title || '(untitled)')}</div>
|
||
<div class="vod-meta">
|
||
<span>${date}</span>
|
||
<span>${hrs}h</span>
|
||
<span><a href="${escapeAttr(v.url || '#')}" target="_blank" style="color:var(--text-dim);text-decoration:underline">VOD ↗</a></span>
|
||
</div>
|
||
</div>
|
||
<div class="vod-pick">
|
||
${alreadyImported
|
||
? '<div class="imported-tag">✓ Already imported</div>'
|
||
: `<select data-vod-pick="${escapeAttr(v.id)}">
|
||
<option value="">— skip —</option>
|
||
${gameOptions}
|
||
</select>`}
|
||
</div>
|
||
</div>
|
||
`;
|
||
}).join('');
|
||
}
|
||
|
||
async function twitchImportSelected() {
|
||
const selects = document.querySelectorAll('[data-vod-pick]');
|
||
const jobs = [];
|
||
selects.forEach(sel => {
|
||
if (sel.value) {
|
||
const vodId = sel.getAttribute('data-vod-pick');
|
||
const vod = pendingVods.find(v => v.id === vodId);
|
||
if (vod) jobs.push({ vod, gameId: sel.value });
|
||
}
|
||
});
|
||
if (!jobs.length) { toast('Nothing selected', true); return; }
|
||
|
||
const btn = document.getElementById('twitchImportBtn');
|
||
btn.disabled = true;
|
||
btn.textContent = 'Importing...';
|
||
|
||
let ok = 0, fail = 0;
|
||
for (const job of jobs) {
|
||
const v = job.vod;
|
||
const payload = {
|
||
game_id: job.gameId,
|
||
streamed_on: v.created_at.slice(0,10),
|
||
duration_minutes: twitchDurationToMin(v.duration) || null,
|
||
peak_viewers: null,
|
||
notes: v.title || null,
|
||
twitch_vod_id: v.id,
|
||
user_id: currentUser.id
|
||
};
|
||
try {
|
||
const { error } = await sb.from('sessions').insert(payload);
|
||
if (error) throw error;
|
||
// Auto-fill started_on on the game if empty and no prior sessions
|
||
const g = games.find(x => x.id === job.gameId);
|
||
const existing = sessions.filter(s => s.game_id === job.gameId);
|
||
if (g && !g.started_on && existing.length === 0) {
|
||
await sb.from('games').update({ started_on: payload.streamed_on }).eq('id', job.gameId);
|
||
}
|
||
ok++;
|
||
} catch (e) {
|
||
console.error('Import failed for VOD', v.id, e);
|
||
fail++;
|
||
}
|
||
}
|
||
|
||
btn.disabled = false;
|
||
btn.textContent = 'Import Selected';
|
||
toast(`Imported ${ok}${fail ? ` (${fail} failed)` : ''}`, fail > 0);
|
||
closeTwitchImport();
|
||
await loadAll();
|
||
}
|
||
|
||
function escapeHtml(s) {
|
||
if (s == null) return '';
|
||
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||
}
|
||
function escapeAttr(s) { return escapeHtml(s); }
|
||
|
||
function toast(msg, isErr) {
|
||
const existing = document.querySelector('.toast');
|
||
if (existing) existing.remove();
|
||
const t = document.createElement('div');
|
||
t.className = 'toast' + (isErr ? ' error' : '');
|
||
t.textContent = msg;
|
||
document.body.appendChild(t);
|
||
setTimeout(() => t.remove(), 2800);
|
||
}
|
||
|
||
// ESC to close modals
|
||
document.addEventListener('keydown', e => {
|
||
if (e.key === 'Escape') {
|
||
document.querySelectorAll('.modal-backdrop.open').forEach(m => m.classList.remove('open'));
|
||
}
|
||
});
|
||
|
||
// Wait for DOM to be ready before running init
|
||
function bootstrap() {
|
||
const rawgInput = document.getElementById('rawgSearch');
|
||
if (rawgInput) rawgInput.addEventListener('input', onRawgInput);
|
||
const genreInput = document.getElementById('genreInput');
|
||
if (genreInput) {
|
||
genreInput.addEventListener('keydown', onGenreKeydown);
|
||
genreInput.addEventListener('blur', e => { if (e.target.value) { addGenre(e.target.value); e.target.value = ''; } });
|
||
}
|
||
setupCoverDropZone();
|
||
// Close RAWG results if clicking outside
|
||
document.addEventListener('click', e => {
|
||
if (!e.target.closest('.rawg-search-field')) {
|
||
document.getElementById('rawgResults')?.classList.remove('open');
|
||
}
|
||
});
|
||
// Handle Twitch OAuth redirect before normal init (non-blocking)
|
||
handleTwitchRedirect();
|
||
refreshTwitchButton();
|
||
init();
|
||
}
|
||
|
||
if (document.readyState === 'loading') {
|
||
document.addEventListener('DOMContentLoaded', bootstrap);
|
||
} else {
|
||
bootstrap();
|
||
}
|
||
</script>
|
||
</body>
|
||
</html>
|