<?php
require_once __DIR__ . '/engine/engine.php';
require_once __DIR__ . '/engine/api-handling/fmp_client.php';
require_once __DIR__ . '/engine/bewertungsmethoden/bewertung_strategic-profiles.php';
require_once __DIR__ . '/engine/bewertungsmethoden/bewertung_fundamental.php';

$requires_search = true;
$requires_chartjs = true;

$symbol  = strtoupper(trim($_GET['symbol'] ?? $_POST['symbol'] ?? ''));
$premium = !empty($_GET['premium_flags'] ?? $_POST['premium_flags'] ?? 0);

function sp_badge_class(string $label): string {
  $l = mb_strtolower($label);

  // harte Filter / Guards / starker Drawdown = rot
  if (str_starts_with($l, 'guard') || str_contains($l, 'filter:') || str_contains($l, 'drawdown')) {
	return 'bg-danger';
  }

  // Zinsdeckung & Volatilität abstufen
  if (str_contains($l, 'zinsdeckung')) {
	if (preg_match('/\(([\d\.]+)x\)/', $l, $m)) {
	  $x = (float)$m[1];
	  return ($x < 3) ? 'bg-danger' : (($x < 5) ? 'bg-warning text-dark' : 'bg-success');
	}
	return 'bg-warning text-dark';
  }
  if (str_contains($l, 'marktvolatilität') || str_contains($l, 'β')) {
	return (str_contains($l, '1.8') || str_contains($l, '2.')) ? 'bg-danger' : 'bg-warning text-dark';
  }

  // Dividenden-Ampel (Suffix)
  if (str_starts_with($l, 'dividendenqualität')) {
	if (str_contains($l, '(grün)'))  return 'bg-success';
	if (str_contains($l, '(gelb)'))  return 'bg-warning text-dark';
	if (str_contains($l, '(rot)'))   return 'bg-danger';
	return 'bg-info text-dark';
  }

  // positive/neutral
  if (str_contains($l, 'umsatz') || str_contains($l, 'eps') ||
	  str_contains($l, 'trend')  || str_contains($l, 'momentum') ||
	  str_contains($l, 'roic')   || str_contains($l, 'liquidität') ||
	  str_contains($l, 'beta ≤ markt') || str_contains($l, 'dividende')) {
	return 'bg-success';
  }

  if (str_starts_with($l, 'debug ')) return 'bg-secondary';
  return 'bg-light text-dark';
}

// Anzeige-Text ohne Ampel-Suffix
function sp_badge_label(string $label): string {
  return preg_replace('/\s*\((grün|gelb|rot)\)\s*$/ui', '', $label) ?? $label;
}

function sp_filter_badge(?string $text): string {
  $t = htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
  return '<span class="badge bg-danger me-1 mb-1">'.$t.'</span>';
}

// Progressbar-Farbe
function sp_progress_class(float $p): string {
  $p = (float)$p; // falls mal NULL reinkommt
  if ($p >= 80) return 'bg-success';
  if ($p >= 50) return 'bg-warning text-dark';
  return 'bg-danger';
}

