const qs = s => document.querySelector(s);
const qsa = s => Array.from(document.querySelectorAll(s));

async function getJSON(url){ const r = await fetch(url); return r.json(); }

function setActiveTab(key){
  qsa('.sidebar nav a').forEach(a=>a.classList.toggle('active', a.dataset.tab===key));
  qsa('.view').forEach(v=>v.classList.add('hidden'));
  qs('#view-'+key).classList.remove('hidden');
}

function card(title, right=''){ return `<div class="card"><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px"><div class="font-semibold">${title}</div><div>${right}</div></div>` }
function end(){ return `</div>` }

function badge(text,tone){ return `<span class="badge ${tone}">${text}</span>` }

async function renderOverview(){
  const wrap = qs('#view-overview');
  const scans = await getJSON('/api/scans');
  const latest = (scans.items||[])[0];
  const head = `${latest?latest.at+' · '+latest.kind+' · '+latest.status:''}`;

  wrap.innerHTML = `
    <div class="grid col3">
      <div class="card"><div>Markttrend</div><div style="font-weight:600;margin-top:6px">Aufwärts</div><div style="color:#6b7280;font-size:12px">aus D1/H1/15m</div></div>
      <div class="card"><div>Neue Signale (heute)</div><div style="font-weight:600;margin-top:6px">–</div><div class="badge info">Demo</div></div>
      <div class="card"><div>Systemstatus</div><div style="font-weight:600;margin-top:6px">Stabil</div><div style="color:#6b7280;font-size:12px">Telegram OK • Cron OK</div></div>
    </div>

    <div class="grid col2">
      ${card('Tickerliste', `<a class="badge mute" href="/api/export/tickers.csv">Export CSV</a>`)}
        <div id="tbl"></div>
      ${end()}
      ${card('Scan-Historie', '')}
        <ul id="scanlist" style="margin:0;padding-left:18px"></ul>
      ${end()}
    </div>
  `;

  const data = await getJSON('/api/tickers');
  const rows = (data.items||[]).map(r=>`
    <tr>
      <td><b>${r.ticker}</b></td>
      <td>${r.date||''}</td>
      <td>${r.price??'–'}</td>
      <td>${r.trend||'—'}</td>
      <td>${r.score??'—'}%</td>
      <td>${r.rvol??'—'}</td>
      <td>${r.atrp??'—'}</td>
      <td>${r.last_scan||'—'}</td>
      <td>${r.result||'—'}</td>
    </tr>
  `).join('');
  qs('#tbl').innerHTML = `
    <table class="table">
      <thead><tr><th>Ticker</th><th>Datum</th><th>Kurs</th><th>Trend</th><th>Score</th><th>RVOL</th><th>ATR%</th><th>Letzter Scan</th><th>Ergebnis</th></tr></thead>
      <tbody>${rows}</tbody>
    </table>
  `;

  const lis = (scans.items||[]).slice(0,20).map(s=>`<li>${s.at} · ${s.kind} · ${s.status}</li>`).join('');
  qs('#scanlist').innerHTML = lis || '<li>Keine Scans</li>';
}

async function renderTickers(){
  const wrap = qs('#view-tickers');
  const data = await getJSON('/api/tickers');
  const rows = (data.items||[]).map(r=>`
    <tr>
      <td><b>${r.ticker}</b></td>
      <td>${r.date}</td>
      <td>${r.price??'–'}</td>
      <td>${r.trend}</td>
      <td>${r.score??'—'}%</td>
      <td>${r.rvol??'—'}</td>
      <td>${r.atrp??'—'}</td>
      <td>${r.last_scan||'—'}</td>
      <td>${r.result||'—'}</td>
    </tr>`).join('');
  wrap.innerHTML = `${card('Tickerliste', `<a class="badge mute" href="/api/export/tickers.csv">Export CSV</a>`)}
    <table class="table">
      <thead><tr><th>Ticker</th><th>Datum</th><th>Kurs</th><th>Trend</th><th>Score</th><th>RVOL</th><th>ATR%</th><th>Letzter Scan</th><th>Ergebnis</th></tr></thead>
      <tbody>${rows}</tbody>
    </table>${end()}`;
}

async function renderScans(){
  const wrap = qs('#view-scans');
  const scans = await getJSON('/api/scans');
  wrap.innerHTML = `${card('Scan-Historie')}${(scans.items||[]).map(s=>`
    <div style="display:flex;justify-content:space-between;border:1px solid #e5e7eb;border-radius:10px;padding:8px 12px;margin-bottom:8px">
      <div><div style="font-weight:600">${s.kind}</div><div style="color:#6b7280;font-size:12px">${s.at}</div></div>
      <div>${badge(s.status, s.status==='Erfolg'?'succ':'dang')}</div>
    </div>`).join('')}${end()}`;
}

function renderSignals(){ qs('#view-signals').innerHTML = `${card('Live-Signale')}<div>Demodaten folgen beim Anschluss der Engine.</div>${end()}`; }
function renderQuality(){ qs('#view-quality').innerHTML = `${card('Datenqualität')}<div>Demo-KPIs – wird mit echter Telemetrie verdrahtet.</div>${end()}`; }
function renderSettings(){
  qs('#view-settings').innerHTML = `${card('Einstellungen')}
    <div style="display:grid;gap:12px">
      <div><div>Schwellen & Filter</div>
        <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-top:6px">
          <label>Score ≥ <input value="88" style="float:right;width:80px"></label>
          <label>RVOL ≥ <input value="1.3" style="float:right;width:80px"></label>
          <label>ATR% 2–8 <input value="2–8" style="float:right;width:80px"></label>
          <label>CRV ≥ <input value="1.5" style="float:right;width:80px"></label>
        </div>
      </div>
      <div><div>Live-Scan Filter</div>
        <div id="livefilters"></div>
        <button id="addfilter" class="badge mute" style="margin-top:6px">+ Filter</button>
      </div>
    </div>${end()}`;
  const box = qs('#livefilters');
  const add = (f={field:'Preis ≥',op:'>=',value:'5'})=>{
    const id = 'f'+Math.random().toString(36).slice(2,7);
    box.insertAdjacentHTML('beforeend',
      `<div id="${id}" style="display:grid;grid-template-columns:1fr 80px 1fr;gap:6px;margin-top:6px;border:1px solid #e5e7eb;border-radius:10px;padding:6px 8px">
        <input value="${f.field}"><input value="${f.op}" style="text-align:center"><div style="display:flex;gap:6px"><input value="${f.value}" style="flex:1;text-align:right"><button onclick="document.getElementById('${id}').remove()" class="badge">×</button></div>
      </div>`);
  };
  window.addEventListener('click', e=>{ if(e.target.id==='addfilter') add(); });
  add(); // eine Startzeile
}

// Tabs
qsa('.sidebar nav a').forEach(a=>a.addEventListener('click', ()=>{
  setActiveTab(a.dataset.tab);
  if(a.dataset.tab==='overview') renderOverview();
  if(a.dataset.tab==='tickers') renderTickers();
  if(a.dataset.tab==='scans') renderScans();
  if(a.dataset.tab==='signals') renderSignals();
  if(a.dataset.tab==='quality') renderQuality();
  if(a.dataset.tab==='settings') renderSettings();
}));

// Start
setActiveTab('overview'); renderOverview();
