/* global React, Screen, AreaLine, Bars */
/* ProTradeJournal — Features screen graphics (part 2) */

const P = window.GFX_PAL;

// horizontal labelled bars
function HBars({ rows, max }) {
  const m = max || Math.max(...rows.map((r) => Math.abs(r.v))) || 1;
  return (
    <div style={{ display: 'grid', gap: 10 }}>
      {rows.map((r, i) => (
        <div key={i}>
          <div className="g-row" style={{ justifyContent: 'space-between', marginBottom: 5 }}>
            <span style={{ fontSize: 12, color: P.ink2, fontWeight: 600 }}>{r.l}</span>
            <span className="g-num" style={{ fontSize: 12, fontWeight: 700, color: r.v >= 0 ? P.green : P.red }}>{r.t}</span>
          </div>
          <div style={{ height: 7, borderRadius: 5, background: P.lineSoft, overflow: 'hidden' }}>
            <div style={{ width: `${(Math.abs(r.v) / m) * 100}%`, height: '100%', borderRadius: 5, background: r.c || (r.v >= 0 ? P.green : P.red) }} />
          </div>
        </div>))}
    </div>);
}

// ===== 2.3a MFE & MAE =====
function GfxMFEMAE() {
  const trades = [
    { mae: 14, cap: 62, mfe: 80 },
    { mae: 8, cap: 40, mfe: 74 },
    { mae: 22, cap: 30, mfe: 55 },
    { mae: 10, cap: 70, mfe: 78 },
  ];
  const W = 320, rowH = 26, mid = 60;
  return (
    <Screen label="MFE / MAE analysis">
      <div className="screen-pad">
        <div className="g-row" style={{ gap: 16, marginBottom: 10 }}>
          <span style={{ fontSize: 10.5, fontWeight: 700, color: P.red }}>● MAE (heat)</span>
          <span style={{ fontSize: 10.5, fontWeight: 700, color: P.ink2 }}>● Captured</span>
          <span style={{ fontSize: 10.5, fontWeight: 700, color: P.green }}>● MFE (potential)</span>
        </div>
        <svg viewBox={`0 0 ${W} ${trades.length * rowH + 14}`} style={{ width: '100%', height: trades.length * rowH + 14, display: 'block' }}>
          <line x1={mid} y1="2" x2={mid} y2={trades.length * rowH + 4} stroke={P.line} strokeWidth="1.5" strokeDasharray="3 4" />
          {trades.map((t, i) => {
            const y = i * rowH + 8; const sc = 2.4;
            return (
              <g key={i}>
                <rect x={mid - t.mae * sc} y={y} width={t.mae * sc} height="11" rx="3" fill={P.redDim} stroke={P.red} strokeWidth="0.8" />
                <rect x={mid} y={y} width={t.mfe * sc} height="11" rx="3" fill={P.greenDim} stroke={P.green} strokeWidth="0.8" />
                <rect x={mid} y={y} width={t.cap * sc} height="11" rx="3" fill={P.green} opacity="0.85" />
              </g>);
          })}
        </svg>
        <div style={{ fontSize: 11, color: P.ink3, marginTop: 4 }}>Avg captured <b style={{ color: P.ink, fontFamily: 'var(--mono)' }}>58%</b> of max favourable move</div>
      </div>
    </Screen>);
}