function render_score_card(string $title, array $res): string {
  // --- sichere, typisierte Inputs ---
  $scorePercent = isset($res['percent']) ? (float)$res['percent'] : 0.0;
  $label        = rtrim(rtrim(number_format($scorePercent, 2, '.', ''), '0'), '.');
  $name         = htmlspecialchars($res['name'] ?? '-', ENT_QUOTES, 'UTF-8');
  $exchange     = htmlspecialchars($res['exchange'] ?? '-', ENT_QUOTES, 'UTF-8');
  $why          = is_array($res['why'] ?? null) ? $res['why'] : [];
  $premiumD     = $res['premium'] ?? null;

  // Farblogik: Badge & Progressbar identisch
  $scoreBadgeClass = sp_progress_class($scorePercent);

  // Filter-Gründe separat, übrige Gründe als Badges
  $filters = array_values(array_filter($why, fn($w) => stripos((string)$w, 'Filter:') === 0));
  $whyGood = array_values(array_diff($why, $filters));

	ob_start(); ?>
		<div class="card mb-3">
			<div class="card-body">
				<div class="d-flex justify-content-between align-items-start">
					<h5 class="card-title mb-1"><?= htmlspecialchars($title) ?></h5>
					<span class="badge <?= $scoreBadgeClass ?>"><?= $label ?>/100</span>
				</div>
		
				<!-- Progressbar -->
				<div class="progress my-2" style="height: 10px;">
					<div class="progress-bar bg-dark" role="progressbar"
						style="width: <?= (int)round($scorePercent) ?>%;"
						aria-valuenow="<?= (int)round($scorePercent) ?>" aria-valuemin="0" aria-valuemax="100">
					</div>
				</div>
		
				<?php if (!empty($filters)): ?>
					<div class="mb-2">
						<?php foreach ($filters as $f) { echo sp_filter_badge($f); } ?>
					</div>
				<?php endif; ?>
		
				<?php if (!empty($whyGood)): ?>
					<?php foreach (array_slice($whyGood, 0, 8) as $w): ?>
						<span class="badge me-1 mb-1 <?= sp_badge_class($w) ?>"><?= htmlspecialchars(sp_badge_label($w)) ?></span>
					<?php endforeach; ?>
				<?php else: ?>
					<p class="text-muted mb-0">Keine Begründungen verfügbar.</p>
				<?php endif; ?>
	
				<?php if (is_array($premiumD)): ?>
					<div class="border-top pt-2">
						<div class="small text-muted mb-1">Premium-Signals</div>
						<div class="row row-cols-2 g-2">
							<?php foreach ($premiumD as $k => $v): ?>
							<div class="col">
								<div class="border rounded p-2">
									<div class="small text-muted"><?= htmlspecialchars((string)$k) ?></div>
									<div class="fw-semibold">
										<?php
										if ($v === null || $v === '') echo '–';
										elseif (is_numeric($v)) echo rtrim(rtrim(number_format((float)$v, 2, '.', ''), '0'), '.');
										else echo htmlspecialchars((string)$v);
										?>
									</div>
								</div>
							</div>
							<?php endforeach; ?>
						</div>
					</div>
				<?php endif; ?>
			</div>
		</div>
  <?php
  return ob_get_clean();
}

function render_risk_card(string $title, array $raw): string {
  // Rohdaten aus fetch() zusammenbauen (wir brauchen ein paar Kennzahlen)
  $profile = $raw['profile'] ?? [];
  $rt      = $raw['rt'] ?? [];
  $km      = $raw['km'] ?? [];
  $hist    = $raw['hist'] ?? [];

  // Helper
  $beta       = $profile['beta'] ?? null;
  $d2e        = $rt['debtToEquityTTM'] ?? null;
  $debtEb     = $rt['netDebtToEBITDATTM'] ?? null;
  $interest   = $km['interestCoverageTTM'] ?? null;
  $current    = $rt['currentRatioTTM'] ?? null;
  $fcfYield   = $rt['freeCashFlowYieldTTM'] ?? null;

  // Drawdown 12M (true max drawdown)
  $rows = $hist['historical'] ?? $hist;
  $dd12 = null;
  if (is_array($rows) && count($rows) > 0) {
	usort($rows, fn($a,$b)=>strcmp($a['date'] ?? '', $b['date'] ?? ''));
	$closes = array_values(array_filter(array_map(fn($r)=>(float)($r['close'] ?? $r['adjClose'] ?? $r['Close'] ?? 0), $rows)));
	if (count($closes) >= 252) {
	  $slice = array_slice($closes, -252);
	  $peak = $slice[0];
	  $maxDD = 0.0;
	  foreach ($slice as $c) {
		if ($c > $peak) $peak = $c;
		if ($peak > 0) {
		  $dd = ($c/$peak - 1.0) * 100.0; // negativ
		  if ($dd < $maxDD) $maxDD = $dd;
		}
	  }
	  $dd12 = $maxDD; // z.B. -28.4%
	}
  }

  // Warnungen
  $warn = [];
  if (is_numeric($beta) && $beta > 1.3)                  $warn[] = "Hohe Marktvolatilität (β {$beta})";
  if (is_numeric($debtEb) && $debtEb > 3.0)              $warn[] = "Hebelung erhöht (Debt/EBITDA {$debtEb})";
  if (!is_numeric($debtEb) && is_numeric($d2e) && $d2e>1.5) $warn[] = "Debt/Equity hoch ({$d2e})";
  if (is_numeric($current) && $current < 1.2)            $warn[] = "Schwache Liquidität (Current Ratio {$current})";
  if (is_numeric($fcfYield) && $fcfYield < 0)            $warn[] = "Negativer FCF-Yield";
  if (is_numeric($dd12) && $dd12 < -25)                  $warn[] = "Starker 12M Drawdown (" . number_format($dd12,1) . "%)";
  
  $netDebtSafe = (is_numeric($debtEb) && $debtEb <= 0) || (is_numeric($d2e) && $d2e < 0.3);
  if (is_numeric($interest) && $interest > 0 && $interest < 5) {
	  $warn[] = "Geringe Zinsdeckung (" . rtrim(rtrim(number_format($interest,2,'.',''), '0'), '.') . "x)";
  } elseif (!is_numeric($interest) || $interest <= 0) {
	  if (!$netDebtSafe) {
	  }
  }

  ob_start(); ?>
	<div class="card mb-3">
		<div class="card-body">
			<h5><?= htmlspecialchars($title) ?></h5>
			<?php if ($warn): ?>
				<div class="mb-0">
					<?php foreach ($warn as $w): ?>
					<span class="badge bg-danger me-1 mb-1"><?= htmlspecialchars($w) ?></span>
					<?php endforeach; ?>
				</div>
			<?php else: ?>
				<p class="mb-0 text-success">Keine auffälligen Risikosignale anhand der Basis-Metriken.</p>
			<?php endif; ?>
		</div>
	</div>
  <?php return ob_get_clean();
}

