<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Config;

final class BookmarkletController extends Controller
{
    public function show(): Response
    {
        $appUrl = rtrim((string) Config::get('app.url', ''), '/');

        $bookmarkletScript = <<<'BOOKMARKLET'
(function(){
  var APP_URL = '__APP_URL__';
  if(!location.hostname.includes('songselect.ccli.com')){
    alert('Bitte öffne dieses Lesezeichen auf einer SongSelect Liedseite (songselect.ccli.com).');
    return;
  }
  var title = (document.querySelector('h1, .song-title, [class*="title"]') || {}).innerText || document.title || '';
  var author = (document.querySelector('.song-authors, .song-artist, [class*="author"]') || {}).innerText || '';
  var bodyText = document.body ? document.body.innerText : '';
  var ccliMatch = bodyText.match(/CCLI[\s#-]*(\d+)/i);
  var ccliId = ccliMatch ? ccliMatch[1] : '';
  var payload = {
    title: title.trim(),
    author: author.trim(),
    ccliId: ccliId,
    sourceUrl: location.href,
    rawText: bodyText
  };
  var encoded = btoa(unescape(encodeURIComponent(JSON.stringify(payload))));
  window.open(APP_URL + '/songs/import-from-ccli-paste?prefill=' + encoded, '_blank');
})();
BOOKMARKLET;

        $bookmarkletScript = str_replace('__APP_URL__', $appUrl, $bookmarkletScript);

        $singleLine = 'javascript:'.preg_replace('/\s+/', ' ', $bookmarkletScript);

        return response($singleLine, 200, [
            'Content-Type' => 'text/javascript; charset=utf-8',
            'Cache-Control' => 'public, max-age=3600',
        ]);
    }
}