// ===== 2.3b AI analysis =====
function GfxAIAnalysis() {
  return (
    <Screen label="AI analysis">
      <div className="screen-pad">
        <div className="g-row" style={{ gap: 9, marginBottom: 12 }}>
          <span style={{ width: 28, height: 28, borderRadius: 8, background: P.greenDim, color: P.green, display: 'grid', placeItems: 'center', flex: 'none' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M9 5a3 3 0 0 0-3 3 3 3 0 0 0-1 5.8A2.8 2.8 0 0 0 8 19a2.5 2.5 0 0 0 4-2V6a2 2 0 0 0-2-2 1 1 0 0 0-1 1Z" /><path d="M15 5a3 3 0 0 1 3 3 3 3 0 0 1 1 5.8A2.8 2.8 0 0 1 16 19a2.5 2.5 0 0 1-4-2" /></svg>
          </span>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: P.ink }}>Pattern detected</span>
          <span style={{ marginLeft: 'auto', fontSize: 10, fontWeight: 700, color: P.green, background: P.greenDim, padding: '3px 8px', borderRadius: 999 }}>92% conf.</span>
        </div>
        <div style={{ background: P.elev, border: `1px solid ${P.line}`, borderRadius: 10, padding: '12px 13px', fontSize: 12.5, color: P.ink2, lineHeight: 1.55 }}>
          Your <b style={{ color: P.ink }}>breakout</b> setups return <b style={{ color: P.green }}>2.4×</b> more when held past the first pullback. You exit early on <b style={{ color: P.ink }}>71%</b> of winners.
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 10 }}>
          <div className="mk"><div className="k">Edge leak</div><div className="v g-neg" style={{ fontSize: 15 }}>Early exits</div></div>
          <div className="mk"><div className="k">Best window</div><div className="v" style={{ fontSize: 15, color: P.ink }}>9:45–10:30</div></div>
        </div>
      </div>
    </Screen>);
}

// ===== 2.3c-i Time of day =====
function GfxTimeOfDay() {
  return (
    <Screen label="P&L by time of day">
      <div className="screen-pad">
        <Bars
          data={[{ v: 9 }, { v: 14 }, { v: 6 }, { v: -4 }, { v: -2 }, { v: 5 }, { v: 11 }]}
          labels={['9:15', '9:45', '10:30', '11:30', '13:00', '14:00', '15:00']} h={108} />
      </div>
    </Screen>);
}

// ===== 2.3c-ii Day of week =====
function GfxDayOfWeek() {
  return (
    <Screen label="P&L by day of week">
      <div className="screen-pad">
        <Bars
          data={[{ v: 12 }, { v: 7 }, { v: -3 }, { v: 15 }, { v: 9 }]}
          labels={['Mon', 'Tue', 'Wed', 'Thu', 'Fri']} h={108} />
      </div>
    </Screen>);
}

// ===== 2.3c-iii Situational awareness =====
function GfxSituational() {
  return (
    <Screen label="Situational awareness">
      <div className="screen-pad">
        <HBars rows={[
          { l: 'Followed plan', v: 86, t: '+₹2.1L', c: P.green },
          { l: 'Patient entry', v: 64, t: '+₹94k', c: P.green },
          { l: 'Chased / FOMO', v: 48, t: '−₹61k', c: P.red },
          { l: 'Revenge trade', v: 30, t: '−₹38k', c: P.red },
        ]} max={86} />
      </div>
    </Screen>);
}

// ===== 2.3d Strategy / mistakes / exit =====
function GfxStrategyMix() {
  return (
    <Screen label="Strategy · mistakes · exits">
      <div className="screen-pad" style={{ display: 'grid', gap: 14 }}>
        <div>
          <div className="g-cap" style={{ marginBottom: 8 }}>By strategy</div>
          <HBars rows={[
            { l: 'Breakout', v: 92, t: '2.8R', c: P.green },
            { l: 'Pullback', v: 60, t: '1.6R', c: P.green },
            { l: 'Reversal', v: 35, t: '0.4R', c: P.amber },
          ]} max={92} />
        </div>
        <div>
          <div className="g-cap" style={{ marginBottom: 8 }}>Top mistakes</div>
          <HBars rows={[
            { l: 'Moved stop', v: 70, t: '−₹84k', c: P.red },
            { l: 'Oversized', v: 44, t: '−₹52k', c: P.red },
          ]} max={70} />
        </div>
      </div>
    </Screen>);
}