function sp_matrix_signal(float $fund, float $strat): array {
  // Quadranten-Logik
  if ($fund >= 75 && $strat >= 60) {
	return ['label' => 'Grüner Bereich – Kandidat für Watchlist/Breakout',
			'badge' => 'bg-success'];
  }
  if ($fund >= 75 && $strat < 60) {
	return ['label' => 'Fundament stark, Momentum fehlt (Beobachten)',
			'badge' => 'bg-primary'];
  }
  if ($fund < 75 && $strat >= 60) {
	return ['label' => 'Momentum stark, Fundament schwach (Trading-Kandidat, Risiko höher)',
			'badge' => 'bg-warning text-dark'];
  }
  return ['label' => 'Kein Signal', 'badge' => 'bg-secondary'];
}

function render_summary(array $hp, array $sol, array $erg, array $raw, float $fundPercent, float $stratPercent): string {
  $short = []; $mid = []; $long = [];

	// High-Performer = kurzfristige Dynamik
	  if (($hp['percent'] ?? 0) >= 70)      $short[] = "Starke Momentum- und Wachstumsdynamik. Kurzfristig gute Chancen auf Kursgewinne.";
	  elseif (($hp['percent'] ?? 0) >= 40)  $short[] = "Gemischte Dynamik. Kurzfristig eher verhaltene Erwartungen.";
	  else                                  $short[] = "Fehlender Trend oder schwaches Momentum. Kurzfristig unsicher.";
	
	  // Solide = mittelfristige Stabilität
	  if (($sol['percent'] ?? 0) >= 70)      $mid[] = "Solide Fundamentaldaten stützen das Investment mittelfristig.";
	  elseif (($sol['percent'] ?? 0) >= 40)  $mid[] = "Nur teils solide Kennzahlen. Mittelfristig erhöhte Schwankungen möglich.";
	  else                                   $mid[] = "Kaum Fundamentalsicherheit. Mittelfristig hohes Risiko.";
	
	  // Ertragreich = langfristiges Bewertungs-/Wachstumspotenzial
	  if (($erg['percent'] ?? 0) >= 70)      $long[] = "Attraktive Bewertung mit Wachstumsperspektiven. Langfristig aussichtsreich.";
	  elseif (($erg['percent'] ?? 0) >= 40)  $long[] = "Teils faire Bewertung. Langfristig begrenztes Potenzial.";
	  else                                   $long[] = "Hohe Bewertung oder schwaches Wachstum. Langfristig fraglich.";
	
	  // Risiken
	  $warns = [];
	  $rt = $raw['rt'] ?? []; $km = $raw['km'] ?? [];
	  if (isset($rt['currentRatioTTM']) && $rt['currentRatioTTM'] < 1)   $warns[] = "Liquiditätsrisiko";
	  if (isset($km['interestCoverageTTM']) && $km['interestCoverageTTM'] > 0 && $km['interestCoverageTTM'] < 5) $warns[] = "niedrige Zinsdeckung";
	  if (!empty($warns)) $short[] = "⚠ Risiken: " . implode(", ", $warns);
	  
	  // >>> Matrix-Signal
		$mx = sp_matrix_signal($fundPercent, $stratPercent);

  ob_start(); ?>
	  <div class="alert alert-light text-dark">
		<h5>Gesamt-Einschätzung</h5>
		<p class="mb-2">
		  <span class="badge <?= htmlspecialchars($mx['badge']) ?> me-1">Matrix</span>
		  <strong><?= htmlspecialchars($mx['label']) ?></strong>
		</p>
		<ul class="mb-0 small">
		  <li class="mb-2"><strong>Kurzfrist (Wochen):</strong> <?= implode(" ", $short) ?></li>
		  <li class="mb-2"><strong>Mittelfrist (Monate):</strong> <?= implode(" ", $mid) ?></li>
		  <li><strong>Langfrist (Jahre):</strong> <?= implode(" ", $long) ?></li>
		</ul>
	  </div>
	  <?php return ob_get_clean();
}

