/* global React */
const { useState, useEffect, useRef, useMemo } = React;

/* ============================================
   EXPERT FOR FOREX — Shared Components
   ============================================ */

/* ---------- Logo ---------- */
function Logo({ size = 40 }) {
  return (
    <div className="logo">
      <div className="logo-mark" style={{ width: size, height: size }}>
        <svg viewBox="0 0 40 40" fill="none">
          <defs>
            <linearGradient id="logoGrad" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stopColor="#00E5FF" />
              <stop offset="50%" stopColor="#7C5CFF" />
              <stop offset="100%" stopColor="#FF2DAA" />
            </linearGradient>
            <filter id="logoGlow"><feGaussianBlur stdDeviation="1.2" /></filter>
          </defs>
          <rect x="1" y="1" width="38" height="38" rx="8" stroke="url(#logoGrad)" strokeWidth="1.5" fill="rgba(0,229,255,0.04)" />
          {/* E shape */}
          <path d="M11 11 L20 11 L20 13.5 L13.5 13.5 L13.5 18.75 L19 18.75 L19 21.25 L13.5 21.25 L13.5 26.5 L20 26.5 L20 29 L11 29 Z" fill="url(#logoGrad)" filter="url(#logoGlow)" />
          {/* F shape interlocked */}
          <path d="M21 11 L29 11 L29 13.5 L23.5 13.5 L23.5 18.75 L28.5 18.75 L28.5 21.25 L23.5 21.25 L23.5 29 L21 29 Z" fill="url(#logoGrad)" opacity="0.85" />
        </svg>
      </div>
      <div className="logo-text">
        EXPERT FOR FOREX
      </div>
    </div>);

}

