<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';
require_once dirname(__DIR__, 3) . '/modules/files/AssetReplacementView.php';

$repository = myronFileRepository();
$uploadHandler = myronAssetUploadRequestHandler();
$videoAssets = myronVideoAssetRepository();
$captionAttachments = myronMediaAccessibilityAttachmentRepository();
$csrfToken = myronCsrfToken();
$requestPath = myronResolveAppRequestPath((string) ($_SERVER['REQUEST_URI'] ?? myronBuildAdminUrl('design.imageManager')));
$mode = str_ends_with($requestPath, '/videos') ? 'video' : (str_ends_with($requestPath, '/audio') ? 'audio' : 'image');
$modeMap = [
    'image' => [
        'title' => 'Image Manager',
        'activeItem' => 'design-image-manager',
        'route' => 'design.imageManager',
        'label' => 'image',
    ],
    'video' => [
        'title' => 'Video Manager',
        'activeItem' => 'design-video-manager',
        'route' => 'design.videoManager',
        'label' => 'video',
    ],
    'audio' => [
        'title' => 'Audio Manager',
        'activeItem' => 'design-audio-manager',
        'route' => 'design.audioManager',
        'label' => 'audio',
    ],
];
$config = $modeMap[$mode];
$currentRoute = (string) $config['route'];
$manageId = trim((string) ($_GET['manage'] ?? ''));
$manageVideoId = trim((string) ($_GET['manage_video'] ?? ''));
$captionFileWasSubmitted = static function (mixed $uploadedFile): bool {
    return is_array($uploadedFile) && (int) ($uploadedFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;
};
$uploadVideoCaptionFile = static function (array $uploadedFile, array $video, array $input, string $actorUserId) use ($repository, $captionAttachments): void {
    $title = trim((string) ($video['title'] ?? $input['title'] ?? 'Video'));
    $captionFile = $repository->uploadFile(
        $uploadedFile,
        $actorUserId,
        [
            'asset_class' => 'document',
            'title' => ($title !== '' ? $title : 'Video') . ' captions',
            'description' => 'Caption file for the video asset.',
            'alt_text' => '',
            'caption' => '',
        ],
        false
    );
    $captionAttachments->attachOrReplace(
        'video_asset',
        (string) ($video['id'] ?? ''),
        'captions',
        (string) $captionFile['id'],
        $actorUserId,
        [
            'language' => (string) ($input['caption_language'] ?? 'en'),
            'label' => (string) ($input['caption_label'] ?? 'English'),
        ]
    );
};
$uploadAudioTranscriptFile = static function (array $uploadedFile, array $audioFile, array $input, string $actorUserId) use ($repository, $captionAttachments): void {
    $title = trim((string) ($audioFile['title'] ?? $input['title'] ?? 'Audio'));
    $transcriptFile = $repository->uploadFile(
        $uploadedFile,
        $actorUserId,
        [
            'asset_class' => 'document',
            'title' => ($title !== '' ? $title : 'Audio') . ' transcript',
            'description' => 'Transcript file for the audio asset.',
            'alt_text' => '',
            'caption' => '',
        ],
        false
    );
    $captionAttachments->attachOrReplace(
        'audio_file',
        (string) ($audioFile['id'] ?? ''),
        'transcript',
        (string) $transcriptFile['id'],
        $actorUserId,
        [
            'language' => (string) ($input['transcript_language'] ?? 'en'),
            'label' => (string) ($input['transcript_label'] ?? 'Transcript'),
        ]
    );
};

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $currentUser = myronRequireDesignAccess(true);
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));

        if ($action === 'upload-file') {
            $file = $uploadHandler->upload(
                $_FILES,
                array_merge($_POST, ['asset_class' => $mode]),
                (string) $currentUser['id'],
                ['assetClass' => $mode, 'metadataRequired' => true]
            );
            if ($mode === 'audio' && $captionFileWasSubmitted($_FILES['transcript_file'] ?? null)) {
                $uploadAudioTranscriptFile($_FILES['transcript_file'], $file, $_POST, (string) $currentUser['id']);
            }
            myronRedirectWithFlash(
                myronBuildAdminUrl($currentRoute, ['manage' => (string) $file['id']]),
                ucfirst($mode) . ' asset uploaded.',
                'success'
            );
        }

        if ($action === 'update-file') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            $repository->updateMetadata($fileId, $_POST);
            myronRedirectWithFlash(
                myronBuildAdminUrl($currentRoute, ['manage' => $fileId]),
                ucfirst($mode) . ' asset details saved.',
                'success'
            );
        }

        if ($action === 'replace-file') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            myronFilesActionService()->replaceFromMultipart(
                $fileId,
                $_FILES['replacement_file'] ?? [],
                $_POST,
                myronActionCallerContextForUser($currentUser)
            );

            $videoAssetId = trim((string) ($_POST['video_asset_id'] ?? ''));
            $query = $mode === 'video' && $videoAssetId !== ''
                ? ['manage_video' => $videoAssetId]
                : ['manage' => $fileId];

            myronRedirectWithFlash(
                myronBuildAdminUrl($currentRoute, $query),
                ucfirst($mode) . ' asset replaced. Existing references now use the new asset bytes.',
                'success'
            );
        }

        if ($action === 'delete-file') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            if ($mode === 'audio') {
                $captionAttachments->deleteAttachment('audio_file', $fileId, 'transcript', true);
                $captionAttachments->deleteAttachment('audio_file', $fileId, 'captions', true);
            }
            $repository->deleteFile($fileId);
            myronRedirectWithFlash(myronBuildAdminUrl($currentRoute), ucfirst($mode) . ' asset deleted.', 'success');
        }

        if ($action === 'create-video-asset') {
            $file = $uploadHandler->upload(
                $_FILES,
                array_merge($_POST, ['asset_class' => 'video']),
                (string) $currentUser['id'],
                ['assetClass' => 'video', 'metadataRequired' => true]
            );
            $asset = $videoAssets->createVideoAsset(
                $_POST,
                (string) $currentUser['id'],
                (string) $file['id'],
                (string) ($_POST['quality_label'] ?? '1080p')
            );
            if ($captionFileWasSubmitted($_FILES['caption_file'] ?? null)) {
                $uploadVideoCaptionFile($_FILES['caption_file'], $asset, $_POST, (string) $currentUser['id']);
            }
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.videoManager', ['manage_video' => (string) $asset['id']]),
                'Video asset created.',
                'success'
            );
        }

        if ($action === 'update-video-asset') {
            $assetId = trim((string) ($_POST['video_asset_id'] ?? ''));
            $videoAssets->updateVideoAsset($assetId, $_POST, (string) $currentUser['id']);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.videoManager', ['manage_video' => $assetId]),
                'Video asset details saved.',
                'success'
            );
        }

        if ($action === 'add-video-rendition') {
            $assetId = trim((string) ($_POST['video_asset_id'] ?? ''));
            $file = $uploadHandler->upload(
                $_FILES,
                array_merge($_POST, ['asset_class' => 'video']),
                (string) $currentUser['id'],
                ['assetClass' => 'video', 'metadataRequired' => true]
            );
            $videoAssets->addRendition($assetId, (string) $file['id'], (string) ($_POST['quality_label'] ?? '720p'));
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.videoManager', ['manage_video' => $assetId]),
                'Video rendition saved.',
                'success'
            );
        }

        if ($action === 'upload-video-captions') {
            $assetId = trim((string) ($_POST['video_asset_id'] ?? ''));
            $asset = $videoAssets->getVideoAssetById($assetId);
            if (!is_array($asset)) {
                throw new RuntimeException('The selected video asset could not be found.');
            }
            $uploadVideoCaptionFile($_FILES['caption_file'] ?? [], $asset, $_POST, (string) $currentUser['id']);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.videoManager', ['manage_video' => $assetId]),
                'Video captions saved.',
                'success'
            );
        }

        if ($action === 'delete-video-captions') {
            $assetId = trim((string) ($_POST['video_asset_id'] ?? ''));
            $captionAttachments->deleteAttachment('video_asset', $assetId, 'captions', true);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.videoManager', ['manage_video' => $assetId]),
                'Video captions removed.',
                'success'
            );
        }

        if ($action === 'upload-audio-transcript') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            $file = $repository->getFileById($fileId);
            if (!is_array($file) || (string) ($file['media_class'] ?? '') !== 'audio') {
                throw new RuntimeException('The selected audio asset could not be found.');
            }
            $uploadAudioTranscriptFile($_FILES['transcript_file'] ?? [], $file, $_POST, (string) $currentUser['id']);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.audioManager', ['manage' => $fileId]),
                'Audio transcript saved.',
                'success'
            );
        }

        if ($action === 'delete-audio-transcript') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            $captionAttachments->deleteAttachment('audio_file', $fileId, 'transcript', true);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.audioManager', ['manage' => $fileId]),
                'Audio transcript removed.',
                'success'
            );
        }

        if ($action === 'delete-video-asset') {
            $assetId = trim((string) ($_POST['video_asset_id'] ?? ''));
            $videoAssets->deleteVideoAsset($assetId, true);
            myronRedirectWithFlash(myronBuildAdminUrl('design.videoManager'), 'Video asset deleted.', 'success');
        }

        throw new RuntimeException('Unknown asset manager action.');
    } catch (Throwable $exception) {
        $query = [];
        if ($manageId !== '') {
            $query['manage'] = $manageId;
        }
        if ($manageVideoId !== '') {
            $query['manage_video'] = $manageVideoId;
        }
        myronRedirectWithFlash(myronBuildAdminUrl($currentRoute, $query), $exception->getMessage(), 'error');
    }
}

