// Interactive case study — "The Trust Play"
// Branching narrative: meet Charles Banks IV, watch him work, then reveal Tim Duncan.

const TOTAL_FRAMES = 7;
const SCENE_NUM = {
  scene1: 1, scene2a: 2, scene2b: 2,
  scene3a: 3, scene3b: 3,
  scene4a: 4, scene4b: 4, scene4c: 4,
  scene5: 5, scene5b: 6, scene6: 7,
};

// ----- helpers -----

const formatMoney = (n) => {
  if (n >= 1_000_000) return '$' + (n / 1_000_000).toFixed(2) + 'M';
  if (n >= 1_000)     return '$' + (n / 1_000).toFixed(2) + 'K';
  return '$' + n.toFixed(2);
};

const MoneyCounter = ({ target }) => {
  const [displayed, setDisplayed] = React.useState(target);
  const [pulse, setPulse] = React.useState(false);
  React.useEffect(() => {
    if (displayed === target) return;
    const start = displayed;
    const startTime = performance.now();
    const duration = 800;
    let raf;
    if (target > start) {
      setPulse(true);
      const t = setTimeout(() => setPulse(false), 1500);
      raf = { _t: t };
    }
    const tick = (now) => {
      const t = Math.min((now - startTime) / duration, 1);
      const eased = 1 - Math.pow(1 - t, 3);
      setDisplayed(Math.round(start + (target - start) * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
    return () => { if (raf && raf._t) clearTimeout(raf._t); };
  }, [target]);
  return (
    <div className={`ic-money-counter ${pulse ? 'pulse' : ''}`}>
      <div className="ic-hud-label">Money at risk</div>
      <div className="ic-money-value">{formatMoney(displayed)}</div>
    </div>
  );
};

const ScoreTracker = ({ flags }) => (
  <div className="ic-score-tracker">
    <div className="ic-hud-label">Red flags spotted</div>
    <div className="ic-score-dots">
      {flags.map((f, i) => (
        <span key={i} className={`ic-score-dot ${f || ''}`} />
      ))}
    </div>
  </div>
);

// ----- shared scene UI -----

const Stamp2 = ({ kind, label, children }) => (
  <div className={`ic-stamp ${kind}`}>
    <div className="ic-stamp-label">{label}</div>
    <p>{children}</p>
  </div>
);

const PeerStat = ({ number, text }) => (
  <div className="ic-peer-stat">
    <div className="ic-peer-eyebrow">★ FILE INTAKE · PEER DATA ★</div>
    <div className="ic-peer-number">{number}</div>
    <div className="ic-peer-text">{text}</div>
  </div>
);

const Question = ({ text, children }) => (
  <div className="ic-question-box">
    <div className="ic-question">{text}</div>
    {children}
  </div>
);

const Choices = ({ items, choose }) => (
  <div className="ic-choices">
    {items.map(({ letter, text, to, result, qNum, money }) => (
      <button key={letter} className="ic-choice" onClick={() => choose(to, result, qNum, money || 0)}>
        <span className="ic-choice-letter">{letter}</span>
        <span className="ic-choice-text">{text}</span>
      </button>
    ))}
  </div>
);

// ----- scenes -----

const Scene1 = ({ choose }) => (
  <>
    <p className="ic-narrative">
      You're <strong>21 years old</strong>. You just got drafted in the first round.
      Your rookie deal is <span className="gold">$10.00M</span> over four years.
      You grew up in a household where the biggest money conversation was the cable bill.
      You've never managed real money in your life.
    </p>
    <p className="ic-narrative">
      A few weeks after the draft, a teammate introduces you to a friend of his.
      <strong> Meet <span className="red">Charles Banks IV</span></strong> — Atlanta wealth
      manager, tailored suit, crisp handshake, smile that lands easy. He's already managing
      money for a handful of pros — names you recognize. They all swear by him.
      <em> "He's family,"</em> one of them says. Charles tells you he'd love to look after
      you the same way.
    </p>
    <Question text="What do you do with your money?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Hire him. He's vouched for. He's basically family already.", to: 'scene2a', result: 'danger', qNum: 1, money: 2_000_000 },
        { letter: 'B', text: "Hire him — but insist on independent verification of every investment he recommends.", to: 'scene2b', result: 'safe', qNum: 1 },
      ]} />
    </Question>
  </>
);