/* ---------- Nav ---------- */
function Nav({ current, go, user, onAuth, onSignOut }) {
  const [open, setOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const links = [
  { id: 'home', label: 'Home' },
  { id: 'marketplace', label: 'Marketplace' },
  { id: 'dashboard', label: 'Dashboard' },
  { id: 'agent', label: 'AI Agent' },
  { id: 'about', label: 'About' }];

  const handleNav = (id) => {setOpen(false);setMenuOpen(false);go(id);};

  // Close user menu on outside click
  useEffect(() => {
    if (!menuOpen) return;
    const close = (e) => {
      if (!e.target.closest('[data-user-menu]')) setMenuOpen(false);
    };
    window.addEventListener('click', close);
    return () => window.removeEventListener('click', close);
  }, [menuOpen]);

  return (
    <nav className="nav">
      <div className="container nav-inner">
        <div style={{ cursor: 'pointer' }} onClick={() => handleNav('home')}><Logo /></div>
        <div className="nav-links">
          {links.map((l) =>
          <a key={l.id} className={`nav-link ${current === l.id ? 'active' : ''}`} onClick={() => handleNav(l.id)}>{l.label}</a>
          )}
        </div>
        <div className="nav-actions">
          {user ?
          <div data-user-menu style={{ position: 'relative' }}>
              <button
                onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }}
                className="flex gap-2"
                style={{ alignItems: 'center', padding: '4px 12px', background: 'transparent', border: '1px solid var(--line)', borderRadius: 8, cursor: 'pointer', color: 'inherit' }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', background: user.photoURL ? `url(${user.photoURL}) center/cover` : 'var(--grad-1)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700, color: '#000', fontSize: 12 }}>
                  {!user.photoURL && (user.name?.[0]?.toUpperCase() || 'U')}
                </div>
                <div style={{ fontSize: 12, textAlign: 'left' }} className="hide-mobile">
                  <div style={{ color: 'var(--text)', fontWeight: 600 }}>{user.name}</div>
                  <div className="font-mono text-xs" style={{ color: 'var(--cyan)' }}>{user.plan?.toUpperCase() || 'STARTER'}</div>
                </div>
                <span style={{ color: 'var(--text-3)', fontSize: 10 }} className="hide-mobile">▼</span>
              </button>
              {menuOpen && (
                <div style={{
                  position: 'absolute', top: 'calc(100% + 8px)', right: 0,
                  background: 'rgba(5,6,13,0.98)', backdropFilter: 'blur(16px)',
                  border: '1px solid var(--line-strong)', borderRadius: 8,
                  minWidth: 220, padding: 8, zIndex: 100,
                  boxShadow: '0 12px 32px rgba(0,0,0,0.6), 0 0 0 1px var(--line-strong)',
                  animation: 'fadeIn 0.15s',
                }}>
                  <div style={{ padding: '8px 12px', borderBottom: '1px solid var(--line-soft)' }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{user.name}</div>
                    <div className="font-mono text-xs text-muted mt-1" style={{ wordBreak: 'break-all' }}>{user.email}</div>
                  </div>
                  <div style={{ padding: 4 }}>
                    <button onClick={() => handleNav('dashboard')} style={{ display: 'block', width: '100%', padding: '10px 12px', background: 'transparent', border: 0, color: 'var(--text-2)', textAlign: 'left', cursor: 'pointer', borderRadius: 4, fontSize: 13 }} onMouseEnter={(e) => e.target.style.background = 'rgba(0,229,255,0.06)'} onMouseLeave={(e) => e.target.style.background = 'transparent'}>
                      Dashboard
                    </button>
                    <button onClick={() => handleNav('marketplace')} style={{ display: 'block', width: '100%', padding: '10px 12px', background: 'transparent', border: 0, color: 'var(--text-2)', textAlign: 'left', cursor: 'pointer', borderRadius: 4, fontSize: 13 }} onMouseEnter={(e) => e.target.style.background = 'rgba(0,229,255,0.06)'} onMouseLeave={(e) => e.target.style.background = 'transparent'}>
                      Marketplace
                    </button>
                    <button onClick={() => { setMenuOpen(false); onSignOut?.(); }} style={{ display: 'block', width: '100%', padding: '10px 12px', background: 'transparent', border: 0, color: 'var(--red)', textAlign: 'left', cursor: 'pointer', borderRadius: 4, fontSize: 13, marginTop: 4, borderTop: '1px solid var(--line-soft)' }} onMouseEnter={(e) => e.target.style.background = 'rgba(255,59,92,0.08)'} onMouseLeave={(e) => e.target.style.background = 'transparent'}>
                      Sign out →
                    </button>
                  </div>
                </div>
              )}
            </div> :

          <>
              <button className="btn btn-ghost btn-sm hide-mobile" onClick={() => onAuth('login')}>Sign In</button>
              <button className="btn btn-primary btn-sm btn-sheen" onClick={() => onAuth('signup')}>Get Started</button>
            </>
          }
          <button className="nav-burger" onClick={() => setOpen(!open)} aria-label="Menu">
            {open ?
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6" /></svg> :

            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 7h16M4 12h16M4 17h16" /></svg>
            }
          </button>
        </div>
      </div>
      <div className={`nav-mobile-drawer ${open ? 'open' : ''}`}>
        {links.map((l) =>
        <a key={l.id} className={`nav-link ${current === l.id ? 'active' : ''}`} onClick={() => handleNav(l.id)}>{l.label}</a>
        )}
        {user ? (
          <div className="flex-col gap-2 mt-4">
            <div className="panel" style={{ padding: 12 }}>
              <div style={{ fontWeight: 600 }}>{user.name}</div>
              <div className="font-mono text-xs text-muted mt-1">{user.email}</div>
            </div>
            <button className="btn btn-ghost" onClick={() => { setOpen(false); onSignOut?.(); }} style={{ color: 'var(--red)', borderColor: 'rgba(255,59,92,0.3)' }}>Sign out →</button>
          </div>
        ) : (
          <div className="flex gap-2 mt-4">
            <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => {setOpen(false);onAuth('login');}}>Sign In</button>
            <button className="btn btn-primary btn-sheen" style={{ flex: 1 }} onClick={() => {setOpen(false);onAuth('signup');}}>Get Started</button>
          </div>
        )}
      </div>
    </nav>);

}

/* ---------- Live Ticker ---------- */
function Ticker() {
  const pairs = [
  { p: 'EUR/USD', v: '1.08432', d: '+0.12%', up: true },
  { p: 'GBP/USD', v: '1.27891', d: '-0.08%', up: false },
  { p: 'USD/JPY', v: '149.823', d: '+0.34%', up: true },
  { p: 'XAU/USD', v: '2384.12', d: '+0.92%', up: true },
  { p: 'BTC/USD', v: '67,432.10', d: '+2.41%', up: true },
  { p: 'USD/CHF', v: '0.90124', d: '-0.21%', up: false },
  { p: 'AUD/USD', v: '0.66782', d: '+0.18%', up: true },
  { p: 'NZD/USD', v: '0.61203', d: '-0.04%', up: false },
  { p: 'USD/CAD', v: '1.36421', d: '+0.07%', up: true },
  { p: 'ETH/USD', v: '3,284.50', d: '+1.82%', up: true }];

  const items = [...pairs, ...pairs];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {items.map((it, i) =>
        <span key={i} className="ticker-item">
            <span className="pair">{it.p}</span>
            <span>{it.v}</span>
            <span className={it.up ? 'up' : 'down'}>{it.up ? '▲' : '▼'} {it.d}</span>
          </span>
        )}
      </div>
    </div>);

}

