const { useState, useEffect, useRef, useMemo } = React;

/* ---------- utilities ---------- */
const pad = (n, w = 2) => String(n).padStart(w, '0');
const fmt = (n, d = 2) => n.toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d });

/* ---------- Nav ---------- */
function Nav() {
  const [t, setT] = useState(new Date());
  useEffect(() => {
    const i = setInterval(() => setT(new Date()), 1000);
    return () => clearInterval(i);
  }, []);
  const utc = `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`;
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#top" className="brand">
          <img src="assets/velocity-mark.png" alt="" className="brand-mark" />
          <span className="brand-name">VELOCITY</span>
          <span className="brand-tld">/ dev.cc</span>
        </a>
        <div className="nav-links">
          <a href="#systems">Systems</a>
          <a href="#approach">Approach</a>
          <a href="#stack">Stack</a>
          <a href="#contact">Contact</a>
        </div>
        <div className="nav-meta">
          <span className="nav-dot" />
          <span className="nav-utc">{utc} UTC</span>
        </div>
      </div>
    </nav>
  );
}

/* ---------- Hero ---------- */
function Hero() {
  return (
    <section id="top" className="hero">
      <div className="hero-grid" />
      <div className="hero-glow" />
      <div className="hero-inner">
        <div className="hero-tag">
          <span className="tag-chip">V-01</span>
          <span>QUANTITATIVE SYSTEMS · SIGNALS · EXECUTION</span>
        </div>

        <h1 className="hero-title">
          <span className="line">Engineering</span>
          <span className="line">
            <span className="accent">edge</span> from noise.
          </span>
        </h1>

        <p className="hero-sub">
          Independent developer building signals, expert advisors and execution
          bots. Research-first. Rules-first. Latency-aware.
        </p>

        <div className="hero-cta">
          <a href="#contact" className="btn btn-primary">
            <span>Apply for access</span>
            <ArrowIcon />
          </a>
          <a href="#systems" className="btn btn-ghost">
            <span>See systems</span>
          </a>
        </div>

        <EquityChart />

        <HeroStats />
      </div>

      <Marquee />
    </section>
  );
}

function ArrowIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
      <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square" />
    </svg>
  );
}

/* ---------- Equity curve (animated) ----------
   Built from real monthly returns — single setup, Dukascopy tick data, all-ticks */
const MONTHLY = [
  // [year, [Jan..Dec]]
  [2013, [-1365.3, 2268.85, 629.69, 1741.07, 3079.61, 1706.87, 2596.24, -67.2, 2034.76, 859.37, 51.01, 2810.03]],
  [2014, [1684.24, 87.38, 1721.03, -466.51, 369.67, 34.7, 1808.99, 1511.23, 29.78, 1080.65, 171.46, 6121.51]],
  [2015, [-757.12, 1785.32, -131, -1379.18, 1386.2, -316.69, 365.62, -770.2, -19.13, 157.6, 569.64, -822.72]],
  [2016, [-104.7, -837.69, 664.98, 2558.23, -620.46, 2315.64, 2455.4, -438.31, 1146.31, -602.84, 2252.8, -979.85]],
  [2017, [-374.05, -881.17, -337.06, 2031.28, -298.84, -862.91, -430.91, 1557.2, -998, -420.74, 1010.25, -823.39]],
  [2018, [-582.13, 1514.82, -475.61, 1215.49, 1572.97, 823.94, 583.21, 1376.12, -1107.53, 2203.63, -304.6, 2473.92]],
  [2019, [-729.81, -299.62, 47.23, -1480.08, 777.38, -1767.87, 1528.74, 819.98, -626.31, -388.4, 1872.94, 3226.07]],
  [2020, [814.86, 3533.2, 1766.51, -100.95, -632.8, 991.3, 872.68, 660.34, -414.79, 560.4, 1982.79, -1177.03]],
  [2021, [-362.69, 1918.25, 650.88, 177.37, 135.64, -44.53, 818.19, -366.95, -352.58, 1561.59, -923.79, -237.78]],
  [2022, [631.02, 580.7, 3575.99, 871.04, 307.18, 2845.05, -292.51, 860.45, 588.4, 640.38, 692.69, 884.69]],
  [2023, [68.54, -1372.72, 520.48, -1796.67, 1076.15, 228.33, 1195.85, -816.41, 1977.47, 399.07, 961.4, 81.89]],
  [2024, [17.19, 372.95, 408.8, 2097.91, 642.77, 609.63, 345.46, 875.92, -527.2, -168.29, 1060.11, -1232.83]],
  [2025, [-323.48, 105.6, -891.06, -767.12, 2971.66, 502.65, 145.42, 650.2, 1519.09, 0, 0, 0]],
];