const Scene2a = ({ choose }) => (
  <>
    <Stamp2 kind="danger" label="WHAT THE PLAYER DID">
      The real player chose this exact path. He hired Charles, trusted him completely, and
      handed him broad discretion. For the next several years, Charles handled everything —
      Christmas cards, birthday calls, sat at the wedding rehearsal dinner. The player
      barely thought about money. Charles thought about it constantly.
    </Stamp2>
    <PeerStat number="78%" text="of athletes who take this case study make the same choice you just did." />
    <p className="ic-narrative">
      Five years in, <strong>Charles</strong> calls you about what he's pitching as
      <em> "a killer opportunity."</em> A <strong>private sports merchandise venture</strong>.
      Pre-IPO. Numbers on paper look strong. He recommends you put in
      <span className="gold"> $2.00M</span>. He'll handle the paperwork.
      "Just sign here, here, and here."
    </p>
    <Question text="Do you invest?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Yes. Charles hasn't steered you wrong yet. You trust him.", to: 'scene3a', result: 'danger', qNum: 2, money: 5_000_000 },
        { letter: 'B', text: "Maybe — first you want to see the company's actual financials and know who else is invested.", to: 'scene3b', result: 'safe', qNum: 2 },
      ]} />
    </Question>
  </>
);

const Scene2b = ({ choose }) => (
  <>
    <Stamp2 kind="safe" label="SMART CALL">
      You're already ahead of where the real player was. Independent verification is
      the single most important safeguard an athlete can have. The challenge: most
      athletes don't know what to verify or how to do it. <strong>Charles is counting on that.</strong>
    </Stamp2>
    <PeerStat number="22%" text="of athletes spot this red flag on the very first question. The other 78% don't." />
    <p className="ic-narrative">
      A few months later, <strong>Charles</strong> brings you a deal — a private sports
      merchandise company. Glossy prospectus. Slick projections. "Other clients are already
      in," he says. "Best thing I've put on the table all year."
    </p>
    <Question text="What do you check first?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Bank statements & accounting records — not just projections.", to: 'scene3b', result: 'safe', qNum: 2 },
        { letter: 'B', text: "The prospectus looks polished enough. You trust Charles's judgment and invest.", to: 'scene3a', result: 'danger', qNum: 2, money: 5_000_000 },
      ]} />
    </Question>
  </>
);

const Scene3a = ({ choose }) => (
  <>
    <Stamp2 kind="danger" label="THIS IS WHERE THE FRAUD DEEPENS">
      Here's what you don't know: <strong className="red">Charles owns a piece of this company.</strong>
      He's collecting a hidden commission on your investment. The terms he showed you on
      paper aren't the real terms of the deal. He's playing both sides.
    </Stamp2>
    <PeerStat number="65%" text="of athletes miss this red flag — they trust the track record. By the time it surfaces, the damage is done." />
    <p className="ic-narrative">
      Over the next several years, <strong>Charles</strong> brings you more deals like this — a hotel,
      a beauty company, a winery. He calls each one a slam dunk. By now you call him <strong>Chuck</strong>.
      Your kids call him uncle. You have <span className="gold">$20.00M</span> spread
      across his "private ventures." You've never seen those companies' bank statements.
      You've never seen their books. You see only what Chuck shows you.
    </p>
    <Question text="Something feels off. What do you do?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Nothing. Chuck has managed your money for over a decade. You don't want to insult him.", to: 'scene4a', result: 'danger', qNum: 3, money: 20_000_000 },
        { letter: 'B', text: "Hire an independent forensic accountant to review everything.", to: 'scene4b', result: 'safe', qNum: 3 },
      ]} />
    </Question>
  </>
);

const Scene3b = ({ choose }) => (
  <>
    <Stamp2 kind="safe" label="RIGHT INSTINCT">
      If you can see a company's actual banking and accounting data — the real
      operational data, not summaries Charles drafts himself — you can verify whether
      the business is what he says it is.
    </Stamp2>
    <p className="ic-narrative">
      The problem: <strong>most athletes can't get that data</strong>. The company's not
      handing over their bank statements. <strong>Charles</strong> controls the flow of
      information. The real player in this case never saw the books. <strong>Charles
      controlled everything for nearly two decades.</strong> By the time anyone looked,
      <span className="gold"> $20.00M</span> had been steered into ventures where he held
      <span className="red"> undisclosed ownership and pulled hidden commissions</span>.
    </p>
    <Question text="How would you catch this?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Hire a forensic accountant once you suspect a problem.", to: 'scene4b', result: 'safe', qNum: 3 },
        { letter: 'B', text: "Continuous, automated monitoring on the company's financials from day one.", to: 'scene4c', result: 'safe', qNum: 3 },
      ]} />
    </Question>
  </>
);