/* ---------- Footer ---------- */
function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Logo />
            <EditableText id="footer.tagline" tag="p" style={{ color: 'var(--text-3)', maxWidth: 360, marginTop: 16, fontSize: 13 }}>
Algorithmic trading systems engineered for MetaTrader 5. Every Expert Advisor ships with a full backtest, .set files, and AI-agent guidance.
            </EditableText>
            <div className="flex gap-2 mt-4">
              {['MT5', 'VPS', '24/7'].map((b) => <span key={b} className="tag">{b}</span>)}
            </div>
            <div className="mt-6">
              <EditableText id="footer.follow" tag="h4" style={{ marginBottom: 12 }}>Follow us</EditableText>
              <SocialLinks size={42} showLabels={true} gap={8} />
            </div>
          </div>
          <div>
            <EditableText id="footer.col.product" tag="h4">Product</EditableText>
            <a className="footer-link" onClick={() => go('marketplace')}><EditableText id="footer.product.marketplace" tag="span">Marketplace</EditableText></a>
            <a className="footer-link" onClick={() => go('agent')}><EditableText id="footer.product.agent" tag="span">AI Agent</EditableText></a>
            <a className="footer-link" onClick={() => go('dashboard')}><EditableText id="footer.product.dashboard" tag="span">Dashboard</EditableText></a>
          </div>
          <div>
            <EditableText id="footer.col.company" tag="h4">Company</EditableText>
            <a className="footer-link" onClick={() => go('about')}><EditableText id="footer.company.about" tag="span">About</EditableText></a>
            <a className="footer-link" onClick={() => go('about')}><EditableText id="footer.company.contact" tag="span">Contact</EditableText></a>
            <a className="footer-link"><EditableText id="footer.company.docs" tag="span">Documentation</EditableText></a>
            <a className="footer-link"><EditableText id="footer.company.reports" tag="span">Backtest Reports</EditableText></a>
          </div>
          <div>
            <EditableText id="footer.col.legal" tag="h4">Legal</EditableText>
            <a className="footer-link"><EditableText id="footer.legal.risk" tag="span">Risk Disclosure</EditableText></a>
            <a className="footer-link"><EditableText id="footer.legal.tos" tag="span">Terms of Service</EditableText></a>
            <a className="footer-link"><EditableText id="footer.legal.privacy" tag="span">Privacy Policy</EditableText></a>
            <a className="footer-link"><EditableText id="footer.legal.refund" tag="span">Refund Policy</EditableText></a>
          </div>
        </div>
        <div className="footer-bottom">
          <EditableText id="footer.copyright" tag="span">© 2026 EXPERT FOR FOREX SYSTEMS // ALL RIGHTS RESERVED</EditableText>
          <span></span>
        </div>
      </div>
    </footer>);

}

/* ---------- Equity Curve Chart ---------- */
function EquityCurve({ data, height = 200, color = '#00E5FF', showAxis = false, animated = true }) {
  const w = 800,h = height;
  const padX = showAxis ? 40 : 8,padY = 12;
  const min = Math.min(...data),max = Math.max(...data);
  const range = max - min || 1;
  const step = (w - padX * 2) / (data.length - 1);
  const pts = data.map((v, i) => [padX + i * step, h - padY - (v - min) / range * (h - padY * 2)]);
  const linePath = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p[0]} ${p[1]}`).join(' ');
  const areaPath = `${linePath} L ${pts[pts.length - 1][0]} ${h - padY} L ${pts[0][0]} ${h - padY} Z`;
  const gradId = useMemo(() => `eq-${Math.random().toString(36).slice(2, 8)}`, []);
  return (
    <svg className="chart-svg" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.4" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {showAxis && [0, 0.25, 0.5, 0.75, 1].map((y) =>
      <line key={y} x1={padX} x2={w - padX} y1={padY + y * (h - padY * 2)} y2={padY + y * (h - padY * 2)} stroke="rgba(255,255,255,0.04)" />
      )}
      <path d={areaPath} fill={`url(#${gradId})`} />
      <path d={linePath} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ filter: `drop-shadow(0 0 6px ${color})` }}>
        {animated && <animate attributeName="stroke-dasharray" from="0 5000" to="5000 0" dur="2s" fill="freeze" />}
      </path>
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="3" fill={color} />
    </svg>);

}