function EquityChart() {
  const W = 1080, H = 220;
  const points = useMemo(() => {
    const flat = [];
    MONTHLY.forEach(([y, months]) => {
      months.forEach((m, mi) => {
        if (y === 2025 && mi >= 9) return; // no data yet
        flat.push(m);
      });
    });
    const eq = [0];
    flat.forEach((v) => eq.push(eq[eq.length - 1] + v));
    const min = Math.min(...eq), max = Math.max(...eq);
    return eq.map((y, i) => ({
      x: (i / (eq.length - 1)) * W,
      y: H - 14 - ((y - min) / (max - min)) * (H - 28),
    }));
  }, []);

  const path = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)} ${p.y.toFixed(1)}`).join(' ');
  const area = `${path} L${W} ${H} L0 ${H} Z`;
  const last = points[points.length - 1];

  return (
    <div className="equity">
      <div className="equity-head">
        <div className="equity-label">
          <span className="eq-dot" />
          V-01 · EQUITY · DUKASCOPY TICK · ALL-TICKS · 2013–2025
        </div>
        <div className="equity-stats">
          <Stat k="NET" v="+$86,376" />
          <Stat k="CAGR" v="18.66%" />
          <Stat k="MAX DD" v="−13.23%" />
          <Stat k="PF" v="1.32" />
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} className="equity-svg" preserveAspectRatio="none">
        <defs>
          <linearGradient id="eqFill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="rgba(138, 82, 196, 0.35)" />
            <stop offset="100%" stopColor="rgba(138, 82, 196, 0)" />
          </linearGradient>
          <linearGradient id="eqStroke" x1="0" x2="1" y1="0" y2="0">
            <stop offset="0%" stopColor="#8a52c4" />
            <stop offset="100%" stopColor="#c89af5" />
          </linearGradient>
        </defs>
        {/* grid */}
        {[0.25, 0.5, 0.75].map((g, i) => (
          <line key={i} x1="0" x2={W} y1={H * g} y2={H * g} stroke="rgba(255,255,255,0.05)" strokeDasharray="2 6" />
        ))}
        <path d={area} fill="url(#eqFill)" className="eq-area" />
        <path
          d={path}
          fill="none"
          stroke="url(#eqStroke)"
          strokeWidth="1.75"
          strokeLinecap="round"
          className="eq-line"
        />
        <g>
          <circle cx={last.x} cy={last.y} r="4" fill="#c89af5" className="eq-dot-end" />
          <circle cx={last.x} cy={last.y} r="10" fill="rgba(200,154,245,0.2)" className="eq-dot-end">
            <animate attributeName="r" values="6;16;6" dur="2.2s" repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.5;0;0.5" dur="2.2s" repeatCount="indefinite" />
          </circle>
        </g>
      </svg>
      <div className="equity-axis">
        <span>2013</span><span>2016</span><span>2019</span><span>2022</span><span>2025</span>
      </div>
      <div className="equity-disc">
        Results shown are from a single setup, back-tested on Dukascopy tick data (all-ticks).
        Avg ~$25 per trade. Past performance is not indicative of future results.
      </div>
    </div>
  );
}

function Stat({ k, v }) {
  return (
    <div className="stat">
      <span className="stat-k">{k}</span>
      <span className="stat-v">{v}</span>
    </div>
  );
}

function HeroStats() {
  return (
    <div className="hero-stats">
      <HeroStatBlock n="10+" l="Years of history" />
      <HeroStatBlock n="3k+" l="Trades evaluated" />
      <HeroStatBlock n="21+" l="Return / DD ratio" />
      <HeroStatBlock n="Tick" l="Dukascopy all-ticks" />
    </div>
  );
}
function HeroStatBlock({ n, l }) {
  return (
    <div className="hstat">
      <div className="hstat-n">{n}</div>
      <div className="hstat-l">{l}</div>
    </div>
  );
}

/* ---------- Marquee ---------- */
function Marquee() {
  const items = [
    'XAUUSD', 'EURUSD', 'NAS100', 'GBPJPY', 'US30', 'BTCUSD', 'SPX500', 'USDJPY',
    'ETHUSD', 'DAX40', 'AUDUSD', 'WTI', 'XAGUSD', 'USOIL',
  ];
  const row = [...items, ...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {row.map((s, i) => {
          const up = (i * 7) % 3 !== 0;
          const delta = ((i * 13) % 90) / 10;
          return (
            <span key={i} className="mq-item">
              <span className="mq-sym">{s}</span>
              <span className={up ? 'mq-up' : 'mq-down'}>
                {up ? '▲' : '▼'} {fmt(delta, 2)}%
              </span>
            </span>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Section header ---------- */
function SectionHead({ id, kicker, title, sub }) {
  return (
    <header className="sec-head">
      <div className="sec-kicker">
        <span className="sec-id">{id}</span>
        <span>{kicker}</span>
      </div>
      <h2 className="sec-title">{title}</h2>
      {sub && <p className="sec-sub">{sub}</p>}
    </header>
  );
}

/* ---------- Systems ---------- */
function Systems() {
  const systems = [
    {
      tag: 'SIG',
      name: 'Signal engines',
      blurb: 'Rules-based signal generation across FX, indices and metals. Regime-aware, session-tuned, delivered as feed or webhook.',
      bullets: ['Trend + mean-reversion hybrids', 'Session & volatility filters', 'Webhook / email / MT delivery'],
    },
    {
      tag: 'EA / CBOT',
      name: 'Expert advisors & cBots',
      blurb: 'MT4 / MT5 expert advisors and cTrader cBots built to a spec. Audited risk, realistic slippage, prop-firm aware money management.',
      bullets: ['MQL4 / MQL5 & cTrader C#', 'Spread, slippage & swap aware', 'Broker-side risk kill-switch'],
    },
    {
      tag: 'BOT',
      name: 'Execution bots',
      blurb: 'Crypto and CFD execution layers. Python cores, low-latency brokers, idempotent order routing and recon.',
      bullets: ['Python / Rust execution', 'CEX & broker REST / FIX', 'Reconciliation & alerting'],
    },
  ];
  return (
    <section id="systems" className="section">
      <SectionHead id="/ 02" kicker="WHAT IS BUILT" title="Systems, not scripts." />
      <div className="sys-grid">
        {systems.map((s, i) => <SystemCard key={i} {...s} idx={i} />)}
      </div>
    </section>
  );
}

function SystemCard({ tag, name, blurb, bullets, idx }) {
  return (
    <article className="sys-card">
      <div className="sys-head">
        <span className="sys-tag">{tag}</span>
        <span className="sys-idx">0{idx + 1} / 03</span>
      </div>
      <h3 className="sys-name">{name}</h3>
      <p className="sys-blurb">{blurb}</p>
      <ul className="sys-list">
        {bullets.map((b, i) => (
          <li key={i}>
            <span className="sys-dot" /> {b}
          </li>
        ))}
      </ul>
      <div className="sys-foot">
        <span>Engagement</span>
        <span className="sys-arrow">→</span>
      </div>
    </article>
  );
}

/* ---------- Approach ---------- */
function Approach() {
  const steps = [
    { n: '01', t: 'Research', d: 'Hypothesis from market microstructure, price-action regimes or statistical anomaly. Written before a line of code.' },
    { n: '02', t: 'Backtest', d: 'Vectorized and event-driven passes. Walk-forward splits. No peeking, no survivorship, conservative costs.' },
    { n: '03', t: 'Paper', d: 'Live paper for weeks, not hours. Broker-side behavior, slippage distributions, timing drift — measured, not assumed.' },
    { n: '04', t: 'Deploy', d: 'Versioned build, kill-switches, alerting, post-trade recon. Treated like software, because it is.' },
  ];
  return (
    <section id="approach" className="section">
      <SectionHead
        id="/ 03"
        kicker="HOW THE WORK MOVES"
        title="A short loop, done properly."
        sub="Every system goes through the same four stages. No shortcuts, no vibes."
      />
      <ol className="steps">
        {steps.map((s) => (
          <li key={s.n} className="step">
            <div className="step-n">{s.n}</div>
            <div className="step-body">
              <h4>{s.t}</h4>
              <p>{s.d}</p>
            </div>
          </li>
        ))}
      </ol>
    </section>
  );
}

/* ---------- Stack + Live feed ---------- */
function StackAndFeed() {
  return (
    <section id="stack" className="section section-split">
      <div className="split-left">
        <SectionHead id="/ 04" kicker="STACK" title="Boring tools, used well." />
        <div className="stack-grid">
          {[
            ['Python', 'research · execution'],
            ['Rust', 'hot paths · FIX'],
            ['MQL4 / 5', 'MT expert advisors'],
            ['Pine v5', 'TradingView signals'],
            ['PostgreSQL', 'tick & trade store'],
            ['Redis', 'state · queues'],
            ['Docker', 'deployments'],
            ['Grafana', 'observability'],
          ].map(([k, v]) => (
            <div key={k} className="stack-item">
              <span className="stack-k">{k}</span>
              <span className="stack-v" style={{ textAlign: 'right' }}>{v}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="split-right">
        <LiveFeed />
      </div>
    </section>
  );
}

function LiveFeed() {
  const symbols = ['XAUUSD', 'EURUSD', 'NAS100', 'GBPJPY', 'BTCUSD', 'US30', 'USDJPY', 'ETHUSD'];
  const sides = ['LONG', 'SHORT'];
  const tags = ['V-TREND', 'V-REV', 'V-BRK', 'V-SCALP'];

  const [rows, setRows] = useState(() =>
    Array.from({ length: 6 }).map((_, i) => makeRow(Date.now() - i * 47000))
  );

  function makeRow(t = Date.now()) {
    const s = symbols[Math.floor(Math.random() * symbols.length)];
    const side = sides[Math.floor(Math.random() * sides.length)];
    const tag = tags[Math.floor(Math.random() * tags.length)];
    const base = { XAUUSD: 2340, EURUSD: 1.08, NAS100: 18240, GBPJPY: 197, BTCUSD: 68400, US30: 39100, USDJPY: 152, ETHUSD: 3480 }[s];
    const px = base * (1 + (Math.random() - 0.5) * 0.002);
    const pnl = (Math.random() - 0.35) * 2.6;
    return {
      id: Math.random().toString(36).slice(2, 9),
      t,
      s, side, tag,
      px: px < 10 ? px.toFixed(4) : px.toFixed(2),
      pnl: pnl.toFixed(2),
    };
  }

  useEffect(() => {
    const i = setInterval(() => {
      setRows((r) => [makeRow(), ...r].slice(0, 7));
    }, 3200);
    return () => clearInterval(i);
  }, []);

  const now = Date.now();

  return (
    <div className="feed">
      <div className="feed-head">
        <div className="feed-title">
          <span className="feed-live">
            <span className="feed-live-dot" /> LIVE
          </span>
          <span>SIGNAL FEED · DEMO STREAM</span>
        </div>
        <span className="feed-meta">v-stream / 1m</span>
      </div>
      <div className="feed-body">
        {rows.map((r, i) => {
          const ago = Math.max(1, Math.floor((now - r.t) / 1000));
          return (
            <div key={r.id} className={`feed-row ${i === 0 ? 'feed-row-new' : ''}`}>
              <span className="fr-time">{ago < 60 ? `${ago}s` : `${Math.floor(ago / 60)}m`}</span>
              <span className="fr-tag">{r.tag}</span>
              <span className="fr-sym">{r.s}</span>
              <span className={`fr-side fr-${r.side.toLowerCase()}`}>{r.side}</span>
              <span className="fr-px">@ {r.px}</span>
              <span className={`fr-pnl ${parseFloat(r.pnl) >= 0 ? 'up' : 'down'}`}>
                {parseFloat(r.pnl) >= 0 ? '+' : ''}{r.pnl}R
              </span>
            </div>
          );
        })}
      </div>
      <div className="feed-foot">
        <span>Not financial advice. Past performance ≠ future results.</span>
      </div>
    </div>
  );
}

/* ---------- Contact ---------- */
function Contact() {
  const [sent, setSent] = useState(false);
  const [intent, setIntent] = useState('license');
  return (
    <section id="contact" className="section contact">
      <div className="contact-grid">
        <div>
          <div className="sec-kicker">
            <span className="sec-id">/ 05</span>
            <span>APPLY FOR ACCESS</span>
          </div>
          <h2 className="contact-title">
            Want to apply<br />for access?
          </h2>
          <p className="contact-sub">
            Licenses are issued in limited batches to keep execution quality
            intact. Tell me your account size, broker and instruments—I'll let
            you know if there's a seat.
          </p>
          <p className="contact-sub contact-sub-soft">
            Have a spec, an edge, or a broken bot instead? I take on custom
            work too switch the intent above your message.
          </p>
          <div className="contact-meta">
            <div><span className="cm-k">EMAIL</span><span className="cm-v">support@velocitydev.cc</span></div>
            <div><span className="cm-k">HOURS</span><span className="cm-v">Mon–Fri · 08:00–18:00 UTC</span></div>
          </div>
        </div>
        <form
          className="contact-form"
          onSubmit={(e) => { e.preventDefault(); setSent(true); }}
        >
          <div className="form-row">
            <label>INTENT</label>
            <div className="intent-toggle">
              <button type="button" className={intent === 'license' ? 'it-on' : ''} onClick={() => setIntent('license')}>
                <span className="it-label">01 · Primary</span>
                <span className="it-title">License access</span>
              </button>
              <button type="button" className={intent === 'custom' ? 'it-on' : ''} onClick={() => setIntent('custom')}>
                <span className="it-label">02 · Bespoke</span>
                <span className="it-title">Custom work</span>
              </button>
            </div>
          </div>
          <div className="form-row">
            <label>NAME</label>
            <input type="text" required placeholder="Your name" />
          </div>
          <div className="form-row">
            <label>EMAIL</label>
            <input type="email" required placeholder="you@domain.com" />
          </div>
          {intent === 'license' ? (
            <>
              <div className="form-row">
                <label>INTERESTED IN</label>
                <div className="chips">
                  {['V-01 Signals', 'V-01 EA / cBot', 'Execution bot', 'Full bundle'].map((c) => (
                    <Chip key={c} label={c} />
                  ))}
                </div>
              </div>
              <div className="form-row">
                <label>ACCOUNT</label>
                <input type="text" placeholder="Broker · account size · prop / live" />
              </div>
              <div className="form-row">
                <label>NOTES</label>
                <textarea rows="3" placeholder="Experience, timezone, anything relevant…" />
              </div>
            </>
          ) : (
            <>
              <div className="form-row">
                <label>SCOPE</label>
                <div className="chips">
                  {['Signals', 'Expert advisor / cBot', 'Execution bot', 'Research', 'Audit'].map((c) => (
                    <Chip key={c} label={c} />
                  ))}
                </div>
              </div>
              <div className="form-row">
                <label>BRIEF</label>
                <textarea rows="4" placeholder="Instrument, timeframe, broker, rough idea…" />
              </div>
            </>
          )}
          <button className="btn btn-primary btn-submit" type="submit" disabled={sent}>
            <span>{sent ? 'Submitted ✓' : (intent === 'license' ? 'Submit application' : 'Transmit brief')}</span>
            {!sent && <ArrowIcon />}
          </button>
        </form>
      </div>
    </section>
  );
}

function Chip({ label }) {
  const [on, setOn] = useState(false);
  return (
    <button
      type="button"
      className={`chip ${on ? 'chip-on' : ''}`}
      onClick={() => setOn((x) => !x)}
    >
      {label}
    </button>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-brand">
          <img src="assets/velocity-mark.png" alt="" />
          <div>
            <div className="fb-name">VELOCITY / dev.cc</div>
            <div className="fb-sub">Quantitative systems · Independent</div>
          </div>
        </div>
        <div className="footer-cols">
          <div>
            <div className="fc-h">SITE</div>
            <a href="#systems">Systems</a>
            <a href="#approach">Approach</a>
            <a href="#stack">Stack</a>
            <a href="#contact">Contact</a>
          </div>
          <div>
            <div className="fc-h">LEGAL</div>
            <a href="legal/risk.html">Risk disclosure</a>
            <a href="legal/terms.html">Terms</a>
            <a href="legal/privacy.html">Privacy</a>
          </div>
          <div>
            <div className="fc-h">ELSEWHERE</div>
            <a href="mailto:support@velocitydev.cc">Email</a>
          </div>
        </div>
      </div>
      <div className="footer-bar">
        <span>© 2026 velocitydev.cc</span>
        <span>Trading involves risk of loss. Nothing here is advice.</span>
        <span>Built in cold rooms at odd hours.</span>
      </div>
    </footer>
  );
}

/* ---------- App ---------- */
function App() {
  // subtle mouse spotlight
  useEffect(() => {
    const onMove = (e) => {
      document.documentElement.style.setProperty('--mx', e.clientX + 'px');
      document.documentElement.style.setProperty('--my', e.clientY + 'px');
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);

  // scroll reveal
  useEffect(() => {
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => e.isIntersecting && e.target.classList.add('in')),
      { threshold: 0.12 }
    );
    document.querySelectorAll('.section, .sys-card, .step, .stat, .hstat, .stack-item').forEach((el) => {
      el.classList.add('reveal');
      io.observe(el);
    });
    return () => io.disconnect();
  }, []);

  return (
    <>
      <div className="spotlight" />
      <Nav />
      <Hero />
      <Systems />
      <Approach />
      <StackAndFeed />
      <Contact />
      <Footer />
    </>
  );
}

Object.assign(window, { App });