const Scene4a = ({ choose }) => (
  <>
    <Stamp2 kind="danger" label="THIS IS EXACTLY WHAT HAPPENED">
      The real player trusted <strong>Chuck</strong> for nearly two decades. Never asked to
      see the books. The fraud surfaced only during a <strong className="red">divorce
      proceeding in 2013</strong> — when divorce lawyers reviewing the family's assets
      noticed millions were unaccounted for.
    </Stamp2>
    <PeerStat number="41%" text="of athletes choose to do nothing here. Loyalty overrides instinct. Charles is counting on that too." />
    <p className="ic-narrative">
      Think about that. The only reason the fraud surfaced was a
      <strong> completely unrelated life event</strong>. Not an audit. Not a financial
      review. A divorce. <strong>Without it, Chuck might still be running the scheme today.</strong>
    </p>
    <Question text="Could this have been prevented?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Show me what continuous monitoring would have caught.", to: 'scene5', result: 'safe', qNum: 4 },
      ]} />
    </Question>
  </>
);

const Scene4b = ({ choose }) => (
  <>
    <Stamp2 kind="safe" label="BETTER LATE THAN NEVER">
      A forensic accountant can find the fraud — but only after the damage is done.
      Rearview mirror. By the time anyone looked,
      <span className="gold"> $20.00M</span> had already moved into Chuck's ventures
      over nearly two decades.
    </Stamp2>
    <p className="ic-narrative">
      The real question isn't whether you can find fraud after it happens. It's whether
      you can <strong>see it happening in real time</strong> — before your money disappears
      into a company Chuck secretly owns.
    </p>
    <Question text="What would real-time monitoring have looked like?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Show me.", to: 'scene5', result: 'safe', qNum: 4 },
      ]} />
    </Question>
  </>
);

const Scene4c = ({ choose }) => (
  <>
    <Stamp2 kind="safe" label="THIS IS THE ANSWER">
      Continuous monitoring means you don't have to trust anyone's word about what's
      happening inside a company. You see the actual banking, accounting, and payroll
      data in real time. If money moves where it shouldn't, you know
      <strong> immediately</strong> — not years later during a divorce.
    </Stamp2>
    <p className="ic-narrative">
      That's exactly what didn't exist when this player was defrauded by Charles.
      <strong> It exists now.</strong>
    </p>
    <Question text="Ready to see who this really happened to?">
      <Choices choose={choose} items={[
        { letter: 'A', text: "Show me the real case.", to: 'scene5', result: 'safe', qNum: 4 },
      ]} />
    </Question>
  </>
);

