/* Intelligence Dashboard — Seite A
   Shows: Agent status, all simulations, conflict alerts, custom report trigger */

const { useState: useStateI, useEffect: useEffectI } = React;

function fmtTime(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 nextRunTimes() {
  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' });
}

/* ---------- Agent status bar ---------- */
function AgentBar({ agentData, onTrigger, triggering }) {
  const last = agentData?.last_run;

  return (
    <div className="agent-bar">
      <div style={{ display: 'flex', align: 'center', gap: 32, flexWrap: 'wrap' }}>
        {/* Last run */}
        <div>
          <div className="label" style={{ marginBottom: 6 }}>Letzter Run</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            {last ? (
              <>
                <span style={{
                  width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
                  background: last.status === 'completed' ? '#FFFFFF' :
                              last.status === 'failed'    ? '#E5B25C' : 'var(--on-surface-dim)',
                }} />
                <span style={{ fontSize: 13, color: 'var(--on-surface)' }}>
                  {fmtTime(last.finished_at || last.started_at)}
                </span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--on-surface-dim)' }}>
                  · {last.sims_updated ?? 0} Sims · {last.new_conflicts ?? 0} Konflikte
                </span>
              </>
            ) : (
              <span style={{ fontSize: 13, color: 'var(--on-surface-dim)' }}>Kein Run verfügbar</span>
            )}
          </div>
        </div>

        {/* Next run */}
        <div>
          <div className="label" style={{ marginBottom: 6 }}>Nächster Run</div>
          <div style={{ fontSize: 13, color: 'var(--on-surface-variant)' }}>
            {nextRunTimes()} UTC&nbsp;
            <span className="mono" style={{ fontSize: 10, color: 'var(--on-surface-dim)' }}>
              (tägl. 00:00 + 12:00)
            </span>
          </div>
        </div>
      </div>

      {/* Trigger button */}
      <button
        className="btn btn-secondary btn-sm"
        onClick={onTrigger}
        disabled={triggering}
        style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}
      >
        {triggering && (
          <div style={{
            width: 12, height: 12, border: '1.5px solid var(--ghost-strong)',
            borderTopColor: 'var(--on-surface)', borderRadius: '50%',
            animation: 'spin 0.9s linear infinite',
          }} />
        )}
        {triggering ? 'Wird gestartet…' : 'Jetzt ausführen →'}
      </button>
    </div>
  );
}

/* ---------- Simulation card ---------- */
function SimCard({ sim }) {
  const pct = Math.round((sim.dominant_probability ?? 0) * 100);
  return (
    <a href={`simulation.html?id=${sim.sim_id}`} className="sim-card">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--on-surface-dim)' }}>
          {sim.sim_id}
        </div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--on-surface-quiet)' }}>
          {fmtTime(sim.last_updated)}
        </div>
      </div>

      <div style={{ fontSize: 16, fontWeight: 500, letterSpacing: '-0.01em', color: 'var(--primary)', marginBottom: 6, lineHeight: 1.3 }}>
        {sim.dominant_scenario}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
        <span className="prob-large" style={{ fontSize: 28 }}>{pct}%</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--on-surface-dim)' }}>
          {sim.scenario_count} Szenarien · {sim.rounds_completed} Runden
        </span>
      </div>

      {/* Mini probability bar */}
      <div style={{ height: 2, background: 'var(--ghost-strong)' }}>
        <div style={{ height: '100%', width: `${Math.min(pct, 100)}%`, background: 'var(--primary)', transition: 'width 600ms ease' }} />
      </div>

      <div style={{ marginTop: 14, display: 'flex', justifyContent: 'flex-end' }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: 'var(--on-surface-quiet)', textTransform: 'uppercase' }}>
          Detail öffnen →
        </span>
      </div>
    </a>
  );
}

/* ---------- Conflict alert list ---------- */
function ConflictAlerts({ conflicts }) {
  if (!conflicts || conflicts.length === 0) return null;

  return (
    <div style={{ background: 'var(--surface-lowest)', border: '1px solid var(--ghost)', marginBottom: 36 }}>
      <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--ghost)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="label">Neu erkannte Konflikte</div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--on-surface-dim)' }}>
          {conflicts.length} Einträge
        </div>
      </div>
      {conflicts.slice(0, 8).map((c) => (
        <div key={c.id} className="conflict-item">
          <div>
            <div style={{ fontSize: 14, color: 'var(--on-surface)', marginBottom: 4 }}>{c.topic}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--on-surface-dim)', letterSpacing: '0.06em' }}>
              {fmtTime(c.detected_at)}
              {c.status === 'simulation_created' ? ' · Simulation erstellt' : ' · Fehlgeschlagen'}
            </div>
          </div>
          {c.sim_id && (
            <a href={`simulation.html?id=${c.sim_id}`} className="btn btn-tertiary btn-sm">
              Report →
            </a>
          )}
        </div>
      ))}
    </div>
  );
}

