// Shared UI components used across Apex Algo variations.
// Each variation may override tokens (colors, fonts) via props/context,
// but structure + interactivity live here.

window.ApexUI = (function () {
  const { useState, useRef, useEffect, useMemo } = React;

  // Minimal apply-for-license modal — multi-step, client-side only.
  function ApplyModal({ open, onClose, theme }) {
    const [step, setStep] = useState(0);
    const [form, setForm] = useState({
      name: '', email: '', capital: '50k-250k', venues: [], experience: 'retail-systematic', notes: '',
    });
    const [submitted, setSubmitted] = useState(false);

    useEffect(() => {
      if (!open) return;
      function onKey(e) { if (e.key === 'Escape') onClose(); }
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
    }, [open, onClose]);

    if (!open) return null;

    const t = theme || {};
    const bg = t.surface || '#0F1114';
    const border = t.border || 'rgba(255,255,255,0.08)';
    const fg = t.fg || '#E7E9EC';
    const dim = t.dim || 'rgba(231,233,236,0.55)';
    const accent = t.accent || '#00D4C8';
    const mono = t.mono || 'ui-monospace, SFMono-Regular, Menlo, monospace';

    function toggleVenue(v) {
      setForm(f => ({ ...f, venues: f.venues.includes(v) ? f.venues.filter(x => x !== v) : [...f.venues, v] }));
    }

    function submit() {
      setSubmitted(true);
    }

    const steps = ['Contact', 'Profile', 'Review'];

    return (
      <div style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(4px)',
        zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
      }} onClick={onClose}>
        <div onClick={e => e.stopPropagation()} style={{
          width: 'min(560px, 100%)', background: bg, border: `1px solid ${border}`, borderRadius: 4,
          color: fg, fontFamily: t.sans || 'system-ui, sans-serif',
        }}>
          {submitted ? (
            <div style={{ padding: 40, textAlign: 'center' }}>
              <div style={{ width: 40, height: 40, borderRadius: '50%', border: `1.5px solid ${accent}`, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="2"><polyline points="20 6 9 17 4 12" /></svg>
              </div>
              <div style={{ fontSize: 18, marginBottom: 8 }}>Application received</div>
              <div style={{ color: dim, fontSize: 14, lineHeight: 1.5, maxWidth: 360, margin: '0 auto' }}>
                We review applications within 2 business days. You'll hear from us at <span style={{ color: fg, fontFamily: mono }}>{form.email || 'your email'}</span>.
              </div>
              <button onClick={onClose} style={{ marginTop: 24, background: 'transparent', color: fg, border: `1px solid ${border}`, padding: '8px 18px', borderRadius: 2, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>Close</button>
            </div>
          ) : (
            <>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '18px 22px', borderBottom: `1px solid ${border}` }}>
                <div style={{ fontSize: 13, letterSpacing: '0.12em', textTransform: 'uppercase', fontFamily: mono, color: dim }}>Start 14-day free trial</div>
                <button onClick={onClose} aria-label="Close" style={{ background: 'transparent', color: dim, border: 'none', cursor: 'pointer', fontSize: 18, lineHeight: 1 }}>×</button>
              </div>
              <div style={{ display: 'flex', gap: 4, padding: '14px 22px 0' }}>
                {steps.map((s, i) => (
                  <div key={s} style={{ flex: 1, height: 2, background: i <= step ? accent : border, transition: 'background 0.2s' }} />
                ))}
              </div>
              <div style={{ padding: '18px 22px 22px', fontSize: 14, lineHeight: 1.55 }}>
                {step === 0 && (
                  <div>
                    <Field label="Name" theme={t}>
                      <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Your full name" style={inputStyle(t)} />
                    </Field>
                    <Field label="Email" theme={t}>
                      <input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="name@domain.com" style={inputStyle(t)} />
                    </Field>
                  </div>
                )}
                {step === 1 && (
                  <div>
                    <Field label="Capital to deploy" theme={t}>
                      <select value={form.capital} onChange={e => setForm({ ...form, capital: e.target.value })} style={inputStyle(t)}>
                        <option value="50k-250k">$50k – $250k</option>
                        <option value="250k-1m">$250k – $1M</option>
                        <option value="1m-5m">$1M – $5M</option>
                        <option value="5m+">$5M+</option>
                      </select>
                    </Field>
                    <Field label="Venues of interest" theme={t}>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                        {['Hyperliquid (crypto)', 'Interactive Brokers'].map(v => (
                          <button key={v} onClick={() => toggleVenue(v)} style={{
                            background: form.venues.includes(v) ? accent : 'transparent',
                            color: form.venues.includes(v) ? '#0A0B0D' : fg,
                            border: `1px solid ${form.venues.includes(v) ? accent : border}`,
                            padding: '7px 12px', fontSize: 12, borderRadius: 2, cursor: 'pointer', fontFamily: 'inherit',
                          }}>{v}</button>
                        ))}
                      </div>
                    </Field>
                    <Field label="Systematic trading experience" theme={t}>
                      <select value={form.experience} onChange={e => setForm({ ...form, experience: e.target.value })} style={inputStyle(t)}>
                        <option value="none">New to systematic trading</option>
                        <option value="retail-systematic">Retail, some systematic experience</option>
                        <option value="professional">Professional / small fund</option>
                      </select>
                    </Field>
                  </div>
                )}
                {step === 2 && (
                  <div style={{ fontFamily: mono, fontSize: 12.5, color: dim, lineHeight: 1.75 }}>
                    <Row k="Name"     v={form.name || '—'} fg={fg} />
                    <Row k="Email"    v={form.email || '—'} fg={fg} />
                    <Row k="Capital"  v={form.capital} fg={fg} />
                    <Row k="Venues"   v={form.venues.join(', ') || '—'} fg={fg} />
                    <Row k="Experience" v={form.experience} fg={fg} />
                    <div style={{ marginTop: 14, paddingTop: 14, borderTop: `1px solid ${border}`, color: dim, fontFamily: t.sans || 'system-ui' }}>
                      Submitting forwards this to <span style={{ color: fg, fontFamily: mono }}>access@theapexalgo.com</span>. Approved trials get dashboard access for 14 days — paper or live, your choice. No payment taken now.
                    </div>
                  </div>
                )}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '14px 22px', borderTop: `1px solid ${border}` }}>
                <button onClick={() => step > 0 ? setStep(step - 1) : onClose()}
                  style={{ background: 'transparent', color: dim, border: 'none', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>
                  {step > 0 ? '← Back' : 'Cancel'}
                </button>
                {step < 2 ? (
                  <button onClick={() => setStep(step + 1)}
                    disabled={step === 0 && (!form.name || !form.email)}
                    style={{ background: accent, color: '#0A0B0D', border: 'none', padding: '8px 18px', fontSize: 13, borderRadius: 2, cursor: 'pointer', fontWeight: 500, fontFamily: 'inherit', opacity: (step === 0 && (!form.name || !form.email)) ? 0.4 : 1 }}>
                    Continue
                  </button>
                ) : (
                  <button onClick={submit}
                    style={{ background: accent, color: '#0A0B0D', border: 'none', padding: '8px 18px', fontSize: 13, borderRadius: 2, cursor: 'pointer', fontWeight: 500, fontFamily: 'inherit' }}>
                    Request trial access
                  </button>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    );
  }

  function inputStyle(t) {
    return {
      width: '100%', background: 'transparent', color: t.fg || '#E7E9EC',
      border: `1px solid ${t.border || 'rgba(255,255,255,0.12)'}`, borderRadius: 2,
      padding: '9px 12px', fontSize: 13, outline: 'none', fontFamily: 'inherit',
      boxSizing: 'border-box',
    };
  }
  function Field({ label, children, theme }) {
    const t = theme || {};
    return (
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: t.dim || 'rgba(255,255,255,0.5)', fontFamily: t.mono, marginBottom: 6 }}>{label}</div>
        {children}
      </div>
    );
  }
  function Row({ k, v, fg }) {
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
        <span>{k}</span>
        <span style={{ color: fg, textAlign: 'right', maxWidth: '70%' }}>{v}</span>
      </div>
    );
  }

  // FAQ accordion
  function FAQ({ items, theme }) {
    const [open, setOpen] = useState(-1);
    const t = theme || {};
    return (
      <div style={{ borderTop: `1px solid ${t.border}` }}>
        {items.map((it, i) => {
          const isOpen = open === i;
          return (
            <div key={i} style={{ borderBottom: `1px solid ${t.border}` }}>
              <button onClick={() => setOpen(isOpen ? -1 : i)} style={{
                width: '100%', background: 'transparent', color: t.fg, border: 'none',
                padding: '18px 0', textAlign: 'left', fontSize: 15, cursor: 'pointer',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 20,
                fontFamily: 'inherit',
              }}>
                <span style={{ lineHeight: 1.4 }}>{it.q}</span>
                <span style={{ color: t.accent, fontSize: 16, fontFamily: t.mono, flexShrink: 0 }}>{isOpen ? '−' : '+'}</span>
              </button>
              {isOpen && (
                <div style={{ paddingBottom: 18, color: t.dim, fontSize: 14, lineHeight: 1.7, maxWidth: 720 }}>
                  {it.a}
                </div>
              )}
            </div>
          );
        })}
      </div>
    );
  }

  // Sortable pricing / strategy table
  function SortableStrategyTable({ data, theme, columns }) {
    const [sort, setSort] = useState({ key: 'sharpe', dir: 'desc' });
    const t = theme || {};
    const sorted = useMemo(() => {
      const out = [...data];
      out.sort((a, b) => {
        const av = a[sort.key], bv = b[sort.key];
        if (typeof av === 'number') return sort.dir === 'asc' ? av - bv : bv - av;
        return sort.dir === 'asc' ? String(av).localeCompare(String(bv)) : String(bv).localeCompare(String(av));
      });
      return out;
    }, [data, sort]);

    function click(key) {
      setSort(s => s.key === key ? { key, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { key, dir: 'desc' });
    }

    return (
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: t.mono, fontSize: 12.5 }}>
          <thead>
            <tr style={{ borderBottom: `1px solid ${t.border}` }}>
              {columns.map(c => (
                <th key={c.key} onClick={() => c.sortable !== false && click(c.key)} style={{
                  textAlign: c.align || 'left', padding: '10px 12px', color: t.dim,
                  fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
                  cursor: c.sortable !== false ? 'pointer' : 'default', userSelect: 'none', fontWeight: 400,
                  whiteSpace: 'nowrap',
                }}>
                  {c.label}
                  {sort.key === c.key && <span style={{ marginLeft: 4, color: t.accent }}>{sort.dir === 'asc' ? '↑' : '↓'}</span>}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {sorted.map((row, i) => (
              <tr key={row.id || i} style={{ borderBottom: `1px solid ${t.border}` }}>
                {columns.map(c => (
                  <td key={c.key} style={{ textAlign: c.align || 'left', padding: '11px 12px', color: c.color ? c.color(row) : t.fg }}>
                    {c.render ? c.render(row) : row[c.key]}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  // Comparison table vs alt categories (static data below)
  const COMPARISON = {
    rows: [
      { label: 'Pricing model',         apex: 'One-time $15,000',  signals: '$50–500 / month',      copy: '$50–300 / month + fees', quant: '$500–5,000 / month',    prop: 'Profit split 20–50%' },
      { label: 'Your capital stays yours', apex: true,              signals: true,                     copy: false,                      quant: true,                       prop: false },
      { label: 'You hold the API keys',  apex: true,              signals: false,                    copy: false,                      quant: 'Varies',                   prop: false },
      { label: 'Fully automated execution', apex: true,          signals: false,                    copy: true,                        quant: true,                       prop: true },
      { label: 'Live-account track record', apex: true,          signals: 'Rare',                   copy: 'Shared',                    quant: 'Often paper',              prop: 'Internal' },
      { label: 'Multi-asset, multi-TF',  apex: true,              signals: false,                    copy: 'Pair-dependent',            quant: 'Varies',                   prop: 'Varies' },
      { label: 'Lifetime updates',       apex: true,              signals: false,                    copy: false,                      quant: false,                     prop: false },
      { label: 'Lock-up / rules',        apex: 'None',             signals: 'None',                   copy: 'Vendor-driven',              quant: 'None',                    prop: 'Strict drawdown rules' },
    ],
    cols: ['apex', 'signals', 'copy', 'quant', 'prop'],
    colLabels: {
      apex: 'Apex Algo',
      signals: 'Signal / Discord',
      copy: 'Copy-trading',
      quant: 'Quant SaaS',
      prop: 'Prop firm',
    },
  };

  function ComparisonTable({ theme }) {
    const t = theme || {};
    function cell(v) {
      if (v === true)  return <span style={{ color: '#00C389', fontFamily: t.mono }}>●</span>;
      if (v === false) return <span style={{ color: 'rgba(255,255,255,0.18)', fontFamily: t.mono }}>—</span>;
      return <span style={{ color: t.fg, fontFamily: t.mono, fontSize: 11.5 }}>{v}</span>;
    }
    return (
      <div style={{ overflowX: 'auto', border: `1px solid ${t.border}` }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: t.sans || 'system-ui' }}>
          <thead>
            <tr style={{ background: 'rgba(255,255,255,0.02)' }}>
              <th style={{ textAlign: 'left', padding: '12px 16px', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: t.dim, fontWeight: 400, fontFamily: t.mono, borderBottom: `1px solid ${t.border}` }}></th>
              {COMPARISON.cols.map(k => (
                <th key={k} style={{
                  textAlign: 'left', padding: '12px 16px', fontSize: 11, color: k === 'apex' ? t.accent : t.fg,
                  borderBottom: `1px solid ${t.border}`, fontWeight: 500, whiteSpace: 'nowrap',
                  borderLeft: k === 'apex' ? `1px solid ${t.accent}` : 'none',
                  borderRight: k === 'apex' ? `1px solid ${t.accent}` : 'none',
                  background: k === 'apex' ? 'rgba(0,212,200,0.04)' : 'transparent',
                }}>{COMPARISON.colLabels[k]}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {COMPARISON.rows.map((row, i) => (
              <tr key={i}>
                <td style={{ padding: '12px 16px', color: t.dim, fontSize: 13, borderBottom: `1px solid ${t.border}` }}>{row.label}</td>
                {COMPARISON.cols.map(k => (
                  <td key={k} style={{
                    padding: '12px 16px', fontSize: 13, color: t.fg, borderBottom: `1px solid ${t.border}`,
                    borderLeft: k === 'apex' ? `1px solid ${t.accent}` : 'none',
                    borderRight: k === 'apex' ? `1px solid ${t.accent}` : 'none',
                    background: k === 'apex' ? 'rgba(0,212,200,0.04)' : 'transparent',
                  }}>
                    {cell(row[k])}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  return { ApplyModal, FAQ, SortableStrategyTable, ComparisonTable };
})();
