<?php

/** @var \Kirby\Cms\Block $block */
$figureClassArray   = [];
$imgClassArray      = [];
$alt          = $block->alt();
$caption      = $block->caption();
$crop         = $block->crop()->isTrue();
$link         = $block->link();
$target_blank  = $block->target_blank()->isTrue();
$ratio        = $block->ratio()->or('auto');
$cssclass    = $block->cssclass()->or('');
$src          = null;

if ($crop)
  array_push($figureClassArray, 'crop');


$figureStyle = '';
$figureClass = implode(" ", $figureClassArray);
$imgClass = implode(" ", $imgClassArray);
$imgClass .= " " . $cssclass;
$isSVG = false;

if ($block->location() == 'web') {
  $src = $block->src()->esc();
} elseif ($image = $block->image()->toFile()) {
  $alt = $alt->or($image->alt());
  $caption = $caption->or($image->caption());
  $src = $image->url();
  $isSVG    = ($image->extension() == "svg") ? true : false;
}

if ($ratio == 'auto') {
  $figureClass .= " auto";
} else {
  $figureClass .= " ratioed";

  $ratioData = explode('/', $ratio);
  $figureStyle = 'style = "--w: ' . $ratioData[0] . '; --h: ' . $ratioData[1] . ';"';
}

$desktopW = $span / 12 * 100;
$sizes = 'sizes = "(min-width:1080px) ' . floor($desktopW) . 'vw,			    
			    100vw"';
?>
<?php if ($src) : ?>
  <figure class="<?= $figureClass ?>" <?= $figureStyle ?>>
    <?php
    // WITH LINK
    if ($link->isNotEmpty() && $block->linkactive()->isTrue()) : ?>
      <a <?= e($target_blank, 'target="_blank"') ?> href="<?= Str::esc($link->toUrl()) ?>" title="<?= $block->link_desc() ?>">
        <?php
        // check if from web
        if ($block->location() == 'web') : ?>
          <img class="<?= $imgClass ?>" src="<?= $src ?>" alt="<?= $alt->esc() ?>">
        <?php
        // if local, check svg or no scr setting
        elseif ($isSVG) : ?>
          <img class="svg <?= $imgClass ?>" src="<?= $src ?>" alt="<?= $alt->esc() ?>">
        <?php else : ?>
          <?= $image->responsiveImg($alt, $imgClass, $sizes); ?>
        <?php endif ?>
      </a>
    <?php else :
      // NO LINK
    ?>
      <?php
      // check if from web
      if ($block->location() == 'web') : ?>
        <img class="<?= $imgClass ?>" src="<?= $src  ?>" alt="<?= $alt->esc() ?>">
      <?php
      // if local, check svg or no scr setting
      elseif ($isSVG) : ?>
        <img class="svg <?= $imgClass ?>" src="<?= $src  ?>" alt="<?= $alt->esc() ?>">
      <?php else : ?>
        <?= $image->responsiveImg($alt, $imgClass, $sizes); ?>
      <?php endif ?>
    <?php endif ?>
    <?php if ($caption->isNotEmpty()) : ?>
      <figcaption>
        <?= $caption ?>
      </figcaption>
    <?php endif ?>
  </figure>
<?php endif ?>