$currentUser = myronRequireDesignAccess();
$uploadPolicy = $repository->uploadPolicyForMediaClass($mode);
$captionUploadPolicy = $repository->uploadPolicyForMediaClass('document');
$captionAccept = $repository->acceptAttributeForAccessibilityAttachments();
$managedFile = $mode !== 'video' && $manageId !== '' ? $repository->getFileById($manageId) : null;
$managedAudioTranscript = is_array($managedFile) && ($managedFile['is_audio'] ?? false) === true
    ? $captionAttachments->getAttachment('audio_file', (string) ($managedFile['id'] ?? ''), 'transcript')
    : null;
$managedVideo = $mode === 'video' && $manageVideoId !== '' ? $videoAssets->getVideoAssetById($manageVideoId) : null;
$files = $mode === 'video' ? [] : $repository->listFilesByMediaClass($mode);
$videos = $mode === 'video' ? $videoAssets->listVideoAssets() : [];
$standaloneVideoFiles = $mode === 'video' ? $repository->listFilesByMediaClass('video') : [];
$imageFiles = $repository->listFilesByMediaClass('image');
$canManage = myronUserCanManageDesign($currentUser);

myronRenderAdminShellStart($currentUser, [
    'title' => (string) $config['title'],
    'titleContext' => 'Assets',
    'activeItem' => (string) $config['activeItem'],
    'headScripts' => [myronBuildAssetUrl('runtime/js/files.js'), myronBuildAssetUrl('runtime/js/media-player.js')],
    'utilityPrimary' => $canManage ? [
        'href' => '#asset-upload',
        'label' => $mode === 'video' ? 'Add video' : 'Upload ' . (string) $config['label'],
        'title' => $mode === 'video' ? 'Add video' : 'Upload ' . (string) $config['label'],
        'icon' => 'plus-lg',
    ] : [],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Assets', 'href' => myronBuildAdminUrl('design.imageManager')],
      ['label' => (string) $config['title']],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title"><?= myronEscape((string) $config['title']) ?></h1>
  </div>
  <p class="mc-workspace__subtitle">Upload, preview, update, and remove reusable <?= myronEscape((string) $config['label']) ?> assets available to design surfaces.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <div class="mc-files-layout<?= (is_array($managedFile) || is_array($managedVideo)) ? ' mc-files-layout--sheet-open' : '' ?>">
      <section class="sg-section" data-myron-design-asset-manager="<?= myronEscape($mode) ?>">
        <?php if ($canManage): ?>
        <?= MyronAssetUploadView::renderCompact([
            'id' => 'asset-upload',
            'csrfToken' => $csrfToken,
            'actionValue' => $mode === 'video' ? 'create-video-asset' : 'upload-file',
            'assetClass' => $mode,
            'titleLabel' => $mode === 'video' ? 'Video Title' : 'File Title',
            'fileLabel' => $mode === 'video' ? 'Add Video File' : 'Add ' . ucfirst((string) $config['label']),
            'submitLabel' => $mode === 'video' ? 'Create Video Asset' : 'Upload ' . ucfirst((string) $config['label']),
            'accept' => $repository->acceptAttributeForMediaClass($mode),
            'policyHint' => 'Maximum upload size on this server: ' . (string) $uploadPolicy['effectiveLabel'] . '. MyronCMS ' . $mode . ' policy limit: ' . (string) $uploadPolicy['policyLabel'] . '.',
            'includeQuality' => $mode === 'video',
            'includeCaptionUpload' => $mode === 'video' || $mode === 'audio',
            'captionFieldName' => $mode === 'audio' ? 'transcript_file' : 'caption_file',
            'captionFieldLabel' => $mode === 'audio' ? 'Transcript File' : 'Caption File',
            'captionAccept' => $captionAccept,
            'captionPolicyHint' => $mode === 'audio'
                ? 'Optional transcript file. Accepted: .txt, .vtt, .srt. MyronCMS transcript policy limit: ' . (string) $captionUploadPolicy['policyLabel'] . '.'
                : 'Optional WebVTT/SubRip/plain text captions. MyronCMS caption policy limit: ' . (string) $captionUploadPolicy['policyLabel'] . '.',
        ]) ?>
        <?php endif; ?>

        <?php if ($mode === 'video'): ?>
        <div class="mc-page-grid mc-page-grid--files" role="table" aria-label="Video Manager">
          <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
            <span role="columnheader">Video Asset</span>
            <span role="columnheader">Renditions</span>
            <span role="columnheader">Updated</span>
            <span role="columnheader">Actions</span>
          </div>
          <?php if ($videos === []): ?>
          <div class="mc-page-grid__row" role="row">
            <span class="mc-page-grid__cell" role="cell">No video assets have been created yet.</span>
            <span class="mc-page-grid__cell" role="cell">-</span>
            <span class="mc-page-grid__cell" role="cell">-</span>
            <span class="mc-page-grid__cell" role="cell">-</span>
          </div>
          <?php endif; ?>
          <?php foreach ($videos as $video): ?>
          <?php $primary = is_array($video['primary_rendition'] ?? null) ? $video['primary_rendition'] : null; ?>
          <div class="mc-page-grid__row" role="row">
            <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
              <span class="mc-page-grid__name"><?= myronEscape((string) ($video['title'] ?? 'Video asset')) ?></span>
              <span class="mc-page-grid__subtle"><?= myronEscape((string) ($video['description'] ?? '')) ?></span>
            </span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($video['rendition_count'] ?? 0)) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape(myronFormatAdminTimestamp((string) ($video['updated_at'] ?? ''))) ?></span>
            <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
              <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('design.videoManager', ['manage_video' => (string) $video['id']])) ?>">Manage</a>
              <?php if (is_array($primary)): ?>
              <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape((string) ($primary['file_url'] ?? '')) ?>">Copy URL</button>
              <?php endif; ?>
            </span>
          </div>
          <?php endforeach; ?>
        </div>

        <?php if ($standaloneVideoFiles !== []): ?>
        <p class="sg-field__hint">Standalone video files are available below. Create a video asset above to group manual 1080p, 720p, and 480p renditions.</p>
        <?php endif; ?>
        <?php else: ?>
        <div class="mc-page-grid mc-page-grid--files" role="table" aria-label="<?= myronEscape((string) $config['title']) ?>">
          <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
            <span role="columnheader">Filename</span>
            <span role="columnheader">Type</span>
            <span role="columnheader">Size</span>
            <span role="columnheader">Dimensions</span>
            <span role="columnheader">Actions</span>
          </div>
          <?php if ($files === []): ?>
          <div class="mc-page-grid__row" role="row">
            <span class="mc-page-grid__cell" role="cell">No matching assets have been uploaded yet.</span>
            <span class="mc-page-grid__cell" role="cell">-</span>
            <span class="mc-page-grid__cell" role="cell">-</span>
            <span class="mc-page-grid__cell" role="cell">-</span>
            <span class="mc-page-grid__cell" role="cell">-</span>
          </div>
          <?php endif; ?>
          <?php foreach ($files as $file): ?>
          <div class="mc-page-grid__row" role="row">
            <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
              <span class="mc-page-grid__name"><?= myronEscape((string) ($file['original_filename'] ?? 'asset')) ?></span>
              <span class="mc-page-grid__subtle"><?= myronEscape((string) ($file['title'] ?? '')) ?></span>
            </span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape(strtoupper((string) ($file['file_extension'] ?? ''))) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($file['file_size_label'] ?? '')) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($file['dimensions_label'] ?? '')) ?></span>
            <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
              <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl($currentRoute, ['manage' => (string) $file['id']])) ?>">Manage</a>
              <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape((string) ($file['file_url'] ?? '')) ?>">Copy URL</button>
            </span>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </section>

      <?php if (is_array($managedFile)): ?>
      <aside class="mc-side-sheet" aria-label="Manage asset">
        <div class="mc-side-sheet__header">
          <div>
            <h2 class="mc-side-sheet__title">Manage <?= myronEscape(ucfirst($mode)) ?></h2>
            <div class="mc-side-sheet__meta">
              <span><?= myronEscape((string) $managedFile['original_filename']) ?></span>
              <span><?= myronEscape((string) $managedFile['mime_type']) ?> · <?= myronEscape((string) $managedFile['file_size_label']) ?></span>
            </div>
          </div>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl($currentRoute)) ?>">Close</a>
        </div>

        <div class="mc-side-sheet__preview">
          <?php if (($managedFile['is_image'] ?? false) === true): ?>
          <img class="mc-side-sheet__preview-image" src="<?= myronEscape((string) $managedFile['file_url']) ?>" alt="<?= myronEscape((string) ($managedFile['alt_text'] ?? $managedFile['title'] ?? '')) ?>">
          <?php elseif (($managedFile['is_audio'] ?? false) === true): ?>
          <audio class="mc-side-sheet__preview-media" controls preload="metadata" src="<?= myronEscape((string) $managedFile['file_url']) ?>"></audio>
          <?php if (is_array($managedAudioTranscript)): ?>
          <p class="sg-field__hint">Transcript available: <a href="<?= myronEscape((string) ($managedAudioTranscript['file_url'] ?? '')) ?>" target="_blank" rel="noreferrer"><?= myronEscape((string) ($managedAudioTranscript['original_filename'] ?? 'Transcript')) ?></a></p>
          <?php endif; ?>
          <?php else: ?>
          <div class="mc-side-sheet__preview-generic">Preview unavailable.</div>
          <?php endif; ?>
        </div>

        <form method="post" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="update-file">
          <input type="hidden" name="file_id" value="<?= myronEscape((string) $managedFile['id']) ?>">

          <label class="sg-field">
            <span class="sg-field__label">File Title</span>
            <input class="sg-field__control" type="text" name="title" value="<?= myronEscape((string) ($managedFile['title'] ?? '')) ?>">
          </label>
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Description</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="3"><?= myronEscape((string) ($managedFile['description'] ?? '')) ?></textarea>
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Alt Text</span>
            <input class="sg-field__control" type="text" name="alt_text" value="<?= myronEscape((string) ($managedFile['alt_text'] ?? '')) ?>">
          </label>
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Caption</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="caption" rows="3"><?= myronEscape((string) ($managedFile['caption'] ?? '')) ?></textarea>
          </label>
          <div class="mc-side-sheet__url-row">
            <input class="sg-field__control mc-side-sheet__url-control" type="text" value="<?= myronEscape((string) $managedFile['file_url']) ?>" readonly>
            <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape((string) $managedFile['file_url']) ?>">Copy URL</button>
          </div>
          <div class="mc-side-sheet__actions">
            <button class="sg-button sg-button--primary" type="submit">Save Asset Details</button>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) $managedFile['download_url']) ?>">Download</a>
          </div>
        </form>
        <?= MyronAssetReplacementView::render([
            'csrfToken' => $csrfToken,
            'fileId' => (string) $managedFile['id'],
            'accept' => $repository->acceptAttributeForMediaClass((string) ($managedFile['media_class'] ?? $mode)),
            'label' => 'Replace ' . ucfirst($mode),
            'buttonLabel' => 'Replace ' . ucfirst($mode),
        ]) ?>
        <?php if (($managedFile['is_audio'] ?? false) === true): ?>
        <section class="mc-admin-form__section" aria-label="Audio transcript">
          <div class="mc-admin-form__section-header">
            <h3 class="mc-admin-form__section-title">Transcript</h3>
            <p class="mc-admin-form__section-description">Upload a plain text, WebVTT, or SubRip transcript file for accessible audio review.</p>
          </div>
          <?php if (is_array($managedAudioTranscript)): ?>
          <div class="mc-side-sheet__url-row">
            <input class="sg-field__control mc-side-sheet__url-control" type="text" value="<?= myronEscape((string) ($managedAudioTranscript['original_filename'] ?? 'Transcript')) ?>" readonly>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) ($managedAudioTranscript['file_url'] ?? '')) ?>" target="_blank" rel="noreferrer">View</a>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) ($managedAudioTranscript['download_url'] ?? '')) ?>">Download</a>
          </div>
          <form method="post" class="mc-side-sheet__danger" onsubmit="return window.confirm('Remove the transcript file from this audio asset?');">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="action" value="delete-audio-transcript">
            <input type="hidden" name="file_id" value="<?= myronEscape((string) $managedFile['id']) ?>">
            <button class="sg-button sg-button--danger" type="submit">Delete Transcript</button>
          </form>
          <?php endif; ?>
          <form method="post" enctype="multipart/form-data" class="sg-form-grid">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="action" value="upload-audio-transcript">
            <input type="hidden" name="file_id" value="<?= myronEscape((string) $managedFile['id']) ?>">
            <label class="sg-field">
              <span class="sg-field__label">Transcript File</span>
              <input class="sg-field__control" type="file" name="transcript_file" required accept="<?= myronEscape($captionAccept) ?>">
              <span class="sg-field__hint">Accepted transcript files: <?= myronEscape(implode(', ', $repository->allowedAccessibilityAttachmentExtensions())) ?>.</span>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Language</span>
              <input class="sg-field__control" type="text" name="transcript_language" value="<?= myronEscape((string) ($managedAudioTranscript['language'] ?? 'en')) ?>" maxlength="16">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Label</span>
              <input class="sg-field__control" type="text" name="transcript_label" value="<?= myronEscape((string) ($managedAudioTranscript['label'] ?? 'Transcript')) ?>" maxlength="120">
            </label>
            <div class="mc-side-sheet__actions">
              <button class="sg-button sg-button--secondary" type="submit"><?= is_array($managedAudioTranscript) ? 'Replace Transcript' : 'Upload Transcript' ?></button>
            </div>
          </form>
        </section>
        <?php endif; ?>
        <form method="post" class="mc-side-sheet__danger" onsubmit="return window.confirm('Delete this asset from storage?');">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="delete-file">
          <input type="hidden" name="file_id" value="<?= myronEscape((string) $managedFile['id']) ?>">
          <button class="sg-button sg-button--danger" type="submit">Delete Asset</button>
        </form>
      </aside>
      <?php endif; ?>

      <?php if (is_array($managedVideo)): ?>
      <aside class="mc-side-sheet" aria-label="Manage video asset">
        <div class="mc-side-sheet__header">
          <div>
            <h2 class="mc-side-sheet__title">Manage Video</h2>
            <div class="mc-side-sheet__meta">
              <span><?= myronEscape((string) ($managedVideo['title'] ?? 'Video asset')) ?></span>
              <span><?= myronEscape((string) ($managedVideo['rendition_count'] ?? 0)) ?> renditions</span>
            </div>
          </div>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('design.videoManager')) ?>">Close</a>
        </div>
        <?php $managedRenditions = is_array($managedVideo['renditions'] ?? null) ? $managedVideo['renditions'] : []; ?>
        <?php $managedCaption = is_array($managedVideo['caption_attachment'] ?? null) ? $managedVideo['caption_attachment'] : null; ?>
        <?php if ($managedRenditions !== []): ?>
        <div class="mc-side-sheet__preview">
          <video class="mc-side-sheet__preview-media" controls preload="metadata" data-myron-media-player>
            <?php foreach ($managedRenditions as $rendition): ?>
            <source src="<?= myronEscape((string) ($rendition['file_url'] ?? '')) ?>" type="video/mp4" data-quality="<?= myronEscape((string) ($rendition['quality_label'] ?? '')) ?>">
            <?php endforeach; ?>
            <?php if ((string) ($managedVideo['captions_url'] ?? '') !== ''): ?>
            <track kind="subtitles" src="<?= myronEscape((string) $managedVideo['captions_url']) ?>" srcLang="<?= myronEscape((string) ($managedCaption['language'] ?? 'en')) ?>" label="<?= myronEscape((string) ($managedCaption['label'] ?? 'English')) ?>">
            <?php endif; ?>
          </video>
          <?php if (count($managedRenditions) > 1): ?>
          <div class="mc-media-quality-bar" data-myron-media-quality>
            <?php foreach ($managedRenditions as $rendition): ?>
            <button class="sg-button" type="button" data-quality="<?= myronEscape((string) ($rendition['quality_label'] ?? '')) ?>" data-src="<?= myronEscape((string) ($rendition['file_url'] ?? '')) ?>"><?= myronEscape((string) ($rendition['quality_label'] ?? '')) ?></button>
            <?php endforeach; ?>
          </div>
          <?php endif; ?>
        </div>
        <?php endif; ?>

        <form method="post" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="update-video-asset">
          <input type="hidden" name="video_asset_id" value="<?= myronEscape((string) $managedVideo['id']) ?>">
          <label class="sg-field">
            <span class="sg-field__label">Video Title</span>
            <input class="sg-field__control" type="text" name="title" value="<?= myronEscape((string) ($managedVideo['title'] ?? '')) ?>">
          </label>
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Description</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="3"><?= myronEscape((string) ($managedVideo['description'] ?? '')) ?></textarea>
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Poster Image</span>
            <select class="sg-field__control" name="poster_file_id">
              <option value="">No poster image</option>
              <?php foreach ($imageFiles as $image): ?>
              <option value="<?= myronEscape((string) $image['id']) ?>"<?= (string) ($managedVideo['poster_file_id'] ?? '') === (string) $image['id'] ? ' selected' : '' ?>><?= myronEscape((string) (($image['title'] ?? '') ?: ($image['original_filename'] ?? 'Image asset'))) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <div class="mc-side-sheet__actions">
            <button class="sg-button sg-button--primary" type="submit">Save Video Details</button>
          </div>
        </form>

        <section class="mc-admin-form__section" aria-label="Video captions">
          <div class="mc-admin-form__section-header">
            <h3 class="mc-admin-form__section-title">Captions</h3>
            <p class="mc-admin-form__section-description">Upload a WebVTT, SubRip, or plain text caption file for accessible video playback.</p>
          </div>
          <?php if (is_array($managedCaption)): ?>
          <div class="mc-side-sheet__url-row">
            <input class="sg-field__control mc-side-sheet__url-control" type="text" value="<?= myronEscape((string) ($managedCaption['original_filename'] ?? 'Captions')) ?>" readonly>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) ($managedCaption['file_url'] ?? '')) ?>" target="_blank" rel="noreferrer">View</a>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) ($managedCaption['download_url'] ?? '')) ?>">Download</a>
          </div>
          <form method="post" class="mc-side-sheet__danger" onsubmit="return window.confirm('Remove the caption file from this video?');">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="action" value="delete-video-captions">
            <input type="hidden" name="video_asset_id" value="<?= myronEscape((string) $managedVideo['id']) ?>">
            <button class="sg-button sg-button--danger" type="submit">Delete Captions</button>
          </form>
          <?php endif; ?>
          <form method="post" enctype="multipart/form-data" class="sg-form-grid">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="action" value="upload-video-captions">
            <input type="hidden" name="video_asset_id" value="<?= myronEscape((string) $managedVideo['id']) ?>">
            <label class="sg-field">
              <span class="sg-field__label">Caption File</span>
              <input class="sg-field__control" type="file" name="caption_file" required accept="<?= myronEscape($captionAccept) ?>">
              <span class="sg-field__hint">Accepted caption files: <?= myronEscape(implode(', ', $repository->allowedAccessibilityAttachmentExtensions())) ?>.</span>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Language</span>
              <input class="sg-field__control" type="text" name="caption_language" value="<?= myronEscape((string) ($managedCaption['language'] ?? 'en')) ?>" maxlength="16">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Label</span>
              <input class="sg-field__control" type="text" name="caption_label" value="<?= myronEscape((string) ($managedCaption['label'] ?? 'English')) ?>" maxlength="120">
            </label>
            <div class="mc-side-sheet__actions">
              <button class="sg-button sg-button--secondary" type="submit"><?= is_array($managedCaption) ? 'Replace Captions' : 'Upload Captions' ?></button>
            </div>
          </form>
        </section>

        <form method="post" enctype="multipart/form-data" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="add-video-rendition">
          <input type="hidden" name="video_asset_id" value="<?= myronEscape((string) $managedVideo['id']) ?>">
          <label class="sg-field">
            <span class="sg-field__label">Rendition</span>
            <select class="sg-field__control" name="quality_label">
              <option value="1080p">1080p</option>
              <option value="720p">720p</option>
              <option value="480p">480p</option>
            </select>
          </label>
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Upload Rendition</span>
            <input class="sg-field__control" type="file" name="upload_file" required accept="<?= myronEscape($repository->acceptAttributeForMediaClass('video')) ?>">
          </label>
          <label class="sg-field">
            <span class="sg-field__label">Alt Text</span>
            <input class="sg-field__control" type="text" name="alt_text" required maxlength="500">
          </label>
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Description</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="description" required rows="2"></textarea>
          </label>
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Caption</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="caption" required rows="2"></textarea>
          </label>
          <div class="mc-side-sheet__actions">
            <button class="sg-button sg-button--secondary" type="submit">Add Rendition</button>
          </div>
        </form>

        <?php foreach ($managedRenditions as $rendition): ?>
        <?php $renditionFileId = (string) ($rendition['file_id'] ?? ''); ?>
        <div class="mc-side-sheet__url-row">
          <input class="sg-field__control mc-side-sheet__url-control" type="text" value="<?= myronEscape((string) ($rendition['file_url'] ?? '')) ?>" readonly>
          <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape((string) ($rendition['file_url'] ?? '')) ?>">Copy <?= myronEscape((string) ($rendition['quality_label'] ?? 'URL')) ?></button>
        </div>
        <?php if ($renditionFileId !== ''): ?>
        <?= MyronAssetReplacementView::render([
            'csrfToken' => $csrfToken,
            'fileId' => $renditionFileId,
            'accept' => $repository->acceptAttributeForMediaClass('video'),
            'label' => 'Replace ' . (string) ($rendition['quality_label'] ?? 'Video') . ' Rendition',
            'buttonLabel' => 'Replace Rendition',
            'hidden' => ['video_asset_id' => (string) $managedVideo['id']],
        ]) ?>
        <?php endif; ?>
        <?php endforeach; ?>

        <form method="post" class="mc-side-sheet__danger" onsubmit="return window.confirm('Delete this video asset and its rendition files from storage?');">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="delete-video-asset">
          <input type="hidden" name="video_asset_id" value="<?= myronEscape((string) $managedVideo['id']) ?>">
          <button class="sg-button sg-button--danger" type="submit">Delete Video Asset</button>
        </form>
      </aside>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
