<?php
$translate = $this->plugin('translate');
$escape = $this->plugin('escapeHtml');
$allMedia = null;
$currentMedia = null;
if ($attachedItem) {
    $allMedia = $attachedItem->media();
    $primaryMedia = $attachedItem->primaryMedia();
    if ($attachedMedia) {
        $currentMedia = $attachedMedia;
    } elseif ($primaryMedia) {
        $currentMedia = $primaryMedia;
    }
}
$changeItemButton = '<button id="attachment-item-select" data-sidebar-content-url="' .
    $escape($site->adminUrl('sidebar-item-select')) .
    '">' . $translate('Change item') . '</button>';
?>
<?php if ($attachedItem): ?>
<div class="selected-attachment">
    <?php if ($currentMedia): ?>
    <h3 class="item-title"><?php echo $escape($attachedItem->displayTitle()); ?></h3>
    <span class="media-title"><?php echo $escape($currentMedia->displayTitle()); ?></span>
    <?php echo $this->thumbnail($currentMedia, 'square', ['class' => 'item-thumbnail']); ?>
    <?php else: ?>
    <h3 class="item-title"><?php echo $escape($attachedItem->displayTitle()); ?></h3>
    <?php endif; ?>
    <?php echo $changeItemButton; ?>
</div>
<?php if ($allMedia): ?>
<div class="select-media option">
    <h3><?php echo $translate('Media'); ?></h3>
    <?php echo $this->hyperlink('', '#', [
        'class' => 'collapse',
        'title' => $translate('Collapse'),
    ]); ?>
    <div class="collapsible">
        <ul class="media-list">
            <?php foreach ($allMedia as $media): ?>
            <?php
            $attached = null;
            if (($attachedMedia && ($attachedMedia->id() === $media->id()))
                || (!$attachedMedia && ($primaryMedia->id() === $media->id()))
            ) {
                $attached = 'attached';
            }
            ?>
            <li class="media <?php echo $attached; ?>" data-media-id="<?php echo $escape($media->id()); ?>">
                <?php echo $this->thumbnail($media, 'square', ['class' => 'media-thumbnail', 'title' => $media->displayTitle()]); ?>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>
<?php endif; ?>
<?php else: ?>
<div class="selected-attachment">
    <h3 class="item-title"><?php echo $escape('No Attachment'); ?></h3>
    <p><?php echo $translate('No item selected.'); ?></p>
    <?php echo $changeItemButton; ?>
</div>
<?php endif; ?>