const FinalScore = ({ score }) => {
  let comparison;
  if (score >= 4) comparison = (<>You spotted every red flag. <strong>Most people catch 1 or 2.</strong> You would have protected your money.</>);
  else if (score >= 3) comparison = (<>Strong instincts. <strong>You caught more than most.</strong> But even one missed red flag can cost millions.</>);
  else if (score >= 2) comparison = (<>You're about average. <strong>Most people score 2 of 4. Tim Duncan scored 0.</strong></>);
  else                 comparison = (<>You made the same calls Tim Duncan made. <strong>That path cost him $20.00M.</strong></>);
  return (
    <div className="ic-final-score">
      <div className="ic-final-score-eyebrow">★ YOUR SCORE ★</div>
      <div className="ic-final-score-number">{score}/4</div>
      <div className="ic-final-score-sub">RED FLAGS SPOTTED</div>
      <div className="ic-final-score-cmp">{comparison}</div>
    </div>
  );
};

const Scene5 = ({ choose, score }) => (
  <>
    <div className="ic-reveal">
      <div className="ic-reveal-eyebrow">★ THE REAL CASE ★</div>
      <h2 className="ic-reveal-name">TIM<br />DUNCAN</h2>
      <div className="ic-reveal-amount">$20.00M LOST</div>
      <div className="ic-reveal-sub">5× NBA Champion · Greatest Power Forward in History</div>
    </div>
    <FinalScore score={score} />
    <p className="ic-narrative">
      Tim Duncan earned approximately <span className="gold">$242.00M</span> in salary
      over 19 seasons with the San Antonio Spurs. Across pro sports, he was known as the
      athlete <strong>least likely to make a financial mistake</strong>. He hired
      <strong> Charles Banks IV</strong> — Atlanta wealth manager, polished, well-connected —
      when Duncan was a 21-year-old rookie in 1997. Banks managed Duncan's money for
      nearly two decades.
    </p>
    <ol className="ic-timeline">
      <li><span className="yr">1997</span><span className="tx">Banks begins managing Duncan's finances. Duncan is 21.</span></li>
      <li><span className="yr">1997 — 2013</span><span className="tx">Banks steers ~$20.00M into private ventures (sports merchandise, hotels, beauty products, wineries) where he holds undisclosed ownership stakes and collects hidden commissions.</span></li>
      <li><span className="yr">2013</span><span className="tx">Fraud surfaces during Duncan's divorce. Lawyers reviewing family finances discover millions are unaccounted for.</span></li>
      <li><span className="yr">SEP 2016</span><span className="tx">Banks indicted on federal wire fraud charges.</span></li>
      <li><span className="yr">APR 2017</span><span className="tx">Banks pleads guilty.</span></li>
      <li><span className="yr">JUN 2017</span><span className="tx">U.S. District Judge Fred Biery sentences Banks to 4 years in federal prison.</span></li>
    </ol>
    <button className="ic-continue" onClick={() => choose('scene5b', null, null, 0)}>
      WHAT IF HE'D JUST BOUGHT THE S&amp;P? <span>→</span>
    </button>
  </>
);

const Scene5b = ({ choose }) => {
  const TARGET = 172_000_000;
  const [displayed, setDisplayed] = React.useState(0);
  React.useEffect(() => {
    const startTime = performance.now();
    const duration = 1600;
    let frame;
    const tick = (now) => {
      const t = Math.min((now - startTime) / duration, 1);
      const eased = 1 - Math.pow(1 - t, 3);
      setDisplayed(Math.round(TARGET * eased));
      if (t < 1) frame = requestAnimationFrame(tick);
    };
    frame = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frame);
  }, []);
  const fmt = (n) => '$' + (n / 1_000_000).toFixed(2) + 'M';
  return (
    <>
      <div className="ic-altline">
        <div className="ic-altline-eyebrow">★ THE ALTERNATE TIMELINE ★</div>
        <h2 className="ic-altline-title">PLAN B:<br />BORING<br />WORKED.</h2>
        <div className="ic-altline-sub">Same $20.00M. No private ventures. Just the index.</div>
        <div className="ic-altline-number">{fmt(displayed)}</div>
        <div className="ic-altline-caption">
          What that money would be worth today if Charles had just bought the S&amp;P 500.
        </div>
      </div>
      <p className="ic-narrative">
        $20.00M deposited evenly from <strong>1997 through 2013</strong>, held to today in an
        S&amp;P 500 total-return index (~<strong>10% CAGR</strong> with dividends
        reinvested), compounds to roughly <span className="gold">$172.00M</span>.
      </p>
      <p className="ic-narrative">
        Which means <strong>Chuck didn't just steal $20.00M</strong>. He stole the
        <span className="red"> $152.00M of growth that would have come with it</span>.
        Twenty years of compounding, gone — to fund his hotel, his beauty company, his winery.
      </p>
      <button className="ic-continue" onClick={() => choose('scene6', null, null, 0)}>
        WHAT WOULD MONITORING HAVE CAUGHT? <span>→</span>
      </button>
    </>
  );
};

