// Root app — Swing + Position Trader mockup
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

const TWEAK_DEFAULTS = {
  entryPrice: 2632,
  slPrice:    2590,
  tpPrice:    2720,
};

function useLivePrice(active) {
  const [price, setPrice] = useStateA(2641.30);
  const rafRef = useRefA(null);
  const baseRef = useRefA(active ? 2645 : 2641.30);

  useEffectA(() => {
    baseRef.current = active ? 2645 : 2641.30;
    setPrice(baseRef.current);
  }, [active]);

  useEffectA(() => {
    let t;
    function tick() {
      setPrice(p => {
        const drift = (baseRef.current - p) * 0.04;
        const noise = (Math.random() - 0.5) * 0.18;
        return Math.round((p + drift + noise) * 100) / 100;
      });
      t = setTimeout(tick, 600 + Math.random() * 400);
    }
    t = setTimeout(tick, 800);
    return () => clearTimeout(t);
  }, []);

  return price;
}

function useInstruments() {
  const [instruments, setInstruments] = useStateA(
    INSTRUMENTS.map(i => ({ ...i }))
  );
  useEffectA(() => {
    const id = setInterval(() => {
      setInstruments(prev => prev.map(inst => {
        const noise = (Math.random() - 0.499) * inst.ask * 0.0003;
        const newAsk = Math.round((inst.ask + noise) * 1e5) / 1e5;
        const pct = ((newAsk - inst.close) / inst.close) * 100;
        return { ...inst, ask: newAsk, pct, pctDir: pct >= 0 ? 'up' : 'down' };
      }));
    }, 1200);
    return () => clearInterval(id);
  }, []);
  return instruments;
}

function App() {
  const [mode, setMode] = useStateA('standard');
  const [stdState, setStdState] = useStateA('watchlist');
  const [gzState, setGzState] = useStateA('feed');
  const [tweaks, setTweaks] = useStateA(TWEAK_DEFAULTS);
  const [showTweaks, setShowTweaks] = useStateA(false);
  const [closedPL, setClosedPL] = useStateA(null);
  const [sharePayload, setSharePayload] = useStateA(null);
  const [showShare, setShowShare] = useStateA(false);

  const isLive = (mode === 'standard' && stdState === 'live') ||
                 (mode === 'genz' && gzState === 'live');
  const livePrice = useLivePrice(isLive);
  const instruments = useInstruments();

  function handleResetState(newMode) {
    if (newMode === 'standard') setStdState('watchlist');
    else setGzState('feed');
    setClosedPL(null);
    setSharePayload(null);
    setShowShare(false);
  }

  function handleStdPositionClose(pl) {
    setClosedPL(pl);
    setStdState('journal');
  }

  function handleGzPositionClose(pl) {
    const payload = {
      thesis: 'DXY Weakness',
      thesisQuote: 'Called it. DXY weakness played out exactly as I expected. US10Y fell from 4.48% to 4.31% over 18 days.',
      entry: tweaks.entryPrice,
      exit: livePrice,
      held: '18 days',
      pl: pl,
      plPct: (((livePrice - tweaks.entryPrice) / tweaks.entryPrice) * 100).toFixed(2),
    };
    setSharePayload(payload);
    setShowShare(true);
    setGzState('share');
  }

  // sync instruments into INSTRUMENTS array for child components
  const goldInst = instruments.find(i => i.sym === 'GOLD');
  const liveGoldPrice = isLive ? livePrice : (goldInst ? goldInst.ask : 2641.30);

  return (
    <div className="app-shell">
      <TopBar
        mode={mode}
        setMode={setMode}
        instruments={instruments}
        onResetState={handleResetState}
      />
      <TweaksPanel
        open={showTweaks}
        onClose={() => setShowTweaks(false)}
        tweaks={tweaks}
        setTweaks={setTweaks}
        defaults={TWEAK_DEFAULTS}
      />

      {mode === 'standard' ? (
        <SwingStandardMode
          stdState={stdState}
          setStdState={setStdState}
          tweaks={tweaks}
          livePrice={liveGoldPrice}
          instruments={instruments}
          closedPL={closedPL}
          onPositionClose={handleStdPositionClose}
          onOpenTweaks={() => setShowTweaks(true)}
        />
      ) : (
        <SwingGenZMode
          gzState={gzState}
          setGzState={setGzState}
          tweaks={tweaks}
          livePrice={liveGoldPrice}
          sharePayload={sharePayload}
          showShare={showShare}
          onPositionClose={handleGzPositionClose}
          onCloseShare={() => { setShowShare(false); setGzState('live'); }}
        />
      )}

      {/* Tweaks trigger */}
      <button
        onClick={() => setShowTweaks(v => !v)}
        style={{
          position: 'fixed', bottom: 16, right: 16,
          background: 'var(--accent)', color: '#fff',
          border: 'none', borderRadius: 8, padding: '8px 14px',
          fontSize: 12, cursor: 'pointer', zIndex: 200,
          fontFamily: 'inherit',
        }}
      >
        ⚙ Tweaks
      </button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
