<?php
require_once __DIR__ . '/engine/engine.php';
require_once __DIR__ . '/engine/api-handling/api_helpers.php';
$requires_search = true;
$requires_chartjs = true;
require_once __DIR__ . '/views/header.php';
require_once __DIR__ . '/views/navigation.php';
?>

<main class="flex-grow-1">
  <section class="container my-5">
    
    <h3>Global Liquidity Index Pro (GLI-Pro)</h3>
    <div class="row mt-3 mb-2">
      <div class="col-md-4 d-flex align-items-stretch">
        <div class="card mb-3 d-flex flex-column w-100">
          <div class="card-body">
            <strong>Aktueller Score:</strong>
            <h2 class="mb-0 mt-2"><strong><span id="gliValue">–</span></strong></h2>
            <span id="gliRating">–</span>
            <div class="alert alert-light text-dark mt-4">
              <strong id="avgLabel">Durchschnitt (3 Monate):</strong> <span id="gliAverage">–</span>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-4 d-flex align-items-stretch">
        <div class="card mb-3 d-flex flex-column w-100">
          <div class="card-body">
            <strong class="d-block">Regionale Subscores:</strong>
            <ul class="list-group list-group-flush mt-4">
              <li class="list-group-item px-0">USA: <span id="score-us">–</span></li>
              <li class="list-group-item px-0">Europa: <span id="score-eu">–</span></li>
              <li class="list-group-item px-0">Japan: <span id="score-jp">–</span></li>
            </ul>
          </div>
        </div>
      </div>
      <div class="col-md-4 d-flex align-items-stretch">
          <div class="card mb-3 d-flex flex-column w-100">
            <div class="card-body">
              <div id="data-sources" class="small"></div>
              <small><a href="../execute/globale-liquiditaet/gli_pro_check_availability.php" class="text-dark">Daten-Verfügbarkeit prüfen</a></small>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <div class="d-flex align-items-center gap-3 mb-2">
              <select id="maSelector" class="form-select form-select-sm" style="width: 170px;">
                <option value="3">3 Monate</option>
                <option value="6">6 Monate</option>
                <option value="12" selected>12 Monate</option>
                <option value="60">5 Jahre</option>
                <option value="120">10 Jahre</option>
              </select>
            </div>
            <canvas id="gliChart" width="800" height="270"></canvas>
        </div>
      </div>
    </div>
    
    <h3 class="mt-4">Global Liquidity Proxy</h3>
    <div class="row mt-3">
      <div class="col-12">
        <div class="card">
          <div class="card-body">    
            <canvas id="gliProxyChart" width="800" height="270"></canvas>
          </div>
        </div>
      </div>
    </div>
    
    <h3 class="mt-4">Macro Pressure Index</h3>
    <p class="small">Financial Conditions Light (US10Y / Broad Dollar Index / WTI Crude Oil)</p>
    <div class="row mt-2">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <canvas id="macroPressureChart" width="800" height="270"></canvas>
          </div>
        </div>
      </div>
    </div>
    
    <h3 class="mt-4">Financial Conditions (FCI – z-Score Composite)</h3>
    <p class="small">Financial Conditions Pro (US 10Y Treasury / US High Yield OAS (pp) / Broad Dollar Index / S&P 500 / WTI Crude Oil)</p>
    <div class="row mt-3">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <canvas id="gliFciChart" width="800" height="270"></canvas>
          </div>
        </div>
      </div>
    </div>
    
    <div class="row mt-3">
      <div class="col-12">
        <div class="alert alert-light text-dark mt-3 fw-bold" id="allocationBox">
          FCI-Investment-Ampel: – wird geladen…
        </div>
      </div>
    </div>
    
    <!-- Sanity-Check Tabellen -->
    <h4 class="mt-4 mb-0">Sanity Check</h4>
    <small>letzte 12 Monate</small>
    <div class="row mt-3">
      <div class="col-md-6">
        <h5>Macro Pressure (Vorlauf)</h5>
        <div class="table-responsive">
          <table class="table table-sm table-striped" id="macroTable">
            <thead><tr><th>Monat</th><th>Macro Pressure</th><th>Impact (+9M)</th></tr></thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
      <div class="col-md-6">
        <h5>Financial Conditions (Momentaufnahme)</h5>
        <div class="table-responsive">
          <table class="table table-sm table-striped" id="fciTable">
            <thead><tr><th>Monat</th><th>FCI (z-Composite)</th><th>SMA(3)</th></tr></thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
    
    <div class="row mt-3">
      <div class="col-12">
       <h4 class="mt-4">Investment-Entscheidungs-Matrix</h4>
        <div class="table-responsive">
          <table class="table table-bordered table-sm text-center align-middle">
            <thead class="table-light">
              <tr>
                <th rowspan="2" class="align-middle">FCI (aktueller Stand)</th>
                <th colspan="3">Macro Pressure (+9M)</th>
              </tr>
              <tr>
                <th class="text-success">≤ −20 (Entlastung)</th>
                <th>zwischen −20 … +20</th>
                <th class="text-danger">≥ +20 (Restriktiv)</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <th class="text-success">≤ −0.5 (Expansiv)</th>
                <td class="table-success">Full Risk-On<br><small>Aktien hoch, EM/HY erlaubt</small></td>
                <td class="table-warning">Neutral<br><small>leicht risk-on</small></td>
                <td class="table-warning">Vorsicht<br><small>Gewinne sichern</small></td>
              </tr>
              <tr>
                <th>zwischen −0.5 … +0.5 (Neutral)</th>
                <td class="table-success">Antizyklisch vorbereiten<br><small>Buy-the-dip Szenarien</small></td>
                <td class="table-light">Neutral</td>
                <td class="table-warning">Defensiv aufstellen<br><small>Sektorrotation</small></td>
              </tr>
              <tr>
                <th class="text-danger">≥ +0.5 (Restriktiv)</th>
                <td class="table-info">Antizyklisch vorbereiten<br><small>Cash halten</small></td>
                <td class="table-warning">Defensiv<br><small>Cash/IG-Bonds</small></td>
                <td class="table-danger">Full Risk-Off<br><small>Cash, Defensivwerte</small></td>
              </tr>
            </tbody>
          </table>
        </div>
    
      </div>
    </div>

    
  </section>
  
  <script>
    // --- Helpers ---
    function formatMonthDE(label) {
      // erwartet "YYYY-MM" und gibt "MM.YYYY" zurück
      if (!label || !/^\d{4}-\d{2}$/.test(label)) return label;
      const [y, m] = label.split('-');
      return `${m}.${y}`;
    }
  
    function computeMA(arr, period) {
      return arr.map((_, i) => {
        if (i < period - 1) return null;
        let sum = 0;
        for (let k = i - period + 1; k <= i; k++) sum += arr[k];
        return Number((sum / period).toFixed(2));
      });
    }
  
    function periodLabel(period) {
      if (period === 120) return '10-Jahres-Durchschnitt';
      if (period === 60)  return '5-Jahres-Durchschnitt';
      return `${period}-Monats-Durchschnitt`;
    }
  
    function avgBoxLabel(period) {
      if (period === 120) return 'Durchschnitt (10 Jahre):';
      if (period === 60)  return 'Durchschnitt (5 Jahre):';
      return `Durchschnitt (${period} Monate):`;
    }
  
    function formatNumberDE(n, fractionDigits = 2) {
      return Number(n).toLocaleString('de-DE', { minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits });
    }
    
    function getNineMonthsAgoIndex(labels) {
      if (!labels.length) return 0;
      const lastDate = new Date(labels[labels.length - 1]);
      const nineMonthsAgo = new Date(lastDate);
      nineMonthsAgo.setMonth(lastDate.getMonth() - 9);
      let idx = labels.findIndex(l => new Date(l) >= nineMonthsAgo);
      if (idx === -1) idx = labels.length - 1;
      return idx;
    }
  </script>

  <script>
    let chart, proxyChart;
    const ctx = document.getElementById('gliChart').getContext('2d');
    const proxyCtx = document.getElementById('gliProxyChart').getContext('2d');
  
    // GLI-Chart
    function buildGliChart(labelsDE, data, ma) {
      const maData = computeMA(data, ma);
      if (chart) chart.destroy();
    
      // Index 9 Monate vor letztem Punkt (nutzt YYYY-MM in GLI.labels)
      const nineIdx = getNineMonthsAgoIndex(GLI.labels);
    
      chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labelsDE,
          datasets: [
            {
              label: 'GLI-Pro (%)',
              data,
              borderWidth: 2,
              borderColor: '#000000',
              backgroundColor: '#000000',
              pointBackgroundColor: '#000000',
              pointBorderColor: '#000000',
              pointRadius: 1.0,
              fill: false,
              tension: 0
            },
            {
              label: periodLabel(ma),
              data: maData,
              borderColor: 'red',
              borderWidth: 1.5,
              pointRadius: 0,
              fill: false,
              tension: 0
            }
          ]
        },
        options: {
          responsive: true,
          interaction: { mode: 'nearest', axis: 'xy', intersect: false },
          scales: {
            y: {
              title: { display: true, text: 'Score (%)', color: 'black', font: { weight: 'bold' } },
              ticks: { font: { weight: 'bold' } },
              beginAtZero: false
            },
            x: {
              title: { display: true, text: 'Monat', color: 'black', font: { weight: 'bold' } },
              ticks: { font: { weight: 'bold' } }
            }
          },
          plugins: {
            legend: { display: true },
            tooltip: {
              mode: 'index',
              intersect: false,
              callbacks: {
                label: ctx => `${ctx.dataset.label}: ${formatNumberDE(ctx.raw)} %`
              }
            },
            annotation: {
              annotations: {
                nineMonthsLine: {
                  type: 'line',
                  xMin: nineIdx, xMax: nineIdx,
                  borderColor: 'red',
                  borderWidth: 2,
                  label: { enabled: true, content: '−9M', position: 'start', backgroundColor: 'red', }
                },
                plus10: { type: 'line', yMin: 10, yMax: 10, borderColor: 'green', borderWidth: 1, borderDash: [3,3],
                  label: { content: '+10 % (ultraexpansiv)', enabled: true, position: 'start', backgroundColor: 'green', color: 'white', font: { weight: 'bold' } }
                },
                minus10: { type: 'line', yMin: -10, yMax: -10, borderColor: 'red', borderWidth: 1, borderDash: [3,3],
                  label: { content: '–10 % (ultrarestriktiv)', enabled: true, position: 'start', backgroundColor: 'red', color: 'white', font: { weight: 'bold' } }
                },
                zeroLine: { type: 'line', yMin: 0, yMax: 0, borderColor: 'black', borderWidth: 1, borderDash: [3,3] }
              }
            }
          }
        }
      });
    }
  </script>
  
  <script>
    function buildProxyChart(labelsDE, data, ma) {
      const maData = computeMA(data, ma);
      if (proxyChart) proxyChart.destroy();
    
      // Index 9 Monate vor letztem Punkt (nutzt YYYY-MM in PROXY.labels)
      const nineIdx = getNineMonthsAgoIndex(PROXY.labels);
    
      proxyChart = new Chart(proxyCtx, {
        type: 'line',
        data: {
          labels: labelsDE,
          datasets: [
            {
              label: 'GLI Proxy (YoY %)',
              data,
              borderColor: '#000',
              backgroundColor: '#000',
              borderWidth: 2,
              pointRadius: 1.5,
              fill: false,
              tension: 0
            },
            {
              label: periodLabel(ma),
              data: maData,
              borderColor: 'red',
              borderWidth: 1.5,
              pointRadius: 0,
              fill: false,
              tension: 0
            }
          ]
        },
        options: {
          responsive: true,
          interaction: { mode: 'nearest', axis: 'xy', intersect: false },
          scales: {
            y: {
              title: { display: true, text: 'Jahresveränderung (%)', font: { weight: 'bold' } },
              suggestedMin: -2,
              suggestedMax:  2,
              ticks: { font: { weight: 'bold' } }
            },
            x: {
              title: { display: true, text: 'Monat', font: { weight: 'bold' } },
              ticks: { font: { weight: 'bold' } }
            }
          },
          plugins: {
            legend: { display: true },
            tooltip: { callbacks: { label: ctx => `${ctx.dataset.label}: ${formatNumberDE(ctx.raw)} %` } },
            annotation: {
              annotations: {
                nineMonthsLine: {
                  type: 'line',
                  xMin: nineIdx, xMax: nineIdx,
                  borderColor: 'red',
                  borderWidth: 2,
                  label: { enabled: true, content: '−9M', position: 'start', backgroundColor: 'red', }
                },
                plus10: { type: 'line', yMin: 10, yMax: 10, borderColor: 'green', borderWidth: 1, borderDash: [3,3],
                  label: { content: '+10 % (ultraexpansiv)', enabled: true, position: 'start', backgroundColor: 'green', color: 'white', font: { weight: 'bold' } }
                },
                minus10: { type: 'line', yMin: -10, yMax: -10, borderColor: 'red', borderWidth: 1, borderDash: [3,3],
                  label: { content: '–10 % (ultrarestriktiv)', enabled: true, position: 'start', backgroundColor: 'red', color: 'white', font: { weight: 'bold' } }
                },
                zeroLine: { type: 'line', yMin: 0, yMax: 0, borderColor: 'black', borderWidth: 1, borderDash: [3,3] }
              }
            }
          }
        }
      });
    }
  </script>
  
  <script>
    const maSelector = document.getElementById('maSelector');
    const avgLabelEl = document.getElementById('avgLabel');
    const avgSpan = document.getElementById('gliAverage');
  
    // Wir halten beide Datensätze im Speicher
    let GLI = { labels: [], labelsDE: [], data: [] };
    let PROXY = { labels: [], labelsDE: [], data: [] };
  
    function updateAvgBox(ma) {
      if (!GLI.data.length) return;
      const n = Math.min(ma, GLI.data.length);
      const avgVal = GLI.data.slice(-n).reduce((s,v)=>s+v,0) / n;
      avgLabelEl.textContent = avgBoxLabel(ma);
      avgSpan.textContent = `${formatNumberDE(avgVal)} %`;
    }
  
    function redrawAll() {
      const ma = parseInt(maSelector.value, 10);
      updateAvgBox(ma);
      buildGliChart(GLI.labelsDE, GLI.data, ma);
      buildProxyChart(PROXY.labelsDE, PROXY.data, ma);
    }
  
    // Daten laden (GLI-Pro)
    fetch('execute/globale-liquiditaet/gli_data_pro.php')
      .then(r => r.json())
      .then(result => {
        GLI.labels = result.labels || [];
        GLI.labelsDE = GLI.labels.map(formatMonthDE);
        GLI.data = result.data || [];
  
        // Kopfwerte + Ampel
        const score = result.currentScore;
        document.getElementById('gliValue').textContent = `${formatNumberDE(score)} %`;
        const gliSpan = document.getElementById('gliValue');
        gliSpan.style.color =
          score >= 10 ? 'darkgreen' :
          score >= 5  ? 'green'     :
          score <= -10? 'darkred'   :
          score <= -5 ? 'red'       : 'orange';
  
        const ratingSpan = document.getElementById('gliRating');
        let status = 'Neutral';
        if (score >= 10) status = 'Ultraexpansiv';
        else if (score >= 5) status = 'Expansiv';
        else if (score <= -10) status = 'Ultrarestriktiv';
        else if (score <= -5) status = 'Restriktiv';
        ratingSpan.textContent = status;
  
        if (result.subscores) {
          const fmt = v => v == null ? '–' : `${formatNumberDE(v)} %`;
          document.getElementById('score-us').textContent = fmt(result.subscores.us);
          document.getElementById('score-eu').textContent = fmt(result.subscores.eu);
          document.getElementById('score-jp').textContent = fmt(result.subscores.jp);
        }
  
        // Datenquellen im deutschen Format anzeigen
        const sourcesDiv = document.getElementById("data-sources");
        let sourceHtml = "<strong>Datengrundlage für aktuellen Score:</strong><br><ul>";
        (result.latest_values || []).forEach(item => {
          // item.date erwartet "YYYY-MM"
          sourceHtml += `<li>${item.name}: ${Number(item.value).toLocaleString('de-DE')} (${formatMonthDE(item.date)})</li>`;
        });
        sourceHtml += "</ul>";
        sourcesDiv.innerHTML = sourceHtml;
  
        // Wenn Proxy schon da ist, zeichnen – sonst wartet redrawAll auf beide Loads
        if (PROXY.data.length) redrawAll();
      })
      .catch(err => {
        console.error("Fehler beim Laden der GLI-Daten:", err);
        alert("Daten konnten nicht geladen werden.");
      });
  
    // Daten laden (Proxy)
    fetch('execute/globale-liquiditaet/gli_data_proxy.php')
      .then(r => r.json())
      .then(result => {
        PROXY.labels = result.labels || [];
        PROXY.labelsDE = PROXY.labels.map(formatMonthDE);
        PROXY.data = result.data || [];
  
        if (GLI.data.length) redrawAll();
      })
      .catch(err => console.error("Fehler beim Laden des Proxy-Charts:", err));
  
    // Gemeinsame Steuerung
    maSelector.addEventListener('change', redrawAll);
  
  </script>
  
  <script>
    let macroChart;
    const macroCtx = document.getElementById('macroPressureChart').getContext('2d');
    
    function buildMacroChart(labelsDE, comp, impact) {
      if (macroChart) macroChart.destroy();
      const nineIdx = getNineMonthsAgoIndex(labelsDE.map(s=>s.split('.').reverse().join('-'))); // nutzt YYYY-MM
    
      macroChart = new Chart(macroCtx, {
        type: 'line',
        data: {
          labels: labelsDE,
          datasets: [
            { label: 'Macro Pressure (now)', data: comp, borderWidth: 2, borderColor: '#000', backgroundColor: '#000', pointRadius: 1, fill: false, tension: 0 },
            { label: 'Impact (+9M)', data: impact, borderWidth: 1.5, borderColor: 'red', pointRadius: 0, borderDash: [4,3], fill: false, tension: 0 }
          ]
        },
        options: {
          responsive: true,
          interaction: { mode: 'nearest', intersect: false },
          scales: {
            y: { title: { display: true, text: 'Score (−100…+100)', font: { weight: 'bold' } }, ticks: { font: { weight: 'bold' } } },
            x: { title: { display: true, text: 'Monat', font: { weight: 'bold' } }, ticks: { font: { weight: 'bold' } } }
          },
          plugins: {
            legend: { display: true },
            tooltip: { callbacks: { label: c => `${c.dataset.label}: ${formatNumberDE(c.raw,1)}` } },
            annotation: {
              annotations: {
                nineMonthsLine: { type:'line', xMin:nineIdx, xMax:nineIdx, borderColor:'red', borderWidth:2, label:{enabled:true, content:'−9M', position:'start', backgroundColor:'red',} },
                zeroLine:      { type:'line', yMin:0, yMax:0, borderColor:'black', borderWidth:1, borderDash:[3,3] },
                plus20: { type:'line', yMin:20, yMax:20, borderColor:'orange', borderWidth:1, borderDash:[3,3],
                  label:{content:'+20 (Restriktiv-Schwelle)', enabled:true, position:'start', backgroundColor:'orange', color:'white'} },
                minus20: { type:'line', yMin:-20, yMax:-20, borderColor:'green', borderWidth:1, borderDash:[3,3],
                  label:{content:'-20 (Entlastung)', enabled:true, position:'start', backgroundColor:'green', color:'white'} },
              }
            }
          }
        }
      });
    }
    
    // Laden + Zeichnen
    fetch('execute/globale-liquiditaet/gli_macro_index.php')
      .then(r=>r.json())
      .then(res=>{
        if (res.error) throw new Error(res.error);
        const labelsDE = (res.labels||[]).map(formatMonthDE);
        buildMacroChart(labelsDE, res.comp||[], res.impact||[]);
      })
      .catch(e=>console.error('Macro-Index Fehler:', e));
  </script>
  
  <script>
    // FCI-Chart (Composite + SMA3, inkl. −9M Linie)
    let fciChart;
    const fciCtx = document.getElementById('gliFciChart').getContext('2d');
    
    function buildFciChart(labels, data, sma3) {
      if (fciChart) fciChart.destroy();
      const labelsDE = labels.map(formatMonthDE);
      const nineIdx = getNineMonthsAgoIndex(labels); // nutzt YYYY-MM
    
      fciChart = new Chart(fciCtx, {
        type: 'line',
        data: {
          labels: labelsDE,
          datasets: [
            { label: 'FCI (z-Composite)', data, borderWidth: 2, borderColor: '#000', backgroundColor: '#000', pointRadius: 1, fill: false, tension: 0 },
            { label: 'SMA(3)', data: sma3, borderWidth: 1.5, borderColor: 'red', pointRadius: 0, borderDash: [4,3], fill: false, tension: 0 }
          ]
        },
        options: {
          responsive: true,
          interaction: { mode: 'nearest', intersect: false },
          scales: {
            y: { title: { display: true, text: 'z-Score', font: { weight: 'bold' } }, ticks: { font: { weight: 'bold' } } },
            x: { title: { display: true, text: 'Monat',  font: { weight: 'bold' } }, ticks: { font: { weight: 'bold' } } }
          },
          plugins: {
            legend: { display: true },
            tooltip: { callbacks: { label: c => `${c.dataset.label}: ${c.raw===null?'–':formatNumberDE(c.raw,3)}` } },
            annotation: {
              annotations: {
                nineMonthsLine: { type:'line', xMin:nineIdx, xMax:nineIdx, borderColor:'red', borderWidth:2, label:{enabled:true, content:'−9M', position:'start', backgroundColor:'red', } },
                zeroLine:      { type:'line', yMin:0, yMax:0, borderColor:'black', borderWidth:1, borderDash:[3,3] },
                plus05: { type:'line', yMin:0.5, yMax:0.5, borderColor:'orange', borderWidth:1, borderDash:[3,3],
                  label:{content:'+0.5 (Restriktiv)', enabled:true, position:'start', backgroundColor:'orange', color:'white'} },
                minus05: { type:'line', yMin:-0.5, yMax:-0.5, borderColor:'green', borderWidth:1, borderDash:[3,3],
                  label:{content:'-0.5 (Expansiv)', enabled:true, position:'start', backgroundColor:'green', color:'white'} },

              }
            }
          }
        }
      });
    }
    
    // Daten laden und rendern
    fetch('execute/globale-liquiditaet/gli_fci_index.php')
      .then(r => r.json())
      .then(res => {
        if (res.error) throw new Error(res.error);
        const labels = res.labels || [];          // YYYY-MM
        const data   = (res.data || []).map(v => v===null?null:Number(v));
        const sma3   = (res.avg3Data || []).map(v => v===null?null:Number(v));
        buildFciChart(labels, data, sma3);
      })
      .catch(e => console.error('FCI-Fehler:', e));

  </script>

  <script src="assets/js/chartjs-plugin-crosshair.js"></script>
  
  <script>
    let fciCurrent = null;
    let macroImpactNow = null;
  
    function updateAllocation(fci, macro) {
      let msg = "neutral";
      if (fci <= -0.5 && macro <= -20) msg = "Full Risk-On (Aktien hoch, EM/HY erlaubt)";
      else if (fci <= -0.5 && macro >= 20) msg = "Vorsicht: Gewinne sichern";
      else if (fci >= 0.5 && macro >= 20) msg = "Full Risk-Off (Cash, Defensiv)";
      else if (fci >= 0.5 && macro <= -20) msg = "Antizyklisch vorbereiten (Cash halten)";
      // … Rest nach deiner Matrix
      document.getElementById('allocationBox').textContent = "FCI-Investment-Ampel: " + msg;
    }
  
    function tryUpdateAmpel() {
      if (fciCurrent !== null && macroImpactNow !== null) {
        updateAllocation(fciCurrent, macroImpactNow);
      }
    }
  
    // Macro Pressure laden
    fetch('execute/globale-liquiditaet/gli_macro_index.php')
      .then(r=>r.json())
      .then(res=>{
        const data = res.impact || [];
        macroImpactNow = data.length ? data[data.length-1] : null; // letzter Impact-Wert
        tryUpdateAmpel();
      })
      .catch(e=>console.error('Macro-Index Fehler:', e));
  
    // FCI laden
    fetch('execute/globale-liquiditaet/gli_fci_index.php')
      .then(r=>r.json())
      .then(res=>{
        const data = res.data || [];
        fciCurrent = data.length ? data[data.length-1] : null; // letzter Wert
        tryUpdateAmpel();
      })
      .catch(e=>console.error('FCI Fehler:', e));
  </script>
  
  <script>
    // Tabellen-Renderer (nutzt deine formatMonthDE/formatNumberDE)
    function renderRows(tbody, labels, colA, colB, digitsA=2, digitsB=2) {
      tbody.innerHTML = '';
      const n = labels.length;
      const take = Math.min(12, n);
      for (let i = n - take; i < n; i++) {
        const m = labels[i];
        const a = colA?.[i];
        const b = colB?.[i];
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${formatMonthDE(m)}</td>
          <td>${a==null?'–':formatNumberDE(a, digitsA)}</td>
          <td>${b==null?'–':formatNumberDE(b, digitsB)}</td>
        `;
        tbody.appendChild(tr);
      }
    }
    
    // Macro Pressure (from gli_macro_index.php)
    fetch('execute/globale-liquiditaet/gli_macro_index.php')
      .then(r=>r.json())
      .then(res=>{
        const labels = res.labels || [];            // YYYY-MM
        const now    = res.comp   || [];            // aktueller Score
        const impact = res.impact || [];            // +9M verschoben
        const tb = document.querySelector('#macroTable tbody');
        renderRows(tb, labels, now, impact, 1, 1);
      })
      .catch(e=>console.error('Macro Sanity Fehler:', e));
    
    // FCI (from gli_fci_index.php)
    fetch('execute/globale-liquiditaet/gli_fci_index.php')
      .then(r=>r.json())
      .then(res=>{
        const labels = res.labels   || [];          // YYYY-MM
        const data   = res.data     || [];          // z-Composite
        const sma3   = res.avg3Data || [];          // SMA(3)
        const tb = document.querySelector('#fciTable tbody');
        renderRows(tb, labels, data, sma3, 3, 3);
      })
      .catch(e=>console.error('FCI Sanity Fehler:', e));

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