const Scene6 = () => (
  <>
    <div className="ic-monitoring">
      <div className="ic-monitoring-title">WHAT CONTINUOUS MONITORING WOULD HAVE CAUGHT</div>
      <p>
        If the companies Banks invested Duncan's money into had been connected to a continuous
        monitoring platform — with live access to banking, accounting, and payroll data —
        the following would have been flagged immediately:
      </p>
      <ul>
        <li><strong>Undisclosed related-party transactions</strong> — money flowing between investment companies and entities Banks personally controlled would have appeared in the banking data in real time.</li>
        <li><strong>Hidden fee structures</strong> — commissions Banks was collecting would have shown up as outflows that didn't match the terms Duncan was given.</li>
        <li><strong>Fabricated deal terms</strong> — discrepancies between what Banks said the deal looked like and what the actual accounting records showed would have been visible from day one.</li>
      </ul>
      <p>
        Duncan wouldn't have needed a divorce to find the fraud. He'd have known the moment
        the first dollar moved somewhere it shouldn't have.
      </p>
    </div>

    <p className="ic-narrative ic-closer">
      <strong>Tim Duncan earned $242.00M and lost $20.00M because no one was watching the books.</strong>
      <br /><br />
      NHLAA Athlete Awareness makes sure someone is always watching.
    </p>

    <div className="ic-cta-box">
      <h3>ACTIVATE YOUR NHLAA<br />ATHLETE AWARENESS</h3>
      <p>
        Any company you're invested in — or considering — submit it for review and
        we'll have continuous monitoring live within 24 hours.
      </p>
      <ActivationForm source="trust-play" />
    </div>

    <div className="ic-source">
      Case sourced from the <a href="https://pcfi.org" target="_blank" rel="noopener noreferrer">Private Company Fraud Institute (PCFI)</a><br />
      Powered by <a href="https://oware.com" target="_blank" rel="noopener noreferrer">Athlete Awareness (Oware™)</a>
    </div>
  </>
);

// ----- root -----

const InteractiveCase = ({ onBack }) => {
  const [scene, setScene] = React.useState('scene1');
  const [score, setScore] = React.useState(0);
  const [moneyAtRisk, setMoneyAtRisk] = React.useState(0);
  const [flags, setFlags] = React.useState([null, null, null, null]);
  const [showHud, setShowHud] = React.useState(false);

  const choose = (nextScene, result, qNum, moneyAdd) => {
    if (qNum && result) {
      setShowHud(true);
      setFlags(prev => {
        const next = [...prev];
        if (!next[qNum - 1]) next[qNum - 1] = result;
        return next;
      });
      if (result === 'safe' && !flags[qNum - 1]) setScore(s => s + 1);
    }
    if (moneyAdd > 0) setMoneyAtRisk(m => m + moneyAdd);
    setScene(nextScene);
    window.scrollTo({ top: 0, behavior: 'auto' });
  };

  const num = SCENE_NUM[scene] || 1;

  const sceneEls = {
    scene1: <Scene1 choose={choose} />,
    scene2a: <Scene2a choose={choose} />,
    scene2b: <Scene2b choose={choose} />,
    scene3a: <Scene3a choose={choose} />,
    scene3b: <Scene3b choose={choose} />,
    scene4a: <Scene4a choose={choose} />,
    scene4b: <Scene4b choose={choose} />,
    scene4c: <Scene4c choose={choose} />,
    scene5: <Scene5 choose={choose} score={score} />,
    scene5b: <Scene5b choose={choose} />,
    scene6: <Scene6 />,
  };

  return (
    <div className="page active interactive-case">
      <Nav onBack={onBack} meta={`THE TRUST PLAY · FRAME ${String(num).padStart(2,'0')} / 0${TOTAL_FRAMES}`} />
      <div className="ic-progress" style={{ width: `${(num / TOTAL_FRAMES) * 100}%` }} />

      {showHud && (
        <>
          <ScoreTracker flags={flags} />
          <MoneyCounter target={moneyAtRisk} />
        </>
      )}

      <section className="ic-section paper-tex">
        <header className="ic-header">
          <div className="ic-eyebrow">★ NHLAA ATHLETE AWARENESS · INTERACTIVE CASE ★</div>
          <h1 className="ic-title">THE TRUST PLAY</h1>
          <p className="ic-subtitle">A real case. Real money lost. Your decisions.</p>
        </header>
        <div className="ic-frame-label">FRAME {String(num).padStart(2,'0')} / 0{TOTAL_FRAMES}</div>
        <div key={scene} className="ic-scene">
          {sceneEls[scene]}
        </div>
      </section>
    </div>
  );
};

Object.assign(window, {
  InteractiveCase,
  // Shared HUD + stamp helpers (reused by case-study-oil.jsx)
  Stamp2, Choices, Question, PeerStat,
  ScoreTracker, MoneyCounter,
  formatMoney,
});
