<?php
// Standalone player: /player/?video=gulf-series/series-id/episode-01.mp4
$video = isset($_GET['video']) && is_string($_GET['video']) ? $_GET['video'] : '';
$video = ltrim($video, '/');
$parts = explode('/', $video);
$valid = $video !== '' && count($parts) >= 2 && !array_filter($parts, static function($p){ return $p === '' || $p === '.' || $p === '..'; }) && preg_match('~^(?:gulf-series|arabic-series|turkish-series)/[a-zA-Z0-9_./-]+\.mp4$~', $video);
// Videos remain on AlexHost. Validate the relative path without local filesystem checks.
// The browser fetches MP4 directly from videos.alooytv.work; no PHP proxying.
if (!$valid) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Invalid video path';
    exit;
}
$src = '/' . implode('/', array_map('rawurlencode', explode('/', $video)));
$episode_title = isset($_GET['title']) && is_string($_GET['title']) ? mb_substr(strip_tags($_GET['title']), 0, 120) : basename($video, '.mp4');
header('Content-Type: text/html; charset=UTF-8');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('X-Content-Type-Options: nosniff');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Lumen Player</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;800&display=swap">
<style>
:root{--bg:#f1f2f9;--panel:rgba(255,255,255,.75);--text:#14172b;--muted:#6a7094;--line:rgba(20,23,43,.12);--a:#4f5bff;--b:#9b5cff;--glow:.35;box-sizing:border-box;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#07080f;--panel:rgba(28,31,52,.6);--text:#eef0fc;--muted:#8f95b8;--line:rgba(255,255,255,.1);--a:#6fe3ff;--b:#a78bfa;--glow:.7}}
:root[data-theme="dark"]{--bg:#07080f;--panel:rgba(28,31,52,.6);--text:#eef0fc;--muted:#8f95b8;--line:rgba(255,255,255,.1);--a:#6fe3ff;--b:#a78bfa;--glow:.7}
*{box-sizing:border-box}
html{scroll-padding-top:env(safe-area-inset-top,0px)}
body{margin:0;min-height:100vh;background:var(--bg);color:var(--text);font-family:'Sora',system-ui,-apple-system,'Segoe UI',sans-serif;padding:22px;overflow-x:hidden}
.app{position:relative;z-index:1;max-width:1200px;margin:0 auto}
header{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:18px;flex-wrap:wrap}
h1{font-size:24px;font-weight:800;margin:0;letter-spacing:-.03em}
h1 span{background:linear-gradient(90deg,var(--a),var(--b));-webkit-background-clip:text;background-clip:text;color:transparent}
.tools{display:flex;gap:8px;flex-wrap:wrap}
.btn{background:var(--panel);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);color:var(--text);border:1px solid var(--line);border-radius:14px;padding:10px 16px;font:600 13px inherit;font-family:inherit;cursor:pointer;transition:border-color .2s,transform .15s}
.btn:hover{border-color:var(--a)}.btn:active{transform:scale(.97)}
.btn.main{background:linear-gradient(90deg,var(--a),var(--b));color:#0b0d1a;border:0}
.btn:focus-visible,.c:focus-visible,input:focus-visible,.item:focus-visible{outline:2px solid var(--a);outline-offset:2px}
.layout{display:grid;grid-template-columns:1fr;gap:18px;align-items:start}
.stagewrap{position:relative}
#amb{position:absolute;inset:-6%;width:112%;height:112%;filter:blur(60px) saturate(1.6);opacity:var(--glow);z-index:0;border-radius:40px;transition:opacity .6s;pointer-events:none}
.player{position:relative;z-index:1;background:#05060b;border-radius:5px;overflow:hidden;aspect-ratio:16/9;box-shadow:0 30px 80px -30px rgba(0,0,0,.6);user-select:none;outline:0}
.player:fullscreen{border-radius:0;aspect-ratio:auto}
video{width:100%;height:100%;object-fit:contain;display:block;background:#000}
video::cue{background:rgba(5,6,11,.72);color:#fff;font:600 18px 'Sora',system-ui,sans-serif}
.empty{position:absolute;inset:0;display:grid;place-items:center;text-align:center;padding:24px;background:radial-gradient(ellipse at 20% 15%,rgba(111,227,255,.22),transparent 55%),radial-gradient(ellipse at 85% 90%,rgba(167,139,250,.28),transparent 55%),#080a14;color:#fff}
.empty.hide{display:none}
.empty:not(.hide)~.big{display:none}
.empty b{display:block;font-size:22px;margin-bottom:8px;letter-spacing:-.02em}
.empty p{margin:0 0 18px;font-size:14px;color:#a9afd3}
.player.drag{outline:3px dashed var(--a);outline-offset:-10px}
.big{position:absolute;left:50%;top:50%;width:84px;height:84px;margin:-42px;border-radius:50%;background:#c3193e;box-shadow:0 8px 30px rgba(195,25,62,.55);border:0;display:grid;place-items:center;color:#fff;cursor:pointer;transition:opacity .25s,transform .25s}
.big svg{width:32px;height:32px;fill:currentColor}
.playing .big{opacity:0;pointer-events:none;transform:scale(1.4)}
.spin{position:absolute;left:50%;top:50%;width:46px;height:46px;margin:-23px;border:3px solid rgba(255,255,255,.25);border-top-color:#fff;border-radius:50%;animation:r .8s linear infinite;display:none}
.wait .spin{display:block}@keyframes r{to{transform:rotate(360deg)}}
.ttl{position:absolute;left:20px;top:16px;right:20px;color:#fff;font-weight:600;font-size:14px;text-shadow:0 2px 12px rgba(0,0,0,.6);transition:opacity .3s;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.bar{position:absolute;left:14px;right:14px;bottom:14px;padding:10px 14px 8px;border-radius:5px;background:rgba(10,12,24,.55);border:1px solid rgba(255,255,255,.1);backdrop-filter:blur(22px) saturate(1.4);-webkit-backdrop-filter:blur(22px) saturate(1.4);color:#fff;transition:opacity .3s,transform .3s}
.player.idle.playing .bar,.player.idle.playing .ttl{opacity:0;pointer-events:none}
.player.idle.playing .bar{transform:translateY(12px)}
.player.idle.playing{cursor:none}
.seek{position:relative;height:20px;display:flex;align-items:center;cursor:pointer;touch-action:none}
.track{position:relative;width:100%;height:5px;border-radius:5px;background:rgba(255,255,255,.2);transition:height .15s}
.seek:hover .track,.seek.sk .track{height:8px}
.buf,.prog{position:absolute;left:0;top:0;bottom:0;border-radius:5px}
.buf{background:rgba(255,255,255,.28)}
.prog{background:#c3193e}
.knob{position:absolute;top:50%;width:16px;height:16px;margin:-8px;border-radius:50%;background:#fff;box-shadow:0 0 0 4px rgba(195,25,62,.4),0 2px 8px rgba(0,0,0,.5);transform:scale(0);transition:transform .15s}
.seek:hover .knob,.seek.sk .knob{transform:scale(1)}
.pv{position:absolute;bottom:26px;transform:translateX(-50%);opacity:0;pointer-events:none;text-align:center;transition:opacity .12s}
.seek:hover .pv,.seek.sk .pv{opacity:1}
.pv canvas{display:block;width:160px;height:90px;border-radius:10px;background:#000;border:2px solid #fff;box-shadow:0 8px 24px rgba(0,0,0,.5)}
.pv span{display:inline-block;margin-top:4px;background:#fff;color:#14172b;font-size:12px;font-weight:700;padding:2px 8px;border-radius:8px}
.row{display:flex;align-items:center;gap:2px;margin-top:2px}
.c{background:none;border:0;color:#fff;min-width:38px;height:38px;border-radius:12px;display:grid;place-items:center;cursor:pointer;font:700 13px inherit;font-family:inherit;position:relative}
.c:hover{background:rgba(255,255,255,.16)}.c.on{color:var(--a)}#play{background:#c3193e;border-radius:50%;box-shadow:0 4px 14px rgba(195,25,62,.45)}#play:hover{background:#dc2a52}
.c svg{width:22px;height:22px;fill:currentColor}
.time{font-size:12.5px;font-weight:600;font-variant-numeric:tabular-nums;margin:0 8px;white-space:nowrap}
.sp{flex:1}
.vol{display:flex;align-items:center}
.vol input{width:0;opacity:0;transition:width .2s,opacity .2s;accent-color:#c3193e}
.vol:hover input,.vol input:focus{width:80px;opacity:1}
.menu{position:absolute;bottom:48px;right:0;background:rgba(10,12,24,.94);border:1px solid rgba(255,255,255,.1);border-radius:14px;padding:6px;display:none;min-width:84px}
.menu.open{display:block}
.menu button{display:block;width:100%;background:none;border:0;color:#fff;padding:7px 12px;border-radius:9px;font:600 13px inherit;font-family:inherit;text-align:left;cursor:pointer}
.menu button:hover{background:rgba(255,255,255,.14)}.menu button.on{color:var(--a)}
.toast{position:absolute;top:52px;left:50%;transform:translateX(-50%);background:rgba(10,12,24,.75);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);color:#fff;font-size:13px;font-weight:700;padding:8px 16px;border-radius:999px;opacity:0;transition:opacity .2s;pointer-events:none}
.toast.show{opacity:1}
.side{background:var(--panel);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);border:1px solid var(--line);border-radius:24px;padding:14px;max-height:calc(min(1200px,100vw) * .42);min-height:260px;display:flex;flex-direction:column}
.side h2{font-size:15px;margin:4px 6px 10px;display:flex;justify-content:space-between}
.side h2 small{color:var(--muted);font-weight:600}
.list{overflow:auto;display:flex;flex-direction:column;gap:6px;flex:1}
.item{display:flex;align-items:center;gap:10px;padding:10px;border-radius:14px;cursor:pointer;border:1px solid transparent;font-size:13px;font-weight:600}
.item:hover{background:color-mix(in srgb,var(--a) 10%,transparent)}
.item.cur{border-color:var(--a);background:color-mix(in srgb,var(--a) 14%,transparent)}
.item i{flex:none;width:34px;height:34px;border-radius:10px;display:grid;place-items:center;background:linear-gradient(135deg,var(--a),var(--b));color:#0b0d1a;font-style:normal;font-weight:800;font-size:13px}
.item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.none{color:var(--muted);font-size:13px;padding:10px 6px;line-height:1.5}
.url{display:none;gap:8px;margin-bottom:14px}.url.open{display:flex}
.url input{flex:1;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:14px;padding:11px 14px;font:500 14px inherit;font-family:inherit}
.keys{margin-top:14px;color:var(--muted);font-size:12.5px;line-height:1.9}
.keys kbd{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:1px 7px;font:600 11.5px inherit;font-family:inherit;color:var(--text)}
@media (max-width:900px){.layout{grid-template-columns:1fr}.side{max-height:340px}}
@media (max-width:560px){body{padding:14px}.hm{display:none}.time{margin:0 4px}.big{width:64px;height:64px;margin:-32px}.pv canvas{width:120px;height:68px}}
@media (prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important}}
</style>

<style id="alooy-responsive-fixes">
body{padding:16px 12px}
.app{max-width:1100px;width:100%}
.stagewrap{max-width:1100px;margin:auto}
.player{width:100%;aspect-ratio:16/9}
.player:not(.playing) .big{opacity:1;pointer-events:auto;transform:none}
.player.wait .big{opacity:0;pointer-events:none}
@media(max-width:650px){
body{padding:12px 8px}
.bar{left:7px;right:7px;bottom:7px;padding:7px 8px 5px}
.row{gap:2px;display:flex;flex-wrap:nowrap;align-items:center}
.row .c{flex:0 0 auto;min-width:29px;width:29px;padding:4px}
.row .c svg{width:19px;height:19px}
.row #back,.row #fwd{display:inline-flex!important}
.row #prev,.row #next,.row #cc,.row #pip{display:none!important}
.row .vol{display:flex;min-width:29px}
.row .vol input{display:none}
.row .time{font-size:10px;white-space:nowrap;margin:0 2px}
.row .sp{flex:1;min-width:0}
.row #rateBtn{width:37px}
.row #fs{width:30px}
.ttl{top:9px;left:10px;font-size:11px}
.big{width:62px;height:62px;margin:-31px}
}
</style>

<style id="alooy-v3-final-fixes">
/* Preserve original Lumen visuals; correct mobile geometry and overlay menus. */
#play{width:42px!important;min-width:42px!important;height:42px!important;min-height:42px!important;aspect-ratio:1;border-radius:50%!important;padding:0!important;flex-shrink:0!important;display:grid!important;place-items:center!important}
#play svg{width:21px;height:21px}
#rateBtn{isolation:isolate}
#rateBtn .menu{bottom:calc(100% + 9px);right:0;min-width:67px;max-height:min(225px,48vh);overflow-y:auto;padding:4px;border-radius:11px;z-index:30;box-shadow:0 6px 24px rgba(0,0,0,.5)}
#rateBtn .menu button{font-size:12px;padding:7px 9px;line-height:1.2;white-space:nowrap}
.ttl{padding-left:46px}
@media(max-width:650px){
 .bar{z-index:8}
 .row{min-height:44px;gap:2px}
 #play{width:40px!important;min-width:40px!important;height:40px!important;min-height:40px!important}
 #rateBtn{width:34px!important;min-width:34px!important;font-size:12px}
 #rateBtn .menu{min-width:62px;max-height:170px;bottom:calc(100% + 8px)}
 #rateBtn .menu button{padding:6px 8px;font-size:11px}
 .ttl{top:10px;left:9px;right:8px;padding-left:40px;font-size:12px;line-height:1.35}
 .time{font-size:10px}
}
</style>
<style id="alooy-embed-layout">html,body{width:100%;height:100%;min-height:0;margin:0;padding:0!important;background:#000;overflow:hidden}.app,.layout,.layout>div,.stagewrap{width:100%;height:100%;max-width:none!important;margin:0;padding:0}.stagewrap{display:flex;align-items:center;justify-content:center}#amb{display:none}.player{width:100%;height:100%;max-height:100%;aspect-ratio:auto;border-radius:0;box-shadow:none}.player video{width:100%;height:100%;object-fit:contain}.player:fullscreen{height:100%}@media(max-width:650px){.bar{bottom:6px}}</style><style id="alooy-v4-fit-screen">
/* Keep the entire 16:9 player and its bottom controls inside the visible viewport. */
html,body{width:100%;min-height:100%;height:100%;margin:0;overflow:auto!important;background:#080b12}
body{padding:12px!important;display:flex;align-items:center;justify-content:center}
.app,.layout,.layout>div,.stagewrap{height:auto!important;max-width:100%!important;width:100%;min-height:0!important}
.app{width:min(1100px,calc(100vw - 24px),calc((100dvh - 24px)*16/9))!important;margin:auto!important}
.stagewrap{display:block!important}
.player{width:100%!important;height:auto!important;aspect-ratio:16/9!important;max-height:calc(100dvh - 24px)!important;position:relative;overflow:hidden;border-radius:5px}
.player video{width:100%;height:100%;position:absolute;inset:0;object-fit:contain}
.player:fullscreen{width:100%!important;height:100%!important;max-height:none!important;aspect-ratio:auto!important;border-radius:0}
.bar{z-index:10;bottom:10px}
.ttl{z-index:4}
@media(max-width:650px){body{padding:6px!important}.app{width:min(calc(100vw - 12px),calc((100dvh - 12px)*16/9))!important}.bar{bottom:5px}}
</style>
<style id="alooy-lumen-embed-v2">
html,body {
    margin:0!important;
    padding:0!important;
    min-height:0!important;
    overflow:hidden!important;
}
body {
    display:block!important;
}
.app,.layout,.layout>div,.stagewrap {
    width:100%!important;
    max-width:none!important;
    margin:0!important;
    padding:0!important;
}
.app {
    width:100%!important;
}
.player {
    width:100%!important;
    aspect-ratio:16/9!important;
    height:auto!important;
    max-height:none!important;
    border-radius:0!important;
    box-shadow:none!important;
}
</style>


</head>
<body>
<div class="app">
    
  <div class="layout">
    <div>
      <div class="stagewrap">
        <canvas id="amb" width="32" height="18"></canvas>
        <div class="player" id="player" tabindex="0">
          <video id="v" playsinline preload="metadata"></video>
          <div class="empty" id="empty"><div><b>Drop your videos here</b><p>Add several files to build a playlist. Drop a .srt or .vtt file for subtitles.</p><button class="btn main" id="openFile2">Choose files</button></div></div>
          <div class="ttl" id="ttl"></div>
          <div class="toast" id="toast"></div>
          <div class="spin"></div>
          <button class="big" id="big" aria-label="Play"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg></button>
          <div class="bar">
            <div class="seek" id="seek"><div class="track"><div class="buf" id="buf"></div><div class="prog" id="prog"></div><div class="knob" id="knob"></div></div>
              <div class="pv" id="pv"><canvas id="pc" width="160" height="90"></canvas><span id="pt">0:00</span></div></div>
            <div class="row">
              <button class="c hm" id="prev" aria-label="Previous video"><svg viewBox="0 0 24 24"><path d="M6 5h2v14H6zm3 7 10 7V5z"/></svg></button>
              <button class="c" id="play" aria-label="Play or pause"></button>
              <button class="c hm" id="next" aria-label="Next video"><svg viewBox="0 0 24 24"><path d="M16 5h2v14h-2zM5 19l10-7L5 5z"/></svg></button>
              <button class="c hm" id="back" aria-label="Back 10 seconds"><svg viewBox="0 0 24 24"><path d="M12 5V2L7 6l5 4V7a5 5 0 1 1-5 5H5a7 7 0 1 0 7-7z"/></svg></button>
              <button class="c hm" id="fwd" aria-label="Forward 10 seconds"><svg viewBox="0 0 24 24"><path d="M12 5V2l5 4-5 4V7a5 5 0 1 0 5 5h2a7 7 0 1 1-7-7z"/></svg></button>
              <div class="vol"><button class="c" id="mute" aria-label="Mute"></button><input type="range" id="vol" min="0" max="1" step="0.02" value="1" aria-label="Volume"></div>
              <span class="time" id="time">0:00 / 0:00</span>
              <span class="sp"></span>
              <button class="c hm" id="cc" aria-label="Toggle subtitles"><svg viewBox="0 0 24 24"><path d="M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM11 11H9.5v-.5h-2v3h2V13H11v1a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1zm7 0h-1.5v-.5h-2v3h2V13H18v1a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1z"/></svg></button>
              <button class="c" id="rateBtn" aria-label="Playback speed"><span id="rl">1×</span><div class="menu" id="menu"></div></button>
              <button class="c hm" id="pip" aria-label="Picture in picture"><svg viewBox="0 0 24 24"><path d="M19 7H5v10h14zm2-2v14H3V5zm-9 6h7v5h-7z"/></svg></button>
              <button class="c" id="fs" aria-label="Fullscreen"><svg viewBox="0 0 24 24"><path d="M5 5h5v2H7v3H5zm9 0h5v5h-2V7h-3zM5 14h2v3h3v2H5zm12 0h2v5h-5v-2h3z"/></svg></button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <input type="file" id="file" accept="video/*" multiple hidden>
  <input type="file" id="sub" accept=".srt,.vtt" hidden>
</div>

<script>
window.ALOOY_VIDEO_SOURCE = <?= json_encode('https://videos.alooytv.work' . $src, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES) ?>;
window.ALOOY_VIDEO_TITLE = <?= json_encode($episode_title, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) ?>;
const $=id=>document.getElementById(id),v=$('v'),P=$('player'),tv=document.createElement('video'),pc=$('pc').getContext('2d'),ac=$('amb').getContext('2d');
tv.muted=true;tv.preload='metadata';
const I={play:'<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>',pause:'<svg viewBox="0 0 24 24"><path d="M7 5h4v14H7zm6 0h4v14h-4z"/></svg>',vol:'<svg viewBox="0 0 24 24"><path d="M3 9v6h4l5 5V4L7 9zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.5 4.5 0 0 0 2.5-4z"/></svg>',mute:'<svg viewBox="0 0 24 24"><path d="M3 9v6h4l5 5V4L7 9zm13 .6L14.6 11l1.4 1.4-1.4 1.4L16 15.2l1.4-1.4 1.4 1.4 1.4-1.4-1.4-1.4 1.4-1.4-1.4-1.4-1.4 1.4z"/></svg>'};
let list=[],cur=-1,idle,tt,amb,subUrl=null,tvBusy=false,tvWant=null;
let readyToStart=false;
const fmt=s=>{if(!isFinite(s))return'0:00';s=Math.floor(s);const h=Math.floor(s/3600),m=Math.floor(s%3600/60),r=String(s%60).padStart(2,'0');return h?`${h}:${String(m).padStart(2,'0')}:${r}`:`${m}:${r}`};
const toast=t=>{const e=$('toast');e.textContent=t;e.classList.add('show');clearTimeout(tt);tt=setTimeout(()=>e.classList.remove('show'),900)};
// AlooyTV test adapter: preserve the original Lumen layout and controls.
// Supply ?video=https%3A%2F%2Fvideos.alooytv.work%2F...mp4
function loadAlexHostVideo(url, title){
  try {
    const u=new URL(url,location.href);
    if(u.protocol!=='https:' || u.hostname!=='videos.alooytv.work' || !/\.mp4$/i.test(u.pathname)) throw Error('Invalid MP4 URL');
    list=[{name:title||decodeURIComponent(u.pathname.split('/').pop()),src:u.href}];
    cur=-1;play(0);
  } catch(e){toast('Use a valid videos.alooytv.work MP4 link')}
}
const qp=new URLSearchParams(location.search);
window.addEventListener('load',()=>loadAlexHostVideo(window.ALOOY_VIDEO_SOURCE, window.ALOOY_VIDEO_TITLE));
window.loadAlexHostVideo=loadAlexHostVideo;
function render(){}
function play(i){if(i<0||i>=list.length)return;cur=i;const it=list[i];v.src=it.src;

/* AlooyTV automatic episode poster */
v.removeAttribute('poster');
/* ALOOY_WORDPRESS_POSTER_V1 */
const wpPoster=new URLSearchParams(location.search).get('poster');
if(wpPoster){try{const u=new URL(wpPoster);if(u.protocol==='https:'||u.protocol==='http:')v.poster=u.href;}catch(e){}}

try {
    const videoURL = new URL(it.src, location.href);

    if (
        videoURL.hostname === 'videos.alooytv.work' &&
        videoURL.pathname.toLowerCase().endsWith('.mp4')
    ) {
        const posterURL = new URL(videoURL.href);
        posterURL.pathname = posterURL.pathname.replace(/\.mp4$/i, '-poster.jpg');

        if (!v.poster) v.poster = posterURL.href;
    }
} catch(e) {}

tv.removeAttribute('src');tv.load();$('empty').classList.add('hide');$('ttl').textContent=it.name;if(subUrl){v.querySelectorAll('track').forEach(t=>t.remove());subUrl=null}readyToStart=false;v.pause();v.load();P.classList.add('wait');P.classList.remove('idle');render()}
function add(files){let first=list.length;[...files].forEach(f=>{if(f.type.startsWith('video/'))list.push({name:f.name.replace(/\.[^.]+$/,''),src:URL.createObjectURL(f)});else if(/\.(srt|vtt)$/i.test(f.name))sub(f)});if(list.length>first){if(cur<0||v.ended)play(first);else render()}}
function sub(f){f.text().then(t=>{if(!/^WEBVTT/.test(t))t='WEBVTT\n\n'+t.replace(/\r/g,'').replace(/(\d{2}:\d{2}:\d{2}),(\d{3})/g,'$1.$2');v.querySelectorAll('track').forEach(x=>x.remove());subUrl=URL.createObjectURL(new Blob([t],{type:'text/vtt'}));const tk=document.createElement('track');tk.kind='subtitles';tk.src=subUrl;tk.default=true;v.appendChild(tk);tk.onload=()=>{tk.track.mode='showing'};setTimeout(()=>{tk.track.mode='showing'},100);$('cc').classList.add('on');toast('Subtitles added')})}
function toggle(){
 if(!list.length)return;
 if(v.paused)v.play().catch(()=>toast('Tap Play to start'));else v.pause();
}
function ui(){const p=!v.paused;P.classList.toggle('playing',p);$('play').innerHTML=p?I.pause:I.play;$('big').setAttribute('aria-label',p?'Pause':'Play')}
function vui(){$('mute').innerHTML=v.muted||v.volume===0?I.mute:I.vol;$('vol').value=v.muted?0:v.volume}
function tick(){const d=v.duration||0,f=d?v.currentTime/d:0;$('prog').style.width=f*100+'%';$('knob').style.left=f*100+'%';$('time').textContent=fmt(v.currentTime)+' / '+fmt(d);if(v.buffered.length&&d)$('buf').style.width=v.buffered.end(v.buffered.length-1)/d*100+'%'}
function skip(s){v.currentTime=Math.max(0,Math.min(v.duration||0,v.currentTime+s));toast((s>0?'+':'−')+Math.abs(s)+'s')}
function setVol(x){v.muted=false;v.volume=Math.max(0,Math.min(1,x));toast('Volume '+Math.round(v.volume*100)+'%')}
const fs=()=>document.fullscreenElement?document.exitFullscreen():P.requestFullscreen&&P.requestFullscreen();
function glow(){try{ac.drawImage(v,0,0,32,18)}catch(e){}}
['play','pause'].forEach(e=>v.addEventListener(e,ui));
v.addEventListener('play',()=>{clearInterval(amb);amb=setInterval(glow,120);wake()});v.addEventListener('pause',()=>{clearInterval(amb);clearTimeout(idle);P.classList.remove('idle')});
v.addEventListener('timeupdate',tick);v.addEventListener('progress',tick);v.addEventListener('loadedmetadata',tick);v.addEventListener('volumechange',vui);
v.addEventListener('waiting',()=>P.classList.add('wait'));['playing','canplay'].forEach(e=>v.addEventListener(e,()=>P.classList.remove('wait')));
v.addEventListener('loadeddata',()=>{glow();readyToStart=true;P.classList.remove('wait');P.classList.remove('idle');});
v.addEventListener('canplay',()=>{readyToStart=true;P.classList.remove('wait');});

v.addEventListener('ended',()=>{if(cur<list.length-1){play(cur+1);toast('Up next')}});
v.addEventListener('error',()=>{if(!v.src)return;$('empty').classList.remove('hide');$('empty').querySelector('b').textContent='This video can’t be played';$('empty').querySelector('p').textContent='Check the file format or link, then try again.'});
v.addEventListener('click',toggle);
v.addEventListener('dblclick',e=>{const r=v.getBoundingClientRect(),x=(e.clientX-r.left)/r.width;x<.33?skip(-10):x>.67?skip(10):fs()});
$('big').onclick=toggle;$('play').onclick=toggle;$('back').onclick=()=>skip(-10);$('fwd').onclick=()=>skip(10);
$('prev').onclick=()=>{if(cur>0)play(cur-1);else toast('First episode')};
$('next').onclick=()=>{if(cur<list.length-1)play(cur+1);else toast('Last episode in this player')};
$('mute').onclick=()=>{v.muted=!v.muted};$('vol').oninput=e=>{v.muted=false;v.volume=+e.target.value};
$('fs').onclick=fs;$('pip').onclick=()=>{try{document.pictureInPictureElement?document.exitPictureInPicture():v.requestPictureInPicture()}catch(e){toast('Not supported here')}};
function cc(){const t=v.textTracks[0];if(!t)return toast('No subtitles available');t.mode=t.mode==='showing'?'hidden':'showing';$('cc').classList.toggle('on',t.mode==='showing');toast(t.mode==='showing'?'Subtitles on':'Subtitles off')}
$('cc').onclick=cc;
// seek + thumbnail preview
const seek=$('seek');let drag=false;
const at=e=>{const r=seek.getBoundingClientRect();return Math.max(0,Math.min(1,(e.clientX-r.left)/r.width))};
function thumb(t){if(!tv.src || !tv.src.startsWith('http'))tv.src=v.currentSrc;tvWant=t;if(tvBusy)return;tvBusy=true;tv.currentTime=tvWant;tvWant=null}
tv.addEventListener('seeked',()=>{try{pc.drawImage(tv,0,0,160,90)}catch(e){}tvBusy=false;if(tvWant!==null)thumb(tvWant)});
seek.addEventListener('pointerdown',e=>{drag=true;seek.classList.add('sk');seek.setPointerCapture(e.pointerId);if(v.duration)v.currentTime=at(e)*v.duration});
seek.addEventListener('pointermove',e=>{const f=at(e),r=seek.getBoundingClientRect(),w=window.innerWidth<560?60:80;$('pv').style.left=Math.max(w,Math.min(r.width-w,f*r.width))+'px';const t=f*(v.duration||0);$('pt').textContent=fmt(t);if(v.duration)thumb(t);if(drag&&v.duration)v.currentTime=t});
seek.addEventListener('pointerup',()=>{drag=false;seek.classList.remove('sk')});
// speed
const menu=$('menu');[0.5,0.75,1,1.25,1.5,2].forEach(r=>{const b=document.createElement('button');b.textContent=r+'×';if(r===1)b.className='on';b.onclick=e=>{e.stopPropagation();v.playbackRate=r;$('rl').textContent=r+'×';[...menu.children].forEach(c=>c.classList.toggle('on',c===b));menu.classList.remove('open')};menu.appendChild(b)});
$('rateBtn').onclick=e=>{e.stopPropagation();wake();menu.classList.toggle('open')};
document.addEventListener('pointerdown',e=>{if(!e.target.closest('#rateBtn'))menu.classList.remove('open')});
// idle
function wake(){P.classList.remove('idle');clearTimeout(idle);if(!v.paused)idle=setTimeout(()=>P.classList.add('idle'),2500)}
['mousemove','pointerdown','keydown','touchstart','click'].forEach(e=>P.addEventListener(e,wake));P.addEventListener('mouseleave',()=>{if(!v.paused){clearTimeout(idle);idle=setTimeout(()=>P.classList.add('idle'),2500)}});
// keys (player or page, not text inputs)
document.addEventListener('keydown',e=>{if(e.target.tagName==='INPUT'||e.target.classList.contains('item')||e.target.classList.contains('btn'))return;const k=e.key.toLowerCase();
 if(k===' '||k==='k'){e.preventDefault();toggle()}else if(k==='arrowright'){e.preventDefault();skip(10)}else if(k==='arrowleft'){e.preventDefault();skip(-10)}
 else if(k==='arrowup'){e.preventDefault();setVol(v.volume+.1)}else if(k==='arrowdown'){e.preventDefault();setVol(v.volume-.1)}
 else if(k==='m')v.muted=!v.muted;else if(k==='f')fs();else if(k==='n')play(cur+1);else if(k==='p')play(cur-1);else if(k==='c')cc();wake()});
// sources
const fi=$('file');$('openFile2').onclick=()=>fi.click();fi.onchange=()=>{add(fi.files);fi.value=''};
$('sub').onchange=e=>{if(e.target.files[0])sub(e.target.files[0]);e.target.value=''};
['dragover','dragenter'].forEach(e=>P.addEventListener(e,x=>{x.preventDefault();P.classList.add('drag')}));
['dragleave','drop'].forEach(e=>P.addEventListener(e,x=>{x.preventDefault();P.classList.remove('drag')}));
P.addEventListener('drop',e=>add(e.dataTransfer.files));
ui();vui();tick();
</script>
</body>
</html>