/* ---------- Intelligence Dashboard root ---------- */
function IntelligenceDashboard() {
  const [agentData, setAgentData] = useStateI(null);
  const [sims, setSims] = useStateI([]);
  const [conflicts, setConflicts] = useStateI([]);
  const [loading, setLoading] = useStateI(true);
  const [triggering, setTriggering] = useStateI(false);
  const [triggerMsg, setTriggerMsg] = useStateI('');
  const [showOptimizer, setShowOptimizer] = useStateI(false);
  const [customPrompt] = useStateI('');

  const load = async () => {
    try {
      const [agent, simsRes, conflictsRes] = await Promise.all([
        window.RICS_API.getAgentStatus().catch(() => null),
        window.RICS_API.getLiveReports().catch(() => []),
        window.RICS_API.getConflicts(20).catch(() => []),
      ]);
      setAgentData(agent);
      setSims(Array.isArray(simsRes) ? simsRes : []);
      setConflicts(Array.isArray(conflictsRes) ? conflictsRes : []);
    } finally {
      setLoading(false);
    }
  };

  useEffectI(() => { load(); }, []);

  const handleTrigger = async () => {
    setTriggering(true);
    setTriggerMsg('');
    try {
      await window.RICS_API.triggerAgent();
      setTriggerMsg('Agent wurde gestartet. Daten in ~10 Minuten aktualisiert.');
      setTimeout(load, 5000);
    } catch (e) {
      setTriggerMsg('Fehler: ' + e.message);
    } finally {
      setTriggering(false);
    }
  };

  return (
    <React.Fragment>
      {showOptimizer && (
        <PromptOptimizerModal
          rawPrompt={customPrompt || 'Strategische Analyse:'}
          onClose={() => setShowOptimizer(false)}
          onLaunched={(simId) => { window.location.href = `simulation.html?id=${simId}`; }}
        />
      )}

      <Nav />
      <main style={{ paddingTop: 96, paddingBottom: 120 }}>
        <div className="container">
          {/* Breadcrumb */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 40 }}>
            <a href="dashboard.html" className="nav-link">← Dashboard</a>
            <span className="mono" style={{ fontSize: 11, color: 'var(--ghost-strong)' }}>/</span>
            <span className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', color: 'var(--on-surface-dim)' }}>
              Intelligence
            </span>
          </div>

          {/* Header */}
          <div style={{ display: 'grid', gridTemplateColumns: '7fr 5fr', gap: 24, marginBottom: 56, alignItems: 'end' }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 20 }}>
                <span className="label">Intelligence</span>
              </div>
              <h1 className="display-sm" style={{ margin: 0, fontSize: 'clamp(28px, 3.5vw, 48px)', color: 'var(--primary)' }}>
                {loading ? 'Daten werden geladen…' : `${sims.length} aktive Simulationen.`}<br />
                <span style={{ color: 'var(--on-surface-variant)' }}>Täglich aktualisiert.</span>
              </h1>
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', alignItems: 'flex-end' }}>
              <button className="btn btn-secondary" onClick={() => setShowOptimizer(true)}>
                Benutzerdefinierten Bericht anfordern <span className="arrow">→</span>
              </button>
            </div>
          </div>

          {/* Agent status bar */}
          {!loading && (
            <AgentBar agentData={agentData} onTrigger={handleTrigger} triggering={triggering} />
          )}

          {triggerMsg && (
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', color: 'var(--on-surface-dim)', marginBottom: 20 }}>
              {triggerMsg}
            </div>
          )}

          {/* Conflict alerts */}
          {!loading && <ConflictAlerts conflicts={conflicts} />}

          {/* Simulations grid */}
          {loading ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 20, padding: '48px 0' }}>
              <div className="spinner" />
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--on-surface-dim)' }}>
                Simulationen werden geladen…
              </div>
            </div>
          ) : sims.length === 0 ? (
            <div style={{ padding: '48px 0' }}>
              <div className="mono" style={{ fontSize: 12, color: 'var(--on-surface-dim)', marginBottom: 16 }}>
                Noch keine Simulationen vorhanden.
              </div>
              <button className="btn btn-primary" onClick={() => setShowOptimizer(true)}>
                Erste Simulation starten →
              </button>
            </div>
          ) : (
            <div>
              <div className="label" style={{ marginBottom: 16 }}>
                Alle Simulationen · {sims.length} aktiv
              </div>
              <div className="sim-grid">
                {sims.map((s) => <SimCard key={s.sim_id} sim={s} />)}
              </div>
            </div>
          )}
        </div>
      </main>
      <Footer />
    </React.Fragment>
  );
}

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