/* ---------- Donut / Win Rate ---------- */
function Donut({ value, color = '#00E5FF', size = 120, label, sub }) {
  const r = size / 2 - 10;
  const c = 2 * Math.PI * r;
  const off = c - value / 100 * c;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="6" />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth="6" strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round" style={{ filter: `drop-shadow(0 0 6px ${color})`, transition: 'stroke-dashoffset 1s' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
        <div>
          <div className="display" style={{ fontSize: 22, color }}>{value}%</div>
          {sub && <div className="font-mono text-xs text-muted">{sub}</div>}
        </div>
      </div>
    </div>);

}

/* ---------- Stat Card ---------- */
function StatCard({ label, value, delta, deltaColor = 'green', icon, accent = 'cyan' }) {
  return (
    <div className="panel panel-padded lift">
      <div className="flex-between mb-4">
        <span className="stat-label">{label}</span>
        {icon && <span style={{ color: `var(--${accent})`, opacity: 0.7 }}>{icon}</span>}
      </div>
      <div className={`stat-value ${accent}`}>{value}</div>
      {delta &&
      <div className={`stat-delta mt-2 text-${deltaColor}`}>
          {delta}
        </div>
      }
    </div>);

}

/* ---------- Bars chart ---------- */
function Bars({ data, height = 120, color = '#00E5FF' }) {
  const max = Math.max(...data.map((d) => Math.abs(d.v)));
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height, padding: '8px 0' }}>
      {data.map((d, i) => {
        const positive = d.v >= 0;
        const c = positive ? 'var(--green)' : 'var(--red)';
        return (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
            <div style={{
              width: '100%',
              height: `${Math.abs(d.v) / max * (height - 24)}px`,
              background: c,
              opacity: 0.85,
              borderRadius: 2,
              boxShadow: `0 0 8px ${c}`,
              transition: 'height 0.5s'
            }} />
            <span className="font-mono text-xs text-muted" style={{ fontSize: 9 }}>{d.l}</span>
          </div>);

      })}
    </div>);

}

/* ---------- Heatmap ---------- */
function Heatmap({ data }) {
  const max = Math.max(...data.map((d) => d.v));
  return (
    <div className="grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
      {data.map((d, i) => {
        const intensity = d.v / max;
        return (
          <div key={i} style={{
            padding: 12,
            borderRadius: 8,
            background: `linear-gradient(135deg, rgba(0,255,148,${intensity * 0.35}) 0%, rgba(0,229,255,${intensity * 0.15}) 100%)`,
            border: `1px solid rgba(0,255,148,${intensity * 0.5})`
          }}>
            <div className="font-mono text-xs text-muted">{d.pair}</div>
            <div className="display" style={{ fontSize: 18, color: 'var(--green)', marginTop: 4 }}>+${d.v}</div>
          </div>);

      })}
    </div>);

}

