/* ═══════════════════════════════════════════════════════════════════
   INTEL BAR · top-strip market intelligence — live API wired
   Fear & Greed · BTC.D · Regime · Equity · Funding · UTC clock
   ═══════════════════════════════════════════════════════════════════ */

function IntelBar({ intel }) {
  /* UTC clock — only this re-renders every second */
  const [utcStr, setUtcStr] = React.useState(() => {
    const n = new Date();
    return String(n.getUTCHours()).padStart(2,'0') + ':' +
           String(n.getUTCMinutes()).padStart(2,'0') + ':' +
           String(n.getUTCSeconds()).padStart(2,'0');
  });
  React.useEffect(() => {
    const id = setInterval(() => {
      const n = new Date();
      setUtcStr(String(n.getUTCHours()).padStart(2,'0') + ':' +
                String(n.getUTCMinutes()).padStart(2,'0') + ':' +
                String(n.getUTCSeconds()).padStart(2,'0'));
    }, 1000);
    return () => clearInterval(id);
  }, []);

  /* ── All intel values computed safely at top level — NO IIFEs ── */
  const fg   = Number(intel && intel.fear_greed    != null ? intel.fear_greed    : 25) || 25;
  const btcd = Number(intel && intel.btc_dominance != null ? intel.btc_dominance : 58.2) || 58.2;
  const mr   = Number(intel && intel.macro_risk    != null ? intel.macro_risk    : 42)  || 42;
  const fr   = Number(intel && intel.funding_rate  != null ? intel.funding_rate  : 0.0042) || 0.0042;
  const eq   = (intel && intel.equity_outlook) ? String(intel.equity_outlook) : 'BULLISH';
  const regime = (intel && intel.regime) ? String(intel.regime) : 'BEARISH';
  const flipNote = (intel && intel.regime_flip_note) ? intel.regime_flip_note : 'awaiting flip conditions';

  /* Fear & Greed */
  const fgColor = fg <= 25 ? ST.red : fg <= 45 ? ST.amber : fg <= 55 ? ST.ink3 : ST.green;
  const fgLabel = fg <= 25 ? 'EXTREME FEAR' : fg <= 45 ? 'FEAR' : fg <= 55 ? 'NEUTRAL' : fg <= 75 ? 'GREED' : 'EXTREME GREED';

  /* BTC Dominance */
  const btcdStr = isNaN(btcd) ? '58.2' : btcd.toFixed(1);

  /* Regime */
  const regColor = regime === 'BULLISH' ? ST.green : regime === 'NEUTRAL' ? ST.ink3 : ST.amber;

  /* Equity */
  const eqColor = eq === 'BULLISH' ? ST.green : eq === 'BEARISH' ? ST.red : ST.ink3;

  /* Funding */
  const frSafe  = isNaN(fr) ? 0.0042 : fr;
  const frPct   = (frSafe * 100).toFixed(4);
  const frAPR   = (frSafe * 100 * 3 * 365).toFixed(1);
  const frColor = Math.abs(frSafe) < 0.002 ? ST.ink3 : frSafe > 0 ? ST.green : ST.red;
  const frLabel = Math.abs(frSafe) < 0.002 ? 'NEUTRAL' : frSafe > 0 ? 'POSITIVE' : 'NEGATIVE';

  /* Macro Risk */
  const mrSafe  = isNaN(mr) ? 42 : mr;
  const mrColor = mrSafe >= 60 ? ST.red : mrSafe >= 40 ? ST.amber : ST.green;
  const mrLabel = mrSafe >= 60 ? 'HIGH' : mrSafe >= 40 ? 'ELEVATED' : 'LOW';

  return (
    <div style={{
      display: 'flex', alignItems: 'stretch',
      borderBottom: `1px solid ${ST.border}`,
      background: `linear-gradient(180deg, ${ST.bg2} 0%, ${ST.bg} 100%)`,
      minHeight: 56, flexShrink: 0, overflow: 'hidden',
    }}>

      {/* Fear & Greed */}
      <IntelCell label="FEAR & GREED" wide>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="num" style={{ fontSize: 18, fontWeight: 600, color: fgColor, letterSpacing: '-0.02em' }}>{Math.round(fg)}</span>
          <div style={{ flex: 1, minWidth: 80 }}>
            <FearMeter value={fg} />
            <span className="mono" style={{ fontSize: 9, color: fgColor, fontWeight: 600, letterSpacing: '0.08em' }}>{fgLabel}</span>
          </div>
        </div>
      </IntelCell>

      {/* BTC Dominance */}
      <IntelCell label="BTC DOMINANCE">
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span className="num" style={{ fontSize: 18, fontWeight: 600, color: ST.ink, letterSpacing: '-0.02em' }}>{btcdStr}%</span>
          <span style={{ fontSize: 13, color: ST.amber, fontWeight: 600 }}>↑</span>
        </div>
        <span className="mono" style={{ fontSize: 9, color: ST.ink4, marginTop: 2 }}>
          alts <span style={{ color: btcd > 56 ? ST.red : ST.green }}>{btcd > 56 ? 'weakening' : 'rotating'}</span>
        </span>
      </IntelCell>

      {/* Crypto Regime */}
      <IntelCell label="CRYPTO REGIME">
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <RegimePill c={regColor}>{regime}</RegimePill>
        </div>
        <span className="mono" style={{ fontSize: 9, color: ST.ink4, marginTop: 4 }}>
          {flipNote}
        </span>
      </IntelCell>

      {/* Equity Outlook */}
      <IntelCell label="EQUITY OUTLOOK">
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <RegimePill c={eqColor}>{eq}</RegimePill>
        </div>
        <span className="mono" style={{ fontSize: 9, color: ST.ink4, marginTop: 4 }}>
          stocks/crypto correlation
        </span>
      </IntelCell>

      {/* Funding */}
      <IntelCell label="FUNDING · 8H">
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <RegimePill c={frColor}>{frLabel}</RegimePill>
          <span className="num" style={{ fontSize: 10, color: ST.ink2, fontWeight: 600 }}>{frSafe >= 0 ? '+' : ''}{frPct}%</span>
        </div>
        <span className="mono" style={{ fontSize: 9, color: ST.ink4, marginTop: 4 }}>
          APR <span className="num" style={{ color: ST.ink2 }}>{frAPR}%</span>
        </span>
      </IntelCell>

      {/* Macro Risk */}
      <IntelCell label="MACRO RISK">
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span className="num" style={{ fontSize: 18, fontWeight: 600, color: mrColor, letterSpacing: '-0.02em' }}>{Math.round(mrSafe)}</span>
          <span className="mono" style={{ fontSize: 9, color: mrColor, fontWeight: 600, letterSpacing: '0.08em' }}>{mrLabel}</span>
        </div>
        <span className="mono" style={{ fontSize: 9, color: ST.ink4, marginTop: 2 }}>
          live macro index
        </span>
      </IntelCell>

      {/* UTC clock */}
      <div style={{
        padding: '10px 18px',
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
        background: `linear-gradient(180deg, ${ST.bg} 0%, ${ST.bg2} 100%)`,
        borderLeft: `1px solid ${ST.border}`,
        marginLeft: 'auto',
        minWidth: 132,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span className="st-live-dot" />
          <span className="eyebrow">UTC · LIVE</span>
        </div>
        <span className="num" style={{
          fontSize: 18, fontWeight: 600, color: ST.amber,
          letterSpacing: '-0.01em', marginTop: 2, lineHeight: 1,
        }}>{utcStr}</span>
      </div>
    </div>
  );
}

function IntelCell({ label, children, wide }) {
  return (
    <div style={{
      padding: '8px 18px',
      borderRight: `1px solid ${ST.border}`,
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
      minWidth: wide ? 200 : 158,
      flex: wide ? 1.2 : 1,
    }}>
      <span className="eyebrow" style={{ marginBottom: 4 }}>{label}</span>
      {children}
    </div>
  );
}

function FearMeter({ value }) {
  const safeVal = Number(value) || 0;
  return (
    <div style={{
      position: 'relative', height: 5,
      background: ST.panel,
      borderRadius: 3,
      overflow: 'visible',
      marginBottom: 3,
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(90deg, ${ST.red} 0%, ${ST.amber} 50%, ${ST.green} 100%)`,
        borderRadius: 3,
        opacity: 0.35,
      }} />
      <div style={{
        position: 'absolute', left: `${Math.min(100, Math.max(0, safeVal))}%`,
        top: -2, bottom: -2,
        width: 3, background: safeVal <= 40 ? ST.red : safeVal <= 55 ? ST.amber : ST.green,
        boxShadow: `0 0 5px ${safeVal <= 40 ? ST.red : ST.amber}`,
        transform: 'translateX(-50%)',
        borderRadius: 1.5,
      }} />
    </div>
  );
}

function RegimePill({ c, children }) {
  return (
    <span className="mono" style={{
      fontSize: 10, fontWeight: 700, letterSpacing: '0.1em',
      color: c, background: c + '14',
      padding: '3px 7px', borderRadius: 3,
      border: '1px solid ' + c + '40',
    }}>{children}</span>
  );
}

window.IntelBar = IntelBar;
