// ── InfoRobot：左下角資訊助手（狐狸版） ─────────────────────────
// 2026-05-12 升級：狐狸取代機器人 SVG + 加股票操作知識輪播
// 資料來源：window.STOCK_DATA_LIVE（即時系統狀態）+ 內建股市知識陣列
// 互動：bubble 點擊跳對應頁、狐狸點擊展開面板、idle 跑步動畫 + 眨眼 + 尾巴搖

(function(){
const T = window.STOCK_TOKENS;

// ── 股票操作基本知識（會隨機混入輪播）────────────────
const STOCK_TIPS = [
  { icon: '🦊', label: '紀律 · 停損', value: '跌破 -5% 就出', hint: '別硬凹，硬凹會死人' },
  { icon: '🦊', label: '紀律 · 風報比', value: '< 1:1.5 不進場', hint: '每單位風險換 ≥1.5 報酬才值' },
  { icon: '🦊', label: '紀律 · 部位', value: '單檔 ≤ 8%', hint: '旗艦才到 8、新手控 4%' },
  { icon: '🦊', label: '紀律 · 不追高', value: '突破當下別買', hint: '回測站穩才進，省下追高被甩' },
  { icon: '🦊', label: '紀律 · 分批', value: '目標 1 出 1/3', hint: '到第一停利先鎖利、留錢給 t2' },
  { icon: '🦊', label: '紀律 · 燈號', value: '黃/紅 砍半部位', hint: '系統會自動減倉，跟著做' },
  { icon: '🦊', label: '訊號 · 跌破均線', value: '連 3 天該停損', hint: '20MA/60MA 跌破是反轉警訊' },
  { icon: '🦊', label: '籌碼 · 外資', value: '連賣 5 日要小心', hint: '主力撤退，散戶不要硬接' },
  { icon: '🦊', label: '心法 · 不貪', value: '小賺也是賺', hint: '錯失才是常態，不是每天都要中' },
  { icon: '🦊', label: '心法 · 不怕', value: '對的計畫照做', hint: '訊號到就進，不要被恐懼綁架' },
];

function InfoFox() {
  const [tick, setTick] = React.useState(0);
  const [bubbleIdx, setBubbleIdx] = React.useState(0);
  const [expanded, setExpanded] = React.useState(false);
  const [blink, setBlink] = React.useState(false);
  const [showBubble, setShowBubble] = React.useState(true);
  const [hover, setHover] = React.useState(false);

  // 每 30 秒重新計算資料快照
  React.useEffect(() => {
    const t = setInterval(() => setTick(x => x + 1), 30000);
    return () => clearInterval(t);
  }, []);

  // 系統狀態 fact + 知識 tip 混合
  const live = window.STOCK_DATA_LIVE || {};
  const facts = React.useMemo(() => {
    const systemFacts = [];

    // 1) 今日推薦數
    const picksCount = (live.picks?.picks || live.picks || []).length;
    if (picksCount > 0) {
      systemFacts.push({
        icon: '🤖', label: '今日 AI 推薦', value: `${picksCount} 檔`,
        hint: '看 AI 推薦頁 →', page: 'picks',
      });
    }
    // 2) 大盤燈號
    const regimeIndices = live.regime?.indices || [];
    const twse = regimeIndices.find(r => r.index_name === 'TWSE');
    if (twse) {
      const lvl = (twse.alert_level || 'green').toUpperCase();
      const emoji = lvl === 'GREEN' ? '🟢' : lvl === 'YELLOW' ? '🟡' : lvl === 'ORANGE' ? '🟠' : '🔴';
      const dir = twse.alert_direction === 'bull_reversal' ? '熊轉牛 ↑'
                : twse.alert_direction === 'bear_reversal' ? '牛轉熊 ↓' : '穩定';
      systemFacts.push({
        icon: emoji, label: '台股燈號', value: `${lvl} · ${dir}`,
        hint: '看盤前簡報 →', page: 'briefing',
      });
    }
    // 3) 外資籌碼
    const flow = live.flow_tw?.flow?.[0] || live.flow_tw?.[0];
    if (flow && flow.net != null) {
      const net = flow.net;
      const sign = net > 0 ? '+' : '';
      const dir = net > 0 ? '買超' : '賣超';
      systemFacts.push({
        icon: net > 0 ? '💹' : '📉',
        label: '外資' + dir,
        value: `${sign}${net.toFixed(1)} 億`,
        hint: '看籌碼面 →', page: 'chips',
      });
    }
    // 4) 持股健診警告
    const dangerHoldings = (live.portfolio_health?.items || []).filter(h =>
      (h.alert_label || '') === '危險' || (h.alert_label || '') === '警告'
    );
    if (dangerHoldings.length > 0) {
      systemFacts.push({
        icon: '⚠️', label: '持股警示',
        value: `${dangerHoldings.length} 檔需注意`,
        hint: '看自選股健診 →', page: 'watchlist',
      });
    }
    // 5) 推薦浮盈
    const hist = live.history?.recommendations || [];
    const pending = hist.filter(r => !['win', 'loss', 'neutral'].includes(r.backtest?.result));
    if (pending.length >= 3) {
      const quotes = live.quotes || {};
      const ups = pending.filter(r => {
        const q = quotes[r.code];
        return q && r.entry_price && q.price > r.entry_price;
      }).length;
      systemFacts.push({
        icon: '📊', label: '推薦追蹤',
        value: `${ups}/${pending.length} 檔上漲`,
        hint: '看歷史回顧 →', page: 'picks',
      });
    }

    // 混合：每 2 個系統 fact 後插一個知識 tip
    const mixed = [];
    let tipPicked = new Set();
    const pickTip = () => {
      // 隨機選沒選過的
      const avail = STOCK_TIPS.filter((_, i) => !tipPicked.has(i));
      const pool = avail.length > 0 ? avail : STOCK_TIPS;
      const t = pool[Math.floor(Math.random() * pool.length)];
      tipPicked.add(STOCK_TIPS.indexOf(t));
      return t;
    };
    systemFacts.forEach((sf, i) => {
      mixed.push(sf);
      if ((i + 1) % 2 === 0) mixed.push(pickTip());
    });
    if (mixed.length === 0) {
      // 沒系統 fact → 只跑知識
      for (let i = 0; i < 4; i++) mixed.push(pickTip());
    }
    return mixed;
  }, [tick, live.picks, live.regime, live.flow_tw, live.portfolio_health, live.history, live.quotes]);

  // bubble 輪播：每 7 秒換下一個（先 fade out → 換 → fade in）
  React.useEffect(() => {
    if (facts.length <= 1) return;
    const t = setInterval(() => {
      setShowBubble(false);
      setTimeout(() => {
        setBubbleIdx(i => (i + 1) % facts.length);
        setShowBubble(true);
      }, 240);
    }, 7000);
    return () => clearInterval(t);
  }, [facts.length]);

  // 眨眼動畫：每 3-5 秒隨機 blink
  React.useEffect(() => {
    let alive = true;
    const blinkLoop = () => {
      if (!alive) return;
      setBlink(true);
      setTimeout(() => {
        if (!alive) return;
        setBlink(false);
        setTimeout(blinkLoop, 3000 + Math.random() * 2500);
      }, 130);
    };
    const start = setTimeout(blinkLoop, 1500);
    return () => { alive = false; clearTimeout(start); };
  }, []);

  const cur = facts[bubbleIdx] || facts[0];
  const handleBubbleClick = () => {
    if (cur?.page && window.__setPage) {
      window.__setPage(cur.page);
    }
  };
  const handleFoxClick = () => {
    setExpanded(e => !e);
  };

  return (
    <div className="info-robot" style={{
      padding: '14px 14px 18px',
      position: 'relative',
      borderTop: '1px solid var(--line)',
    }}>
      {/* Speech bubble */}
      {showBubble && cur && (
        <div className="info-robot-bubble" style={{
          background: 'var(--bg-2)',
          border: '1px solid var(--line)',
          borderRadius: 12,
          padding: '9px 11px',
          fontSize: 11,
          lineHeight: 1.5,
          marginBottom: 10,
          position: 'relative',
          color: 'var(--fg-1)',
          boxShadow: '0 4px 12px rgba(15,20,32,.06), 0 1px 3px rgba(15,20,32,.04)',
          cursor: cur.page ? 'pointer' : 'default',
          transition: 'transform .2s ease',
        }}
        onMouseEnter={cur.page ? e => e.currentTarget.style.transform = 'translateY(-1px)' : undefined}
        onMouseLeave={cur.page ? e => e.currentTarget.style.transform = '' : undefined}
        onClick={cur.page ? handleBubbleClick : undefined}>
          <div style={{
            fontSize: 9, color: 'var(--fg-3)', letterSpacing: '.06em',
            textTransform: 'uppercase', marginBottom: 3, display: 'flex', alignItems: 'center', gap: 4,
          }}>
            <span style={{ fontSize: 11 }}>{cur.icon}</span>
            {cur.label}
          </div>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-0)', letterSpacing: '.01em' }}>
            {cur.value}
          </div>
          {cur.hint && (
            <div style={{
              fontSize: 9.5,
              color: cur.page ? 'var(--accent)' : 'var(--fg-3)',
              marginTop: 3, fontStyle: cur.page ? 'normal' : 'italic',
            }}>
              {cur.hint}
            </div>
          )}
          {/* 三角尖角指狐狸 */}
          <div style={{
            position: 'absolute', bottom: -6, left: 30,
            width: 0, height: 0,
            borderLeft: '6px solid transparent',
            borderRight: '6px solid transparent',
            borderTop: '6px solid var(--bg-2)',
          }}></div>
          <div style={{
            position: 'absolute', bottom: -7, left: 29,
            width: 0, height: 0,
            borderLeft: '7px solid transparent',
            borderRight: '7px solid transparent',
            borderTop: '7px solid var(--line)',
            zIndex: -1,
          }}></div>
        </div>
      )}

      {/* 狐狸 SVG */}
      <div
        onClick={handleFoxClick}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          display: 'flex', alignItems: 'center', gap: 10,
          cursor: 'pointer', userSelect: 'none',
        }}>
        <FoxImage hover={hover} />
        <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}>
          <div className="mono" style={{
            fontSize: 9.5, color: 'var(--fg-3)', letterSpacing: '.08em',
            textTransform: 'uppercase',
          }}>
            STOCKSENSE
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-1)', lineHeight: 1.3, marginTop: 2, fontWeight: 500 }}>
            狐狸看盤中 🦊
          </div>
        </div>
      </div>

      {/* 展開面板（點狐狸切換）*/}
      {expanded && (
        <div style={{
          marginTop: 10, padding: 10,
          background: 'var(--bg-2)', border: '1px solid var(--line)',
          borderRadius: 8, fontSize: 10.5, lineHeight: 1.6, color: 'var(--fg-2)',
          animation: 'tip-fadein-portal 200ms ease-out',
        }}>
          <div style={{ fontSize: 9, color: 'var(--fg-3)', letterSpacing: '.08em', marginBottom: 6 }}>所有狀態 + 紀律提示</div>
          {facts.map((f, i) => (
            <div key={i}
              onClick={() => f.page && window.__setPage && window.__setPage(f.page)}
              style={{
                display: 'flex', alignItems: 'center', gap: 6,
                padding: '5px 0',
                borderBottom: i === facts.length - 1 ? 'none' : '1px dashed var(--line)',
                cursor: f.page ? 'pointer' : 'default',
                transition: 'color .15s',
              }}
              onMouseEnter={e => f.page && (e.currentTarget.style.color = 'var(--accent)')}
              onMouseLeave={e => f.page && (e.currentTarget.style.color = 'var(--fg-2)')}>
              <span style={{ fontSize: 12 }}>{f.icon}</span>
              <span style={{ color: 'var(--fg-3)', minWidth: 70, fontSize: 9.5 }}>{f.label}</span>
              <span style={{ color: 'inherit', fontWeight: 500, flex: 1, fontSize: 10.5 }}>{f.value}</span>
              {f.page && <span style={{ color: 'var(--accent)', fontSize: 9 }}>→</span>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── FoxImage：用 web/fox.png 透明 PNG，加 CSS 動畫；找不到圖片時 fallback FoxSVG ──
// 2026-05-12：方案 A（照片 + CSS 動畫）
function FoxImage({ hover }) {
  const [errored, setErrored] = React.useState(false);
  if (errored) return <FoxSVG hover={hover} blink={false} />;
  // 三層 transform 才能疊加：
  // outer = hover scale（瞬時 transition）
  // middle = sway 旋轉（2.8s loop）
  // inner img = bob 上下 + squash（1.4s loop）
  return (
    <div style={{
      width: 60, height: 50, flexShrink: 0, position: 'relative',
      transition: 'transform .3s cubic-bezier(.34,1.56,.64,1)',
      transform: hover ? 'scale(1.14)' : 'scale(1)',
    }}>
      <div style={{
        width: '100%', height: '100%',
        animation: 'fox-run-sway 2.8s ease-in-out infinite',
        transformOrigin: 'bottom center',
      }}>
        <img
          src="fox.png"
          alt="fox"
          onError={() => setErrored(true)}
          style={{
            // 2026-05-12: 使用者的去背圖狐狸偏右、左邊大片空白
            // 用 object-fit: cover + object-position: right 自動把狐狸對齊到視窗右側
            // 即使使用者沒裁圖也能正確顯示
            width: '100%', height: '100%',
            objectFit: 'cover',
            objectPosition: 'right center',
            display: 'block',
            animation: 'fox-run-bob 1.4s ease-in-out infinite',
            filter: 'drop-shadow(0 3px 6px rgba(15,20,32,.18)) drop-shadow(0 1px 2px rgba(15,20,32,.12))',
            transformOrigin: 'bottom center',
          }}
        />
      </div>
      {hover && (
        <>
          <span style={{
            position: 'absolute', left: -4, bottom: 2,
            width: 4, height: 4, borderRadius: '50%',
            background: 'var(--fg-4)', opacity: .35,
            animation: 'fox-paw-fade 1.2s ease-out',
          }} />
          <span style={{
            position: 'absolute', left: -10, bottom: 0,
            width: 3, height: 3, borderRadius: '50%',
            background: 'var(--fg-4)', opacity: .25,
            animation: 'fox-paw-fade 1.2s ease-out .15s',
          }} />
        </>
      )}
    </div>
  );
}

// ── FoxSVG：原向量版（fox.png 不存在時的 fallback） ──
function FoxSVG({ hover, blink }) {
  return (
    <svg
      width="60" height="50" viewBox="0 0 60 50"
      style={{
        flexShrink: 0,
        transition: 'transform .3s cubic-bezier(.34,1.56,.64,1)',
        transform: hover ? 'scale(1.12) rotate(-3deg)' : 'scale(1)',
        overflow: 'visible',
      }}>
      <g style={{ animation: 'fox-tail 1.2s ease-in-out infinite', transformOrigin: '42px 25px' }}>
        <path d="M 42 24 Q 50 18 56 14 Q 58 19 56 24 Q 50 26 44 26 Z" fill="#e67e3a" stroke="#c46724" strokeWidth="0.6" />
        <path d="M 53 14 Q 58 14 58 18 Q 56 19 54 17 Z" fill="#fffaf0" stroke="#c46724" strokeWidth="0.4" />
      </g>
      <g style={{ animation: 'fox-bob 0.55s ease-in-out infinite alternate', transformOrigin: '28px 30px' }}>
        <g style={{ animation: 'fox-leg-back 0.55s ease-in-out infinite', transformOrigin: '36px 32px' }}>
          <path d="M 36 32 L 38 42 L 41 42 L 39 32 Z" fill="#d4691c" stroke="#a4530f" strokeWidth="0.6" />
        </g>
        <g style={{ animation: 'fox-leg-front 0.55s ease-in-out infinite reverse', transformOrigin: '20px 32px' }}>
          <path d="M 19 32 L 20 42 L 23 42 L 22 32 Z" fill="#d4691c" stroke="#a4530f" strokeWidth="0.6" />
        </g>
        <ellipse cx="28" cy="28" rx="13" ry="7" fill="#e67e3a" stroke="#c46724" strokeWidth="0.7" />
        <ellipse cx="28" cy="30" rx="9" ry="4" fill="#fffaf0" opacity=".95" />
        <g style={{ animation: 'fox-leg-back 0.55s ease-in-out infinite reverse', transformOrigin: '34px 33px' }}>
          <path d="M 34 33 L 36 43 L 39 43 L 37 33 Z" fill="#f08c46" stroke="#c46724" strokeWidth="0.6" />
        </g>
        <g style={{ animation: 'fox-leg-front 0.55s ease-in-out infinite', transformOrigin: '22px 33px' }}>
          <path d="M 21 33 L 22 43 L 25 43 L 24 33 Z" fill="#f08c46" stroke="#c46724" strokeWidth="0.6" />
        </g>
      </g>
      <g style={{ animation: 'fox-head 0.55s ease-in-out infinite alternate', transformOrigin: '13px 25px' }}>
        <path d="M 9 18 L 7 11 L 13 16 Z" fill="#e67e3a" stroke="#c46724" strokeWidth="0.5" />
        <path d="M 14 16 L 13 9 L 18 15 Z" fill="#e67e3a" stroke="#c46724" strokeWidth="0.5" />
        <path d="M 7 11 L 9 12 L 8 13.5 Z" fill="#2a1810" />
        <path d="M 13 9 L 15 11 L 14 12.5 Z" fill="#2a1810" />
        <path d="M 9.5 16 L 8.5 13 L 12 15 Z" fill="#ffd0b8" opacity=".8" />
        <path d="M 14.5 15 L 14 12 L 17 14.5 Z" fill="#ffd0b8" opacity=".8" />
        <ellipse cx="13" cy="22" rx="8" ry="7" fill="#e67e3a" stroke="#c46724" strokeWidth="0.7" />
        <path d="M 6 24 Q 8 30 13 30 Q 18 30 20 24 Q 18 27 13 27 Q 8 27 6 24 Z" fill="#fffaf0" />
        <ellipse cx="5" cy="24" rx="4" ry="3" fill="#fffaf0" stroke="#c46724" strokeWidth="0.4" />
        <ellipse cx="2.5" cy="24" rx="1.3" ry="1" fill="#2a1810" />
        <ellipse cx="10" cy="20" rx="1.6" ry={blink ? 0.2 : 1.8} fill="#2a1810" style={{ transition: 'ry .1s' }} />
        {!blink && <circle cx="10.5" cy="19.5" r="0.5" fill="#fff" />}
        <path d="M 5 26 Q 7 28 9 26" stroke="#2a1810" strokeWidth="0.5" fill="none" strokeLinecap="round" />
        <line x1="3" y1="25" x2="0" y2="25.5" stroke="#a4530f" strokeWidth="0.3" />
        <line x1="3" y1="26" x2="0" y2="27" stroke="#a4530f" strokeWidth="0.3" />
      </g>
    </svg>
  );
}

window.InfoFox = InfoFox;
// 向後相容：之前 shell.jsx 用 window.InfoRobot
window.InfoRobot = InfoFox;

})();
