/* Dashboard page — header, reports table, request form, and main wiring */

const { useState, useMemo, useEffect } = React;

const TYPE_FILTERS = ['Alle', 'Makro', 'Geo', 'Konflikt', 'Infra', 'Asset', 'Simulation'];

/* ---------- Helpers ---------- */
function fmtDate(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  const months = ['Jan','Feb','Mrz','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
  return `${String(d.getDate()).padStart(2,'0')} · ${months[d.getMonth()]} · ${d.getFullYear()}`;
}

function fmtDateTime(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleString('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
}

function nextAgentRun() {
  const now = new Date();
  const noon     = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 12, 0, 0));
  const midnight = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1, 0, 0, 0));
  const next = now < noon ? noon : midnight;
  return next.toLocaleString('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
}

function simToRow(sim) {
  return {
    id:     sim.sim_id,
    title:  sim.title || sim.label || sim.dominant_scenario || sim.sim_id,
    type:   'Simulation',
    date:   fmtDate(sim.published_at || sim.last_updated),
    pages:  sim.pdf_pages ? `${sim.pdf_pages} S.` : null,
    status: 'live', // getLiveReports gibt ausschließlich live Reports zurück
    dominantPct: sim.dominant_probability ? Math.round(sim.dominant_probability * 100) : null,
  };
}

function StatusPill({ status }) {
  if (status === 'live')  return <span className="pill pill-live"><span className="dot" />Aktuell</span>;
  if (status === 'draft') return <span className="pill pill-draft"><span className="dot" style={{ background: 'var(--on-surface-dim)' }} />In Bearbeitung</span>;
  return <span className="pill pill-arch"><span className="dot" style={{ background: 'var(--on-surface-quiet)' }} />Archiv</span>;
}

