/* Dashboard widgets — Portfolio donut (WorldMap ausgelagert → _world-map-widget.jsx.disabled) */

const { useState: useStateW, useMemo: useMemoW, useEffect: useEffectW } = React;

/* ============================================================
   IDEAL PORTFOLIO — GeoStrat Engine only
   ============================================================ */

/* ---------- Donut chart helpers ---------- */
function donutPath(cx, cy, R, r, startFrac, endFrac) {
  const τ = 2 * Math.PI;
  const toXY = (frac, radius) => [
    cx + radius * Math.cos(frac * τ - Math.PI / 2),
    cy + radius * Math.sin(frac * τ - Math.PI / 2),
  ];
  const [x1, y1] = toXY(startFrac, R);
  const [x2, y2] = toXY(endFrac,   R);
  const [x3, y3] = toXY(endFrac,   r);
  const [x4, y4] = toXY(startFrac, r);
  const large = endFrac - startFrac > 0.5 ? 1 : 0;
  return `M${x1},${y1} A${R},${R},0,${large},1,${x2},${y2} L${x3},${y3} A${r},${r},0,${large},0,${x4},${y4} Z`;
}

// Farbpalette nach Direction
function sliceColor(direction, index) {
  const d = (direction || '').toLowerCase();
  if (d.startsWith('short'))    return '#C4883A';          // amber
  if (d.includes('vol'))        return '#7CB9C4';          // teal — long_vol
  if (d.includes('underweight')) return '#8B6A3A';         // dunkles amber
  const longs = ['#FFFFFF', '#D4D4D4', '#AAAAAA', '#888888', '#666666', '#555555'];
  return longs[index % longs.length];
}