require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';
?>
<main class="flex-grow-1">
	<div class="container pb-5">
		<div class="row">
		<div class="col-12">
			<div class="sticky-top mt-5 bg-white z-3 pb-3">
				<div class="d-flex justify-content-between align-items-center">
					<h1 class="mb-4">Strategisches Profil</h1>
					<div>
					<?php
					if ($symbol) {
						$category = 'Strategic Profile';
						include 'execute/watchlist/watchlist_button.php';
					}
					?>
					</div>
				</div>
		
				<form id="fcForm" method="get" class="mb-0">
					<div class="row g-3">
					<div class="col-md-4">
						<label for="symbol" class="form-label">Symbol eingeben</label>
						<input type="text" class="form-control symbol-autocomplete" name="symbol" id="symbol" placeholder="AAPL" value="<?= htmlspecialchars($symbol) ?>" required>
					</div>
					<div class="col-md-3 d-flex align-items-end">
						<div class="form-check">
						<input class="form-check-input" type="checkbox" id="premium_flags" name="premium_flags" value="1" <?= $premium ? 'checked' : '' ?>>
						<label class="form-check-label" for="premium_flags">FMP-Premium-Flags einbeziehen</label>
						</div>
					</div>
					<div class="col-md-5 d-flex align-items-end">
						<button type="submit" class="btn btn-dark w-100" id="runBtn">Prüfen</button>
					</div>
					</div>
				</form>
				<div id="status" class="text-muted mt-2"></div>
			</div>
		</div>
	</div>

	<?php if ($symbol): ?>
		<?php
			$hp  = bewertung_strategic_profiles_score($symbol, 'high_performer', ['premium'=>$premium]);
			$sol = bewertung_strategic_profiles_score($symbol, 'solide',          ['premium'=>$premium]);
			$erg = bewertung_strategic_profiles_score($symbol, 'ertragreich',     ['premium'=>$premium]);
			$raw = bewertung_strategic_profiles_fetch($symbol, ['premium'=>$premium]);
		
			$prof         = $raw['profile'] ?? [];
			$companyLabel = $prof['companyName'] ?? $prof['company-name'] ?? $prof['company'] ?? $symbol;
			$exchange     = $hp['exchange'] ?? $prof['exchangeShortName'] ?? $prof['exchange'] ?? '-';
			$sector       = $prof['sector'] ?? 'Branche unbekannt';
			$logoUrl      = $prof['image'] ?? null;
		
			$imgFallback  = '/assets/img/company-placeholder.webp';
			$imgSrc       = ($logoUrl && filter_var($logoUrl, FILTER_VALIDATE_URL)) ? $logoUrl : $imgFallback;
				
			// --- Fundamental-Score ---
			$asof = $_GET['asof'] ?? $_POST['asof'] ?? null;
			$resFund = bewertung_fundamental_score(
			  $symbol,
			  $asof,
			  null,
			  null,
			  ['enable_pe_fallback' => false]
			);
			
			$fundScore = (isset($resFund['percent']) && is_numeric($resFund['percent'])) ? (float)$resFund['percent'] : 0.0;
			$score     = (isset($resFund['score'])   && is_numeric($resFund['score']))   ? (int)$resFund['score']   : null;
			$total     = (isset($resFund['total'])   && is_numeric($resFund['total']))   ? (int)$resFund['total']   : null;

			$fundScore = isset($resFund['percent']) && is_numeric($resFund['percent']) ? (float)$resFund['percent'] : 0.0;
			$score     = isset($resFund['score'])   && is_numeric($resFund['score'])   ? (int)$resFund['score'] : null;
			$total     = isset($resFund['total'])   && is_numeric($resFund['total'])   ? (int)$resFund['total'] : null;

			// Strategic-Composite: max der 3 Profile (oder später gewichten)
			$sp_y_base = max((float)$hp['percent'], (float)$sol['percent'], (float)$erg['percent']);
		
			// Kurzfrist-Momentum & SMA200 (AGX-„Frühsignal“)
			$closes = sp_extract_closes($raw['hist'] ?? []);
			$lastPx = !empty($closes) ? end($closes) : null;
			$sma200 = null;
			if (count($closes) >= 200) {
				$sum=0; for ($i=count($closes)-200; $i<count($closes); $i++) $sum += $closes[$i];
				$sma200 = $sum/200;
			}
			$mom1m = (count($closes)>=22 && $closes[count($closes)-22]>0) ? (($closes[count($closes)-1]/$closes[count($closes)-22]-1)*100) : null;
			$mom3m = (count($closes)>=64 && $closes[count($closes)-64]>0) ? (($closes[count($closes)-1]/$closes[count($closes)-64]-1)*100) : null;
		
			$earlySignal = false;
			if ($mom1m !== null && $mom3m !== null && $lastPx !== null && $sma200 !== null) {
				$above200 = ($lastPx >= 0.97*$sma200);
				$fastMom  = ($mom1m >= 15) || ($mom3m >= 25);
				if ($fastMom && $above200) $earlySignal = true;
			}
			$sp_y = $sp_y_base;
			if ($earlySignal && $sp_y_base < 40) $sp_y = 40;
			if ($earlySignal && $sp_y < 60) {
				$strength = min(1.0, max(0.0, max(($mom1m??0)/25.0, ($mom3m??0)/35.0)));
				$sp_y = min(60, $sp_y + 10 + 10*$strength);
			}
		
			$companyLabel = ($raw['profile']['companyName'] ?? $symbol) . " ({$symbol})";
			$sector = $raw['profile']['sector'] ?? $sector;
		
			// Punktfarbe nach Quadrant
			$ptColor = 'rgba(220,53,69,0.9)'; // default rot

			if ($fundScore >= 75 && $sp_y >= 60) $ptColor = 'rgba(0,128,0,0.9)';        // grün
			elseif ($fundScore >= 75)            $ptColor = 'rgba(0,102,204,0.9)';      // blau
			elseif ($sp_y >= 60)                 $ptColor = 'rgba(255,165,0,0.9)';      // orange
		
			$hint = [];
			$hint[] = "Fundamental: ".number_format($fundScore,1)."/100";
			$hint[] = "Strategic: "  .number_format($sp_y,1)."/100";
			if ($mom1m !== null) $hint[] = "1M Mom: ".number_format($mom1m,1)."%";
			if ($mom3m !== null) $hint[] = "3M Mom: ".number_format($mom3m,1)."%";
			if ($sma200 !== null && $lastPx !== null) $hint[] = "Preis/SMA200: ".number_format($lastPx/$sma200*100,1)."%";
			if ($earlySignal) $hint[] = "Early Signal: ✓";
		
			$chartPoint = [
				'x' => round($fundScore,2),
				'y' => round($sp_y,2),
				'r' => $earlySignal ? 8 : 6,
				'c' => $ptColor,
				'label' => $companyLabel,
				'sector' => $sector,
				'hint' => implode(" | ", $hint),
				'glow' => $earlySignal,
			];
		  ?>

		<div class="row mt-3">
			<div class="col-12 mb-3">
				<div class="d-flex align-items-center justify-content-start mb-2">
					<img
					src="<?= htmlspecialchars($imgSrc) ?>"
					alt="<?= htmlspecialchars($companyLabel) ?> Logo"
					loading="lazy"
					decoding="async"
					width="45" height="45"
					class="rounded-circle border me-3"
					referrerpolicy="no-referrer"
					onerror="this.onerror=null;this.src='<?= htmlspecialchars($imgFallback) ?>';"
					/>
					<div>
						<h5 class="mb-0">
							<strong><?= htmlspecialchars($companyLabel) ?></strong>
							<span class="text-muted"> - <?= htmlspecialchars($exchange) ?></span>
						</h5>
						<p class="mb-0 text-muted"><?= htmlspecialchars($sector ?? '') ?></p>
						<span class="badge bg-primary">
						Fundamental: <?= rtrim(rtrim(number_format((float)$fundScore, 1, '.', ''), '0'), '.') ?>%
						<?php if ($score !== null && $total !== null): ?>
							(<?= (int)$score ?>/<?= (int)$total ?>)
						<?php endif; ?>
						</span>
					</div>
				</div>
			</div>
		
			<div class="col-md-7">
				<?= render_score_card('High-Performer', $hp) ?>
				<?= render_score_card('Solide Investments', $sol) ?>
				<?= render_score_card('Ertragreiche Investments', $erg) ?>
				<?= render_risk_card('Risiko-Check', $raw) ?>
			</div>
			<div class="col-md-5">
				<?= render_summary($hp, $sol, $erg, $raw, (float)$fundScore, (float)$sp_y) ?>
			  
				<div class="card mt-3">
					<div class="card-body">
						<h5 class="card-title mb-0">Fundamental × Strategic Matrix</h5>
						<p class="text-muted mb-2">Frühsignal-Modus (1M/3M Momentum)</p>
						<div class="height-150">
							<canvas id="fundStratMatrix" height="150"></canvas>
						</div>
					</div>
				</div>
			</div>
		  </div>
	<?php endif; ?>
  </div>