// ===== 2.3e AI monthly report =====
function GfxMonthlyReport() {
  return (
    <Screen label="AI monthly report" className="lg">
      <div className="screen-pad">
        <div className="g-row" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
          <div><div className="g-cap">May 2026 · Review</div><div style={{ fontSize: 18, fontWeight: 800, color: P.ink, marginTop: 3, letterSpacing: '-.02em' }}>Your best month yet</div></div>
          <span style={{ fontSize: 26, fontWeight: 800, color: P.green, fontFamily: 'var(--mono)' }}>A</span>
        </div>
        <div style={{ display: 'grid', gap: 8 }}>
          {[
            ['Discipline up 18% — you stuck to stops on 9/10 losers.', P.green],
            ['Breakouts drove 74% of net P&L. Double down here.', P.green],
            ['Wednesdays still bleed — consider sitting out.', P.amber],
          ].map((r, i) => (
            <div key={i} className="g-row" style={{ gap: 10, alignItems: 'flex-start' }}>
              <span style={{ width: 6, height: 6, borderRadius: 9, background: r[1], marginTop: 6, flex: 'none' }} />
              <span style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.5 }}>{r[0]}</span>
            </div>))}
        </div>
      </div>
    </Screen>);
}

// ===== 2.4 Review — candle chart with entry/exit + tags =====
function GfxReview() {
  const W = 330, H = 150;
  const candles = [
    [40, 60, 38, 55], [55, 58, 48, 50], [50, 53, 42, 45], [45, 62, 44, 60],
    [60, 64, 54, 57], [57, 59, 49, 52], [52, 75, 51, 72], [72, 88, 70, 84],
    [84, 90, 80, 86], [86, 95, 78, 82], [82, 92, 80, 90], [90, 110, 88, 106],
    [106, 112, 100, 104], [104, 120, 102, 118],
  ];
  const min = 36, max = 124; const cw = W / candles.length;
  const toY = (v) => H - 14 - ((v - min) / (max - min)) * (H - 28);
  const entryIdx = 6, exitIdx = 11;
  return (
    <Screen label="Trade review" className="lg">
      <div className="screen-pad">
        <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: H, display: 'block', overflow: 'visible' }}>
          {candles.map((c, i) => {
            const x = i * cw + cw / 2; const up = c[3] >= c[0];
            const col = up ? P.green : P.red;
            const bodyTop = toY(Math.max(c[0], c[3])), bodyBot = toY(Math.min(c[0], c[3]));
            return (
              <g key={i}>
                <line x1={x} y1={toY(c[1])} x2={x} y2={toY(c[2])} stroke={col} strokeWidth="1.2" />
                <rect x={x - cw * 0.26} y={bodyTop} width={cw * 0.52} height={Math.max(2, bodyBot - bodyTop)} rx="1" fill={col} />
              </g>);
          })}
          <g>
            <line x1={entryIdx * cw + cw / 2} y1={toY(candles[entryIdx][3]) + 6} x2={entryIdx * cw + cw / 2} y2={H - 2} stroke={P.green} strokeWidth="1" strokeDasharray="2 3" />
            <circle cx={entryIdx * cw + cw / 2} cy={toY(candles[entryIdx][3])} r="4" fill={P.green} stroke={P.panel} strokeWidth="1.5" />
            <text x={entryIdx * cw + cw / 2 + 7} y={toY(candles[entryIdx][3]) + 3} fontSize="9" fontWeight="700" fill={P.green}>BUY</text>
          </g>
          <g>
            <circle cx={exitIdx * cw + cw / 2} cy={toY(candles[exitIdx][3])} r="4" fill={P.amber} stroke={P.panel} strokeWidth="1.5" />
            <text x={exitIdx * cw + cw / 2 - 24} y={toY(candles[exitIdx][3]) - 6} fontSize="9" fontWeight="700" fill={P.amber}>SELL</text>
          </g>
        </svg>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginTop: 12 }}>
          {[['Setup', 'Breakout', P.green], ['Mistake', 'Exited early', P.red], ['Exit', 'Target 1', P.ink2]].map((f, i) => (
            <div key={i} style={{ background: P.elev, border: `1px solid ${P.line}`, borderRadius: 9, padding: '9px 10px' }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, color: P.ink3, textTransform: 'uppercase', letterSpacing: '.04em' }}>{f[0]}</div>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: f[2], marginTop: 4 }}>{f[1]}</div>
            </div>))}
        </div>
      </div>
    </Screen>);
}