function PortfolioDonut({ positions }) {
  const [hovered, setHovered] = useStateW(null);

  if (!positions || positions.length === 0) return null;

  // Normalisiere auf 100 % (falls Positionen nicht exakt 100 ergeben)
  const total = positions.reduce((s, p) => s + (p.allocation_pct || 0), 0);
  const norm  = total > 0 ? 100 / total : 1;

  const cx = 80, cy = 80, R = 68, r = 44;
  let cursor = 0;
  const slices = positions.map((p, i) => {
    const frac = ((p.allocation_pct || 0) * norm) / 100;
    const slice = { p, i, startFrac: cursor, endFrac: cursor + frac };
    cursor += frac;
    return slice;
  });

  const hov = hovered != null ? positions[hovered] : null;

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 24, marginBottom: 20 }}>
      {/* SVG Donut */}
      <div style={{ position: 'relative', flexShrink: 0 }}>
        <svg width={160} height={160} style={{ display: 'block' }}>
          {slices.map(({ p, i, startFrac, endFrac }) => (
            <path
              key={i}
              d={donutPath(cx, cy, R, r, startFrac, endFrac)}
              fill={sliceColor(p.direction, i)}
              opacity={hovered === null || hovered === i ? 1 : 0.35}
              style={{ cursor: 'pointer', transition: 'opacity 120ms' }}
              onMouseEnter={() => setHovered(i)}
              onMouseLeave={() => setHovered(null)}
            />
          ))}
          {/* Zentrierter Text */}
          <text x={cx} y={cy - 8} textAnchor="middle" style={{ fill: 'var(--on-surface)', fontSize: hov?.ticker?.length > 8 ? 9 : 12, fontFamily: 'var(--font-mono)', letterSpacing: '0.04em', fontWeight: 600 }}>
            {hov ? (hov.ticker || hov.asset || '—') : `${positions.length}`}
          </text>
          <text x={cx} y={cy + 7} textAnchor="middle" style={{ fill: 'var(--on-surface-dim)', fontSize: 9, fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>
            {hov ? `${(hov.allocation_pct || 0).toFixed(0)}%` : 'POSITIONEN'}
          </text>
        </svg>
      </div>

      {/* Legende */}
      <div style={{ flex: 1, minWidth: 0 }}>
        {slices.map(({ p, i }) => (
          <div
            key={i}
            style={{
              display: 'grid', gridTemplateColumns: '10px 1fr auto',
              gap: 8, alignItems: 'center', padding: '3px 0',
              opacity: hovered === null || hovered === i ? 1 : 0.4,
              transition: 'opacity 120ms', cursor: 'default',
            }}
            onMouseEnter={() => setHovered(i)}
            onMouseLeave={() => setHovered(null)}
          >
            <div style={{ width: 8, height: 8, borderRadius: 1, background: sliceColor(p.direction, i), flexShrink: 0 }} />
            <div style={{ minWidth: 0 }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--on-surface)', letterSpacing: '0.04em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 500 }}>
                {p.ticker || p.asset || '—'}
              </div>
              {p.asset_class && (
                <div className="mono" style={{ fontSize: 9, color: 'var(--on-surface-quiet)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                  {p.asset_class}
                </div>
              )}
            </div>
            <div className="mono tnum" style={{ fontSize: 10, color: 'var(--on-surface-dim)', flexShrink: 0 }}>
              {(p.allocation_pct || 0).toFixed(0)}%
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Conviction stars renderer ---------- */
function ConvictionStars({ value, max = 5 }) {
  return (
    <span style={{ letterSpacing: 1, fontSize: 11 }}>
      {'★'.repeat(value)}{'☆'.repeat(max - value)}
    </span>
  );
}

/* ---------- Direction badge ---------- */
function DirectionBadge({ direction }) {
  const d = (direction || '').toLowerCase();
  const cfg =
    d.startsWith('short')     ? { symbol: '↓', color: '#E5B25C',               label: 'SHORT'    } :
    d === 'long_vol'           ? { symbol: '↗', color: '#7CB9C4',               label: 'LONG VOL' } :
    d.includes('underweight')  ? { symbol: '↘', color: '#8B6A3A',               label: 'UW'       } :
    d.startsWith('long')       ? { symbol: '↑', color: '#FFFFFF',               label: 'LONG'     } :
                                 { symbol: '—', color: 'var(--on-surface-quiet)', label: 'NEUTR'   };
  return (
    <span className="mono" style={{ fontSize: 10, color: cfg.color, letterSpacing: '0.08em' }}>
      {cfg.symbol} {cfg.label}
    </span>
  );
}

/* ---------- Agent position list (GeoStrat tab) ---------- */
function AgentPositionList({ positions, simId }) {
  if (!positions) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '32px 0' }}>
        <div className="spinner" style={{ width: 14, height: 14 }} />
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', color: 'var(--on-surface-dim)' }}>
          GeoStrat-Empfehlung wird geladen…
        </div>
      </div>
    );
  }

  if (positions.length === 0) {
    return (
      <div style={{ padding: '28px 0' }}>
        <div className="mono" style={{ fontSize: 12, color: 'var(--on-surface-dim)', marginBottom: 10 }}>
          Noch keine Agent-Empfehlung verfügbar.
        </div>
        <p style={{ fontSize: 13, color: 'var(--on-surface-quiet)', lineHeight: 1.6, margin: 0 }}>
          Daten werden beim nächsten Agent-Run generiert (tägl. 00:00 + 12:00 UTC) oder nach einer manuell gestarteten Simulation.
        </p>
      </div>
    );
  }

  return (
    <div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '80px 1fr 56px 72px',
        columnGap: 12, rowGap: 0, alignItems: 'center',
      }}>
        <div className="label" style={{ paddingBottom: 8, borderBottom: '1px solid var(--ghost)' }}>Richtung</div>
        <div className="label" style={{ paddingBottom: 8, borderBottom: '1px solid var(--ghost)' }}>Position</div>
        <div className="label" style={{ paddingBottom: 8, borderBottom: '1px solid var(--ghost)', textAlign: 'center' }}>Conv.</div>
        <div className="label" style={{ paddingBottom: 8, borderBottom: '1px solid var(--ghost)', textAlign: 'right' }}>Horizont</div>

        {positions.slice(0, 9).map((p, i) => (
          <React.Fragment key={i}>
            {/* Richtung + Allokation */}
            <div style={{ padding: '9px 0', display: 'flex', flexDirection: 'column', gap: 3 }}>
              <DirectionBadge direction={p.direction} />
              {p.allocation_pct != null && (
                <span className="mono tnum" style={{ fontSize: 9, color: 'var(--on-surface-quiet)', letterSpacing: '0.04em' }}>
                  {p.allocation_pct}%
                </span>
              )}
            </div>
            {/* Ticker + Instrument-Name + Agent */}
            <div style={{ padding: '9px 0', lineHeight: 1.3, minWidth: 0 }}>
              <div className="mono" style={{ fontSize: 13, color: 'var(--on-surface)', letterSpacing: '0.04em', fontWeight: 500 }}>
                {p.ticker || p.asset || '—'}
              </div>
              {(p.instrument_full_name || p.asset_class) && (
                <div style={{ fontSize: 11, color: 'var(--on-surface-dim)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {p.instrument_full_name || p.asset_class.toUpperCase()}
                </div>
              )}
              {p.source_agent && (
                <div className="mono" style={{ fontSize: 9, color: 'var(--on-surface-quiet)', marginTop: 2, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                  {p.source_agent}
                </div>
              )}
            </div>
            {/* Conviction */}
            <div style={{ textAlign: 'center', color: 'var(--on-surface-dim)', padding: '9px 0' }}>
              <ConvictionStars value={p.conviction || 0} />
            </div>
            {/* Horizont */}
            <div className="mono tnum" style={{ textAlign: 'right', fontSize: 11, color: 'var(--on-surface-dim)', padding: '9px 0' }}>
              {p.time_horizon_days ? `${p.time_horizon_days}d` : '—'}
            </div>
          </React.Fragment>
        ))}
      </div>

      {simId && (
        <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--ghost-strong)' }}>
          <a href={`simulation.html?id=${simId}`}
             className="btn btn-tertiary btn-sm"
             style={{ color: 'var(--on-surface-dim)' }}>
            Vollständige Simulation öffnen →
          </a>
        </div>
      )}

      <div className="mono" style={{ fontSize: 10, color: 'var(--on-surface-quiet)', marginTop: 12, lineHeight: 1.5 }}>
        Automatisch generiert · GeoStrat-Engine · Keine Anlageberatung
      </div>
    </div>
  );
}

function PortfolioWidget() {
  const [data,      setData]      = useStateW(null);
  const [loading,   setLoading]   = useStateW(true);
  const [error,     setError]     = useStateW(null);
  const [refreshing, setRefreshing] = useStateW(false);

  const load = async (refresh = false) => {
    if (refresh) setRefreshing(true); else setLoading(true);
    setError(null);
    try {
      const res = await window.RICS_API.getCombinedPortfolio(refresh);
      setData(res);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffectW(() => {
    if (!window.RICS_API) { setLoading(false); return; }
    load();
  }, []);

  const fmtAge = (iso) => {
    if (!iso) return null;
    const diff = Date.now() - new Date(iso).getTime();
    const min  = Math.floor(diff / 60000);
    if (min < 60)   return `vor ${min} Min.`;
    const h = Math.floor(min / 60);
    if (h   < 24)   return `vor ${h} Std.`;
    return `vor ${Math.floor(h / 24)} Tagen`;
  };

  const positions = data?.positions || [];

  return (
    <div className="dash-card">
      <div className="dash-card-hdr">
        <div>
          <div className="label">GeoStrat · Konsolidiertes Portfolio</div>
          {data?.dominant_theme && (
            <div style={{ fontSize: 12, color: 'var(--on-surface-dim)', marginTop: 6, lineHeight: 1.45, maxWidth: 440 }}>
              {data.dominant_theme.slice(0, 120)}{data.dominant_theme.length > 120 ? '…' : ''}
            </div>
          )}
        </div>
        <button
          onClick={() => load(true)}
          disabled={refreshing || loading}
          className="btn btn-tertiary btn-sm"
          style={{ flexShrink: 0, opacity: refreshing ? 0.5 : 1 }}
        >
          {refreshing ? '…' : '↺'}
        </button>
      </div>

      <div style={{ padding: 22 }}>

        {/* Metazeile */}
        {data && (
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--on-surface-quiet)', marginBottom: 16, display: 'flex', gap: 16 }}>
            <span>{fmtAge(data.generated_at)}</span>
            {data.cached && <span>· Aus Cache</span>}
            {positions.length > 0 && <span>· {positions.length} Positionen</span>}
          </div>
        )}

        {/* Loading */}
        {loading && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '24px 0' }}>
            <div className="spinner" />
            <div className="mono" style={{ fontSize: 11, color: 'var(--on-surface-dim)' }}>
              Portfolio wird generiert…
            </div>
          </div>
        )}

        {/* Fehler */}
        {!loading && error && (
          <div style={{ padding: '16px 0' }}>
            <div className="mono" style={{ fontSize: 11, color: '#E5B25C' }}>{error}</div>
          </div>
        )}

        {/* Leer */}
        {!loading && !error && positions.length === 0 && (
          <div style={{ padding: '16px 0' }}>
            <div className="mono" style={{ fontSize: 12, color: 'var(--on-surface-dim)' }}>
              Keine Live-Reports verfügbar. Im Admin-Panel Reports veröffentlichen.
            </div>
          </div>
        )}

        {/* Donut + Legende */}
        {!loading && positions.length > 0 && (
          <PortfolioDonut positions={positions} />
        )}

        {/* Positionstabelle */}
        {!loading && positions.length > 0 && (
          <AgentPositionList positions={positions} simId={null} />
        )}

        {/* Key Risk */}
        {!loading && data?.key_risk && (
          <div style={{
            marginTop: 18, padding: '12px 14px',
            background: 'var(--surface-low)', borderLeft: '2px solid var(--outline-variant)',
          }}>
            <div className="label" style={{ marginBottom: 6 }}>Key Risk</div>
            <div style={{ fontSize: 12, color: 'var(--on-surface-dim)', lineHeight: 1.55 }}>
              {data.key_risk.slice(0, 240)}{data.key_risk.length > 240 ? '…' : ''}
            </div>
          </div>
        )}

        {/* Disclaimer */}
        {!loading && positions.length > 0 && (
          <div className="mono" style={{ fontSize: 10, color: 'var(--on-surface-quiet)', marginTop: 14, lineHeight: 1.5 }}>
            Automatisch generiert · GeoStrat-Engine · Keine Anlageberatung
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PortfolioWidget });