</main>

<script>
(function(){
  const el = document.getElementById('fundStratMatrix');
  if (!el) return;
  const ctx = el.getContext('2d');
  const pt = <?= json_encode($chartPoint ?? [], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;

  // eigener Plugin: Quadranten + Schwellenlinien
  const bgPlugin = {
	id: 'bgPlugin',
	beforeDraw(chart) {
	  const {ctx, chartArea:a, scales} = chart;
	  if (!a) return;
	  const x75 = scales.x.getPixelForValue(75);
	  const y60 = scales.y.getPixelForValue(60);

	  ctx.save();
	  // Quadranten
	  ctx.fillStyle = 'rgba(220,53,69,0.04)'; ctx.fillRect(a.left, y60, x75-a.left, a.bottom-y60); // unten links
	  ctx.fillStyle = 'rgba(0,102,204,0.06)'; ctx.fillRect(x75, y60, a.right-x75, a.bottom-y60);   // unten rechts
	  ctx.fillStyle = 'rgba(255,165,0,0.05)'; ctx.fillRect(a.left, a.top, x75-a.left, y60-a.top);  // oben links
	  ctx.fillStyle = 'rgba(0,128,0,0.05)';   ctx.fillRect(x75, a.top, a.right-x75, y60-a.top);    // oben rechts

	  // Schwellenlinien
	  ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.setLineDash([5,5]); ctx.lineWidth = 1;
	  // v-line x=75
	  ctx.beginPath(); ctx.moveTo(x75, a.top); ctx.lineTo(x75, a.bottom); ctx.stroke();
	  // h-line y=60
	  ctx.beginPath(); ctx.moveTo(a.left, y60); ctx.lineTo(a.right, y60); ctx.stroke();
	  ctx.restore();
	}
  };

  new Chart(ctx, {
	type: 'scatter',
	data: {
	  datasets: [{
		label: 'Aktie',
		data: [{x: pt.x, y: pt.y}],
		parsing: false,
		pointRadius: () => pt.r,
		pointHoverRadius: 10,
		pointBackgroundColor: () => pt.c,
		pointBorderColor: () => pt.glow ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.3)',
		pointBorderWidth: () => pt.glow ? 3 : 1.5,
	  }]
	},
	options: {
	  responsive: true,
	  maintainAspectRatio: false,
	  scales: {
		x: { suggestedMin: 0, suggestedMax: 100, title: {display: true, text: 'Fundamental-Score (0–100)'} },
		y: { suggestedMin: 0, suggestedMax: 100, title: {display: true, text: 'Strategic-Score (0–100)'} }
	  },
	  plugins: {
		legend: { display: false },
		tooltip: {
		  callbacks: {
			label: () => [pt.label, pt.sector ? ('Branche: '+pt.sector) : null, pt.hint].filter(Boolean)
		  }
		}
	  },
	  elements: { point: { hitRadius: 6 } }
	},
	plugins: [bgPlugin]
  });
})();
</script>

<?php require_once __DIR__ . '/views/footer.php'; ?>