/* ---------- Animated number ---------- */
function CountUp({ to, prefix = '', suffix = '', decimals = 0, duration = 1200 }) {
  const [v, setV] = useState(0);
  useEffect(() => {
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(to * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [to]);
  return <span className="count-up">{prefix}{v.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}{suffix}</span>;
}

/* ---------- Background scaffolding ---------- */
function NeonBackground() {
  return (
    <>
      <div className="orb orb-1" />
      <div className="orb orb-2" />
      <div className="orb orb-3" />
      <div className="grid-bg" />
      <div className="scanlines" />
    </>);

}

/* ---------- Modal ---------- */
function Modal({ children, onClose }) {
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>);

}

/* ---------- Buy Widget — shared across pages ---------- */
function BuyWidget({ ea, onBuy, compact }) {
  const tiers = (ea.licenses && ea.licenses.length)
    ? ea.licenses
    : [
        { label: 'One month', months: 1, price: 150 },
        { label: '6 months', months: 6, price: 500 },
        { label: '12 months', months: 12, price: 800 },
      ];
  // Default-select the best-value tier (longest term)
  const [sel, setSel] = React.useState(tiers.length - 1);
  const chosen = tiers[Math.min(sel, tiers.length - 1)];

  return (
    <div className={`panel panel-glow ${compact ? '' : 'panel-padded-lg'}`} style={compact ? { padding: 20 } : {}}>
      <div className="flex-between mb-4">
        <span className="stat-label">License Plan</span>
        <div className="text-right">
          <span className="tag tag-green">VERIFIED</span>
          <div className="font-mono text-xs text-muted mt-2">{ea.users} active users</div>
        </div>
      </div>

      <div className="flex-col gap-2 mb-4">
        {tiers.map((t, i) => {
          const active = i === sel;
          return (
            <button
              key={i}
              onClick={() => setSel(i)}
              className="flex-between"
              style={{
                width: '100%', textAlign: 'left', cursor: 'pointer',
                padding: compact ? '10px 14px' : '14px 16px',
                borderRadius: 10,
                border: active ? '1px solid var(--cyan)' : '1px solid var(--line)',
                background: active ? 'rgba(0,229,255,0.07)' : 'transparent',
                boxShadow: active ? '0 0 16px rgba(0,229,255,0.18) inset' : 'none',
                transition: 'all .15s ease',
              }}>
              <span className="flex gap-3" style={{ alignItems: 'center' }}>
                <span style={{
                  width: 16, height: 16, borderRadius: '50%', flexShrink: 0,
                  border: active ? '5px solid var(--cyan)' : '2px solid var(--text-3)',
                  transition: 'all .15s ease',
                }} />
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: compact ? 14 : 16, color: active ? 'var(--text)' : 'var(--text-2)' }}>{t.label}</span>
              </span>
              <span className="display" style={{ fontSize: compact ? 18 : 22, color: active ? 'var(--cyan)' : 'var(--text-2)', textShadow: active ? '0 0 14px rgba(0,229,255,0.4)' : 'none' }}>
                ${t.price}
              </span>
            </button>);
        })}
      </div>

      <div className="divider" />
      <button className="btn btn-primary btn-block btn-lg btn-sheen" onClick={() => onBuy({ ...ea, price: chosen.price, selectedLicense: chosen })}>
        Buy {chosen.label} · ${chosen.price} →
      </button>
      <div className="flex gap-2 mt-4 text-xs text-muted font-mono" style={{ justifyContent: 'center', flexWrap: 'wrap' }}>
        <span>USDT</span><span>·</span><span>BTC</span><span>·</span><span>BINANCE PAY</span><span>·</span><span>APPLE PAY</span>
      </div>
    </div>);

}

/* ---------- Inline mini analytics — appears on every buy page ---------- */
function InlineAnalytics({ ea }) {
  return (
    <div className="panel panel-padded">
      <div className="flex-between mb-4">
        <div className="flex gap-3" style={{ alignItems: 'center' }}>
          <span className="eyebrow" style={{ margin: 0 }}>Backtest Results · 12 Months</span>
        </div>
        <span className="font-mono text-xs text-muted">ICMarkets tick data · independently verified</span>
      </div>
      <div className="grid grid-4 mb-6">
        <div>
          <span className="stat-label">Win Rate</span>
          <div className="stat-value cyan" style={{ fontSize: 22 }}><CountUp to={ea.winRate} decimals={1} suffix="%" /></div>
        </div>
        <div>
          <span className="stat-label">Profit Factor</span>
          <div className="stat-value green" style={{ fontSize: 22 }}><CountUp to={ea.pf} decimals={2} /></div>
        </div>
        <div>
          <span className="stat-label">Max DD</span>
          <div className="stat-value red" style={{ fontSize: 22 }}><CountUp to={ea.dd} decimals={1} suffix="%" /></div>
        </div>
        <div>
          <span className="stat-label">Risk Score</span>
          <div className="stat-value" style={{ fontSize: 22, color: ea.risk < 4 ? 'var(--green)' : ea.risk < 7 ? 'var(--amber)' : 'var(--red)' }}>
            <CountUp to={ea.risk} decimals={1} /><span style={{ fontSize: 14, color: 'var(--text-3)' }}>/10</span>
          </div>
        </div>
      </div>
      <div style={{ height: 140 }}>
        <EquityCurve data={ea.curve} height={140} showAxis={false} />
      </div>
    </div>);

}

/* ---------- Glitch text ---------- */
function GlitchText({ children }) {
  return <span className="glitch" data-text={children}>{children}</span>;
}

/* ---------- Export to global scope for other JSX files ---------- */
Object.assign(window, {
  Logo, Nav, Ticker, Footer, EquityCurve, Donut, StatCard, Bars, Heatmap,
  CountUp, NeonBackground, Modal, BuyWidget, InlineAnalytics, GlitchText
});