import { useEffect, useRef } from 'react'
import anime from 'animejs'

// Translate technical jargon into plain English
function translate(flag) {
  const rules = [
    ['Weak trend (ADX', "The price is drifting sideways — there's no clear direction yet"],
    ['Volume below average', "Not many shares are changing hands — big investors may not be interested"],
    ['High P/E', "This stock might be expensive compared to what the company actually earns"],
    ['Weak overall signal', "The signals are almost evenly split — no clear direction right now"],
    ['ML model undecided', "Our AI model is nearly torn between buy and hold — it's not very decisive"],
    ['ML confidence low', "Our AI model isn't very confident about this one"],
    ['consider retraining', "The AI model hasn't been updated with very recent data — take ML signals with a grain of salt"],
    ['Prophet forecasts', flag], // keep the actual % number
  ]

  for (const [keyword, replacement] of rules) {
    if (flag.includes(keyword)) return replacement
  }
  return flag
}

export default function RiskFlags({ flags }) {
  const listRef = useRef(null)

  useEffect(() => {
    if (!listRef.current) return
    anime({
      targets: listRef.current.querySelectorAll('.risk-flag'),
      translateX: [28, 0],
      opacity: [0, 1],
      delay: anime.stagger(110, { start: 200 }),
      easing: 'easeOutExpo',
      duration: 550,
    })
  }, [flags])

  if (!flags?.length) return null

  return (
    <div className="card risk-section">
      <h3>⚠️ Things to Watch Out For</h3>
      <div ref={listRef} className="risk-flags-list">
        {flags.map((flag, i) => (
          <div key={i} className="risk-flag" style={{ opacity: 0 }}>
            <span className="risk-icon">⚡</span>
            <p>{translate(flag)}</p>
          </div>
        ))}
      </div>
      <p className="risk-disclaimer">
        These are warning signals, not guarantees. Always do your own research
        before investing any money.
      </p>
    </div>
  )
}