/* ---------- Dashboard header ---------- */
function DashHeader({ agentStatus, simCount }) {
  const lastRun  = agentStatus?.recent_runs?.[0];
  const lastRunIso = lastRun?.finished_at || lastRun?.started_at;
  const timestampStr = lastRunIso
    ? fmtDateTime(lastRunIso) + ' UTC'
    : new Date().toLocaleString('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) + ' UTC';

  const bodyText = lastRunIso
    ? `Letzter Agent-Run: ${fmtDateTime(lastRunIso)} UTC. Nächstes Update: ${nextAgentRun()} UTC. Eskalationspfade werden kontinuierlich überwacht.`
    : `Nächster geplanter Agent-Run: ${nextAgentRun()} UTC. Eskalationspfade werden kontinuierlich überwacht.`;

  const statsData = [
    ['Aktive Simulationen',   String(simCount || 0),    'vom Backend'],
    ['Letzter Agent-Run',     lastRunIso ? fmtDateTime(lastRunIso) : '—', lastRun ? `${lastRun.sims_updated ?? '—'} Sims aktualisiert` : 'noch kein Run'],
  ];

  return (
    <section style={{ paddingTop: 132, paddingBottom: 48 }}>
      <div className="container">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div className="eyebrow"><span className="label">Dashboard / Lagebild</span></div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--on-surface-dim)' }}>
            Stand {timestampStr}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '7fr 5fr', gap: 24, marginTop: 56, alignItems: 'end' }}>
          <h1 className="display-sm" style={{ margin: 0, color: 'var(--primary)' }}>
            {simCount} aktive Simulationen.
          </h1>
          <p className="body" style={{ margin: 0, maxWidth: 460, color: 'var(--on-surface-dim)', fontSize: 13.5 }}>
            {bodyText}
          </p>
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1,
          background: 'var(--ghost-strong)', marginTop: 56, border: '1px solid var(--ghost)',
        }}>
          {statsData.map(([k, v, sub], i) => (
            <div key={i} style={{ background: 'var(--surface)', padding: '24px 22px' }}>
              <div className="label">{k}</div>
              <div className="tnum" style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--primary)', marginTop: 14, lineHeight: 1 }}>
                {v}
              </div>
              <div className="body-sm" style={{ marginTop: 10, fontSize: 12, color: 'var(--on-surface-dim)' }}>{sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Reports table ---------- */
function ReportsTable({ reports, loading }) {
  const [filter, setFilter] = useState('Alle');
  const [query,  setQuery]  = useState('');

  const filtered = useMemo(() => {
    return (reports || []).filter(r => {
      if (filter !== 'Alle' && r.type !== filter) return false;
      if (query && !(r.title.toLowerCase() + r.id.toLowerCase()).includes(query.toLowerCase())) return false;
      return true;
    });
  }, [reports, filter, query]);

  return (
    <div className="dash-card" style={{ height: '100%' }}>
      <div className="dash-card-hdr" style={{ flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="label">Reports · Übersicht</div>
          <div className="title" style={{ marginTop: 6 }}>Alle Berichte</div>
        </div>
        <div className="seg">
          {TYPE_FILTERS.map(t => (
            <button key={t} className={t === filter ? 'on' : ''} onClick={() => setFilter(t)}>{t}</button>
          ))}
        </div>
      </div>

      <div style={{ padding: '12px 22px 0' }}>
        <input
          className="input"
          placeholder="Suche · Titel oder ID"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          style={{ background: 'var(--surface-low)', borderColor: 'var(--ghost-strong)' }}
        />
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1fr) 110px 100px',
        padding: '20px 22px 10px', gap: 16,
      }}>
        <div className="label">Bericht</div>
        <div className="label">Datum</div>
        <div className="label">Status</div>
      </div>

      {loading ? (
        <div style={{ padding: '32px 22px', display: 'flex', alignItems: 'center', gap: 12, color: 'var(--on-surface-dim)', fontSize: 12, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
          <span style={{ animation: 'spin 1.2s linear infinite', display: 'inline-block' }}>◌</span>
          Daten werden geladen…
        </div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: '40px 22px', textAlign: 'center' }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--on-surface-dim)', marginBottom: 12 }}>
            {(reports || []).length === 0 ? 'Keine publizierten Simulationen' : 'Keine Treffer'}
          </div>
          {(reports || []).length === 0 && (
            <p style={{ fontSize: 13, color: 'var(--on-surface-quiet)', margin: 0, lineHeight: 1.6 }}>
              Starte eine Simulation über „Bericht anfordern" oder publiziere eine bestehende im Admin-Bereich.
            </p>
          )}
        </div>
      ) : (
        filtered.map((r) => (
          <a key={r.id} className="dash-row dash-row-link" href={`report-detail.html?id=${r.id}`}
             style={{ textDecoration: 'none', color: 'inherit', cursor: 'pointer' }}>
            <div style={{ minWidth: 0 }}>
              <div title={r.title} style={{
                fontSize: 14, color: 'var(--on-surface)', letterSpacing: '-0.005em',
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>
                {r.title}
              </div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.06em', color: 'var(--on-surface-quiet)', marginTop: 3 }}>
                {r.id}
              </div>
            </div>
            <div className="mono tnum" style={{ fontSize: 12, color: 'var(--on-surface-dim)' }}>{r.date}</div>
            <div><StatusPill status={r.status} /></div>
          </a>
        ))
      )}

      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '18px 22px', borderTop: '1px solid var(--ghost)',
      }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--on-surface-quiet)' }}>
          {loading ? '…' : `${filtered.length} von ${(reports || []).length} Berichten`}
        </div>
        <a href="intelligence.html" className="btn btn-tertiary btn-sm">
          Intelligence-Übersicht <span className="arrow">→</span>
        </a>
      </div>
    </div>
  );
}

/* ---------- Request a report ---------- */
function RequestReport() {
  return (
    <React.Fragment>

      <div className="dash-card">
        <div className="dash-card-hdr">
          <div>
            <div className="label">Auftragsanfrage</div>
            <div className="title" style={{ marginTop: 6 }}>Bericht anfordern</div>
          </div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--on-surface-dim)', border: '1px solid var(--ghost-strong)', padding: '3px 8px' }}>
            Coming Soon
          </div>
        </div>

        <div style={{ padding: '40px 22px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 16 }}>
          <div style={{ fontSize: 32, letterSpacing: '-0.01em', color: 'var(--on-surface-quiet)' }}>—</div>
          <p style={{ margin: 0, fontSize: 13, color: 'var(--on-surface-dim)', lineHeight: 1.65, maxWidth: 440 }}>
            Die direkte Berichtsanfrage wird in Kürze freigeschaltet. Reports können bis dahin intern über das Admin-Panel ausgelöst werden.
          </p>
          <a href="admin.html" className="btn btn-secondary btn-sm" style={{ marginTop: 4 }}>
            Admin-Panel öffnen →
          </a>
        </div>
      </div>
    </React.Fragment>
  );
}

/* ---------- Welcome Modal ---------- */
function WelcomeModal({ onClose, onRequestReport }) {
  const sections = [
    { tag: '01', name: 'Simulations-Archiv',   body: 'Alle veröffentlichten Engine-Simulationen in Echtzeit vom Backend geladen. Klicken Sie eine Simulation an, um den vollständigen Report zu öffnen.' },
    { tag: '02', name: 'Geopolitische Lagekarte', body: 'Interaktive Weltkarte mit Konfliktherden, Lieferketten und Sanktionsregimen. Layer ein- und ausblendbar. Vollbild per Taste F.' },
    { tag: '03', name: 'GeoStrat-Portfolio',    body: 'Aktuelle Allokationsempfehlung direkt aus der letzten Engine-Simulation — für Vermögensverwalter, Family Offices und Privatanleger.' },
    { tag: '04', name: 'Bericht anfordern',     body: 'Eigene Thesen einreichen. Die GeoStrat-Engine startet sofort eine KI-gestützte Simulation und generiert einen vollständigen Analyse-Report.' },
  ];

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(10,10,10,0.82)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }}
    onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{
        background: 'var(--surface-lowest)', border: '1px solid var(--ghost-strong)',
        maxWidth: 720, width: '100%', maxHeight: '90vh', overflowY: 'auto',
        animation: 'fadeIn 320ms cubic-bezier(.2,.6,.2,1) both',
      }}>
        <div style={{ padding: '36px 40px 28px', borderBottom: '1px solid var(--ghost)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--on-surface-dim)', marginBottom: 14 }}>
              RICS Analytics · Dashboard
            </div>
            <h2 className="display-sm" style={{ margin: 0, fontSize: 'clamp(24px, 3vw, 36px)', letterSpacing: '-0.025em', color: 'var(--primary)', fontWeight: 500 }}>
              Willkommen im<br /><span style={{ color: 'var(--on-surface-variant)' }}>Analyse-Dashboard.</span>
            </h2>
            <p className="body" style={{ marginTop: 18, maxWidth: 480, fontSize: 14, lineHeight: 1.6, color: 'var(--on-surface-dim)' }}>
              Das Dashboard gibt Ihnen Zugriff auf alle aktiven Engine-Reports, die geopolitische Lagekarte und die aktuelle GeoStrat-Portfolioempfehlung — in Echtzeit vom Backend.
            </p>
          </div>
          <button onClick={onClose} style={{
            background: 'none', border: '1px solid var(--ghost-strong)', color: 'var(--on-surface-dim)',
            fontSize: 16, lineHeight: 1, padding: '6px 10px', cursor: 'pointer', flexShrink: 0,
          }} aria-label="Schließen">✕</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: 'var(--ghost-strong)', margin: '1px 0' }}>
          {sections.map((s) => (
            <div key={s.tag} style={{ background: 'var(--surface)', padding: '28px 30px' }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--on-surface-quiet)', textTransform: 'uppercase', marginBottom: 10 }}>/{s.tag}</div>
              <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em', color: 'var(--on-surface)', marginBottom: 10 }}>{s.name}</div>
              <p className="body-sm" style={{ margin: 0, fontSize: 13, color: 'var(--on-surface-dim)', lineHeight: 1.55 }}>{s.body}</p>
            </div>
          ))}
        </div>

        <div style={{ padding: '24px 40px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid var(--ghost)', flexWrap: 'wrap', gap: 12 }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.06em', color: 'var(--on-surface-quiet)' }}>
            KI-gestützte Simulation · Sofortiger Report
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn btn-secondary btn-sm" onClick={onRequestReport}>Bericht anfordern <span className="arrow">→</span></button>
            <button className="btn btn-primary btn-sm" onClick={onClose}>Dashboard öffnen <span className="arrow">→</span></button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Dashboard root ---------- */
function Dashboard() {
  const [showWelcome, setShowWelcome] = React.useState(() => {
    try { return !localStorage.getItem('rics_dashboard_welcomed'); } catch (_) { return true; }
  });

  const [agentStatus, setAgentStatus] = React.useState(null);
  const [sims,        setSims]        = React.useState([]);
  const [loading,     setLoading]     = React.useState(true);

  useEffect(() => {
    if (!window.RICS_API) { setLoading(false); return; }
    Promise.all([
      window.RICS_API.getAgentStatus().catch(() => null),
      window.RICS_API.getLiveReports().catch(() => []),
    ]).then(([agent, simList]) => {
      setAgentStatus(agent);
      setSims(Array.isArray(simList) ? simList : []);
      setLoading(false);
    });
  }, []);

  const allReports = useMemo(() => sims.map(simToRow), [sims]);

  const closeWelcome = () => {
    try { localStorage.setItem('rics_dashboard_welcomed', '1'); } catch (_) {}
    setShowWelcome(false);
  };
  const goToRequest = () => {
    closeWelcome();
    setTimeout(() => {
      const el = document.getElementById('request-report');
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 80);
  };

  return (
    <React.Fragment>
      {showWelcome && <WelcomeModal onClose={closeWelcome} onRequestReport={goToRequest} />}
      <Nav />
      <main>
        <DashHeader agentStatus={agentStatus} simCount={sims.length} />
        <section id="reports" style={{ paddingBottom: 64, scrollMarginTop: 80 }}>
          <div className="container" style={{ display: 'grid', gridTemplateColumns: '7fr 5fr', gap: 24, alignItems: 'start' }}>
            <ReportsTable reports={allReports} loading={loading} />
            <div id="portfolio" style={{ scrollMarginTop: 80 }}><PortfolioWidget /></div>
          </div>
        </section>

        <section id="request-report" style={{ paddingBottom: 120, scrollMarginTop: 80 }}>
          <div className="container"><RequestReport /></div>
        </section>
      </main>
      <Footer />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Dashboard />);
