// Main app: mode toggle, state machine, live price ticker
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showSL": true,
  "showTP": true,
  "showEntry": true,
  "entryPrice": 4612,
  "slPrice": 4595,
  "tpPrice": 4645,
  "showCurrentPriceLine": true,
  "lineStyle": "dashed",
  "showLabels": true
}/*EDITMODE-END*/;

function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [mode, setMode] = useState('standard');         // 'standard' | 'genz'
  const [stdState, setStdState] = useState('session');  // 'session' | 'watching' | 'signal' | 'live'
  const [gzState, setGzState] = useState('feed');       // 'feed' | 'live' | 'share'
  const [navTab, setNavTab] = useState('home');         // home / chart / copy / journal / settings
  const [selectedSym, setSelectedSym] = useState('GOLD');
  const [livePrice, setLivePrice] = useState(4615.30);
  const [hasOpenPosition, setHasOpenPosition] = useState(false);
  const [toast, setToast] = useState(null);
  const [showShare, setShowShare] = useState(null); // { pl, entry, exit, hold }

  // Live price tick — subtle drift around 4615
  useEffect(() => {
    const id = setInterval(() => {
      setLivePrice(p => {
        const drift = (Math.random() - 0.45) * 0.6;
        let next = p + drift;
        // gentle anchor toward 4618 when position is live (so PnL stays positive-ish)
        if (stdState === 'live' || gzState === 'live') {
          next += (4620 - next) * 0.02;
        } else {
          next += (4615.30 - next) * 0.02;
        }
        return Math.round(next * 100) / 100;
      });
    }, 1100);
    return () => clearInterval(id);
  }, [stdState, gzState]);

  // Daily loss meter values
  const dailyLimit = 200;
  const baseUsed = 47;
  const dailyUsedAmt = baseUsed;
  const dailyUsedPct = Math.round((dailyUsedAmt / dailyLimit) * 100);

  const goldInstrument = { sym: 'GOLD', bid: livePrice - 0.05, ask: livePrice + 0.05, pct: 1.14, pctDir: 'up' };

  const [closedToast, setClosedToast] = useState(null);
  const handleStdPositionClose = ({ pl, entry, exit, hold, pct }) => {
    if (mode === 'genz') {
      setShowShare({ pl: 147.20, entry, exit, hold, sym: 'GOLD', dir: 'LONG', pct: 3.2 });
    } else {
      setClosedToast({ pl, entry, exit, hold, pct: pct || 0.93 });
    }
    setStdState('session');
    setGzState('feed');
    setHasOpenPosition(false);
  };

  const handleGzShare = () => {
    // Show modal share card with realistic positive close
    const exitPx = 4645.00;
    const pl = (exitPx - 4612) * 5.9; // 0.59 lots * 100 multiplier-ish for display
    setShowShare({ pl: 147.20, entry: 4612.00, exit: 4645.00, hold: '38 min', sym: 'GOLD', dir: 'LONG' });
    setGzState('feed');
  };

  const handleResetState = (newMode) => {
    if (newMode === 'standard') setStdState('session');
    if (newMode === 'genz') { setGzState('feed'); setNavTab('home'); }
  };

  // Build chart overlay from tweaks — used by both Standard and Gen Z chart screens
  const chartOverlay = {
    entry: tw.showEntry ? Number(tw.entryPrice) : null,
    sl:    tw.showSL    ? Number(tw.slPrice)    : null,
    tp:    tw.showTP    ? Number(tw.tpPrice)    : null,
  };
  const overlayStyle = {
    dashed: tw.lineStyle === 'dashed',
    solid:  tw.lineStyle === 'solid',
    showLabels: !!tw.showLabels,
    showCurrentPriceLine: !!tw.showCurrentPriceLine,
  };

  return (
    <div className="app">
      <TopBar
        mode={mode}
        setMode={setMode}
        instrument={goldInstrument}
        onResetState={handleResetState}
      />

      {mode === 'standard' && (
        <StandardMode
          stdState={stdState}
          setStdState={(s) => { setStdState(s); setClosedToast(null); }}
          selectedSym={selectedSym}
          setSelectedSym={setSelectedSym}
          livePrice={livePrice}
          onPositionClose={handleStdPositionClose}
          setHasOpenPosition={setHasOpenPosition}
          closedToast={closedToast}
          onDismissToast={() => setClosedToast(null)}
          chartOverlay={chartOverlay}
          overlayStyle={overlayStyle}
        />
      )}

      {mode === 'genz' && (
        <GenZMode
          gzState={gzState}
          setGzState={(s) => {
            setGzState(s);
            if (s === 'share') handleGzShare();
            if (s === 'live') setNavTab('chart');
          }}
          livePrice={livePrice}
          navTab={navTab}
          setNavTab={setNavTab}
          onCloseShare={() => setShowShare(null)}
          sharePayload={showShare}
          chartOverlay={chartOverlay}
          overlayStyle={overlayStyle}
        />
      )}

      {toast && <div className="toast success">✓ {toast}</div>}

      <TweaksPanel>
        <TweakSection label="Chart overlays" />
        <TweakToggle label="Entry line"      value={tw.showEntry} onChange={(v) => setTweak('showEntry', v)} />
        <TweakNumber label="Entry price"     value={tw.entryPrice} step={1} onChange={(v) => setTweak('entryPrice', v)} />
        <TweakToggle label="Stop Loss line"  value={tw.showSL} onChange={(v) => setTweak('showSL', v)} />
        <TweakNumber label="SL price"        value={tw.slPrice} step={1} onChange={(v) => setTweak('slPrice', v)} />
        <TweakToggle label="Take Profit line" value={tw.showTP} onChange={(v) => setTweak('showTP', v)} />
        <TweakNumber label="TP price"        value={tw.tpPrice} step={1} onChange={(v) => setTweak('tpPrice', v)} />

        <TweakSection label="Style" />
        <TweakRadio  label="Line style" value={tw.lineStyle} options={['dashed','solid']}
                     onChange={(v) => setTweak('lineStyle', v)} />
        <TweakToggle label="Price labels" value={tw.showLabels} onChange={(v) => setTweak('showLabels', v)} />
        <TweakToggle label="Current price line" value={tw.showCurrentPriceLine} onChange={(v) => setTweak('showCurrentPriceLine', v)} />
      </TweaksPanel>

      {showShare && (
        <div className="modal-backdrop" onClick={() => setShowShare(null)}>
          <div className="share-card" onClick={(e) => e.stopPropagation()}>
            <div className="share-head">
              <div className="share-pill">● {showShare.sym} {showShare.dir} · CLOSED ✓</div>
            </div>
            <div className="share-meta">
              <div className="share-meta-row">
                <div className="lbl">Entry</div>
                <div className="val">{showShare.entry.toFixed(2)}</div>
              </div>
              <div className="share-meta-row">
                <div className="lbl">Exit</div>
                <div className="val">{showShare.exit.toFixed(2)}</div>
              </div>
              <div className="share-meta-row">
                <div className="lbl">Hold time</div>
                <div className="val">{showShare.hold}</div>
              </div>
              <div className="share-meta-row">
                <div className="lbl">Risk used</div>
                <div className="val">1%</div>
              </div>
            </div>
            <div className="share-pl">+${showShare.pl.toFixed(2)}</div>
            <div className="share-pct">+3.2% · 1 : 2.0 R:R achieved</div>
            <div className="share-streak">
              🔥 <span style={{fontWeight:700}}>5 sessions green</span>
              <span style={{color:'var(--text-3)', marginLeft:'auto', fontSize:11}}>personal best: 8</span>
            </div>
            <div className="share-actions">
              <button className="secondary">📓 Journal</button>
              <button className="primary">📤 Share to Feed</button>
            </div>
            <button className="share-close" onClick={() => setShowShare(null)}>Close</button>
          </div>
        </div>
      )}
    </div>
  );
}

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