<?php
namespace Zab\ZabSite\ViewHelpers;

use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

/**
 * Extracts the title from a typolink parameter string.
 *
 * Typolink format: "url target class title"
 * Example: 'http://example.com - - "Login"' → 'Login'
 *
 * Usage:
 *   <zab:typolinkTitle parameter="{headerLoginLink}" />
 *   or
 *   {headerLoginLink -> zab:typolinkTitle()}
 */
class TypolinkTitleViewHelper extends AbstractViewHelper
{
    public function initializeArguments(): void
    {
        $this->registerArgument('parameter', 'string', 'The typolink parameter string', false);
    }

    public function render(): string
    {
        $parameter = $this->arguments['parameter'] ?? $this->renderChildren();
        if (empty($parameter)) {
            return '';
        }

        // Title is the 4th part, possibly quoted: url target class "title"
        if (preg_match('/(?:^|\\s)"([^"]*)"\\s*$/', $parameter, $matches)) {
            return $matches[1];
        }

        // Fallback: split by space, 4th element (unquoted)
        $parts = str_getcsv($parameter, ' ');
        return $parts[3] ?? '';
    }
}