// ===== 2.4a Print book =====
function GfxPrintBook() {
  return (
    <Screen label="Export review book">
      <div className="screen-pad" style={{ display: 'grid', placeItems: 'center', minHeight: 150 }}>
        <div style={{ position: 'relative', width: 130, height: 120 }}>
          {[2, 1, 0].map((d) => (
            <div key={d} style={{ position: 'absolute', left: d * 9, top: d * 7, width: 104, height: 116, background: d === 0 ? '#fbfbfa' : P.elev, border: `1px solid ${d === 0 ? P.line : P.line}`, borderRadius: 6, boxShadow: d === 0 ? '0 8px 22px rgba(0,0,0,.5)' : 'none', padding: 10 }}>
              {d === 0 && <div>
                <div style={{ height: 30, borderRadius: 3, background: '#eef2f6' }} />
                <div style={{ height: 4, width: '70%', background: '#d8dee6', borderRadius: 3, marginTop: 8 }} />
                <div style={{ height: 4, width: '90%', background: '#e6eaef', borderRadius: 3, marginTop: 5 }} />
                <div style={{ height: 4, width: '50%', background: '#e6eaef', borderRadius: 3, marginTop: 5 }} />
              </div>}
            </div>))}
        </div>
        <div style={{ fontSize: 11, color: P.ink3, marginTop: 6 }}>One chart per page · print-ready PDF</div>
      </div>
    </Screen>);
}

// ===== 2.5 Stock Bee Market Monitor =====
function GfxMarketMonitor() {
  const tickers = [
    ['NIFTY', '+0.8%', true], ['BANKNIFTY', '+1.2%', true], ['SENSEX', '+0.7%', true],
    ['ADV', '1,842', true], ['DEC', '1,106', false], ['NH-NL', '+214', true],
  ];
  return (
    <Screen label="Stock Bee · Market Monitor" live="Live">
      <div className="screen-pad">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>
          {tickers.map((t, i) => (
            <div key={i} style={{ background: P.elev, border: `1px solid ${P.line}`, borderRadius: 9, padding: '9px 10px' }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, color: P.ink3 }}>{t[0]}</div>
              <div className="g-num" style={{ fontSize: 13.5, fontWeight: 700, color: t[2] ? P.green : P.red, marginTop: 3 }}>{t[1]}</div>
            </div>))}
        </div>
        <div style={{ marginTop: 11 }}>
          <div className="g-cap" style={{ marginBottom: 7 }}>Market breadth · 4% gainers vs decliners</div>
          <Bars data={[{ v: 7 }, { v: 9 }, { v: 12 }, { v: 8 }, { v: 14 }, { v: 11 }, { v: 16 }]} h={66} />
        </div>
      </div>
    </Screen>);
}

// ===== 3 Security =====
function GfxSecurity() {
  return (
    <Screen label="Security">
      <div className="screen-pad" style={{ display: 'grid', placeItems: 'center', minHeight: 150 }}>
        <div style={{ width: 64, height: 64, borderRadius: 18, background: P.greenDim, color: P.green, display: 'grid', placeItems: 'center', border: `1px solid ${P.green}` }}>
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3.5 5 6v5.5c0 4.4 3 7.5 7 9 4-1.5 7-4.6 7-9V6Z" /><path d="m9 12 2 2 4-4" /></svg>
        </div>
        <div style={{ fontSize: 13, fontWeight: 700, color: P.ink, marginTop: 12 }}>AES-256 encrypted</div>
        <div style={{ fontSize: 11, color: P.ink3, marginTop: 3 }}>Read-only access · your data, exportable anytime</div>
      </div>
    </Screen>);
}

Object.assign(window, {
  HBars, GfxMFEMAE, GfxAIAnalysis, GfxTimeOfDay, GfxDayOfWeek, GfxSituational,
  GfxStrategyMix, GfxMonthlyReport, GfxReview, GfxPrintBook, GfxMarketMonitor, GfxSecurity,
});
