// Strategies — mirrors apps/web/src/app/(dashboard)/strategies/page.tsx.
// Lists strategies as cards. "New strategy" flip shows the create form.

window.Strategies = function Strategies({ goto }) {
  const { useState } = React;
  const [mode, setMode] = useState('list'); // 'list' | 'new'
  const list = window.useApi(() => window.EQ_API.getStrategies(true), []);

  if (mode === 'new') {
    return <NewStrategyForm onCancel={() => setMode('list')} onCreated={() => { setMode('list'); list.reload(); }}/>;
  }

  return (
    <div>
      <window.TopBar
        title="Strategies"
        subtitle={list.loading ? 'Loading…' : `${list.data?.data?.length ?? 0} total`}
        right={
          <button onClick={() => setMode('new')} style={{
            padding: '8px 16px', fontSize: 12.5, fontWeight: 500,
            background: 'var(--ink-900)', color: 'white', borderRadius: 7,
            border: 'none', cursor: 'pointer', fontFamily: 'inherit'
          }}>+ New strategy</button>
        }
      />
      <div style={{ padding: '24px 32px' }}>
        {list.error && <window.ErrorBanner error={list.error} onRetry={list.reload}/>}
        {list.loading && <div style={{ color: 'var(--ink-500)', fontSize: 12.5 }}>Loading…</div>}
        {!list.loading && !list.error && (
          !(list.data?.data?.length)
            ? <window.EmptyState title="No strategies yet" hint="Create a strategy to screen tickers on a recurring cadence."/>
            : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 12 }}>
                {list.data.data.map(s => <StrategyCard key={s.id} s={s}/>)}
              </div>
            )
        )}
      </div>
    </div>
  );
};

function StrategyCard({ s }) {
  return (
    <div style={{
      background: 'var(--paper)', border: '1px solid var(--ink-150)',
      borderRadius: 12, padding: '16px 18px',
      display: 'flex', flexDirection: 'column', gap: 8
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', gap: 8 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)' }}>{s.name || '—'}</div>
        <span style={{
          padding: '2px 8px', fontSize: 10.5, borderRadius: 999,
          background: s.is_active ? 'var(--buy-soft)' : 'var(--ink-100)',
          color: s.is_active ? 'var(--buy)' : 'var(--ink-500)',
          fontFamily: 'var(--font-mono)', fontWeight: 600, letterSpacing: '0.02em'
        }}>{s.is_active ? 'ACTIVE' : 'INACTIVE'}</span>
      </div>
      {s.description && <div style={{ fontSize: 12.5, color: 'var(--ink-600)', lineHeight: 1.5 }}>{s.description}</div>}
      <div style={{ display: 'flex', gap: 20, marginTop: 4, fontSize: 11, color: 'var(--ink-500)' }}>
        <div>Re-run ≥ <span style={{ color: 'var(--ink-800)', fontFamily: 'var(--font-mono)' }}>{s.rerun_days ?? '—'}d</span></div>
        <div>Price Δ <span style={{ color: 'var(--ink-800)', fontFamily: 'var(--font-mono)' }}>{s.price_change_threshold != null ? s.price_change_threshold + '%' : '—'}</span></div>
        <div>Last screen <span style={{ color: 'var(--ink-800)', fontFamily: 'var(--font-mono)' }}>{window.formatDate(s.last_screen_at)}</span></div>
      </div>
    </div>
  );
}

function NewStrategyForm({ onCancel, onCreated }) {
  const { useState } = React;
  const [form, setForm] = useState({
    name: '', description: '',
    min_market_cap: '', max_market_cap: '',
    min_price: '', max_price: '',
    sectors: [],
    rerun_days: 90,
    price_change_threshold: 20,
  });
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const setNum = (k) => (e) => setForm({ ...form, [k]: e.target.value === '' ? '' : Number(e.target.value) });

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setError(null);
    try {
      const body = { ...form };
      ['min_market_cap','max_market_cap','min_price','max_price'].forEach(k => { if (body[k] === '') body[k] = null; });
      await window.EQ_API.createStrategy(body);
      onCreated();
    } catch (err) {
      setError(err.message || 'Create failed');
    } finally { setBusy(false); }
  };

  return (
    <div>
      <window.TopBar title="New strategy" right={<button onClick={onCancel} style={{
        background: 'transparent', border: 'none', color: 'var(--ink-600)', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit'
      }}>← Cancel</button>}/>
      <form onSubmit={submit} style={{ padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 640 }}>
        {error && <window.ErrorBanner error={{ message: error }}/>}
        <Field label="Name">
          <input required value={form.name} onChange={set('name')} style={inputStyle}/>
        </Field>
        <Field label="Description">
          <textarea rows={3} value={form.description} onChange={set('description')} style={{ ...inputStyle, resize: 'vertical' }}/>
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Min market cap (USD)"><input type="number" value={form.min_market_cap} onChange={setNum('min_market_cap')} style={inputStyle}/></Field>
          <Field label="Max market cap (USD)"><input type="number" value={form.max_market_cap} onChange={setNum('max_market_cap')} style={inputStyle}/></Field>
          <Field label="Min price (USD)"><input type="number" value={form.min_price} onChange={setNum('min_price')} style={inputStyle}/></Field>
          <Field label="Max price (USD)"><input type="number" value={form.max_price} onChange={setNum('max_price')} style={inputStyle}/></Field>
          <Field label="Re-run after (days)"><input type="number" value={form.rerun_days} onChange={setNum('rerun_days')} style={inputStyle}/></Field>
          <Field label="Price change threshold (%)"><input type="number" value={form.price_change_threshold} onChange={setNum('price_change_threshold')} style={inputStyle}/></Field>
        </div>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
          <button type="button" onClick={onCancel} style={{ padding: '8px 16px', fontSize: 12.5, background: 'transparent', color: 'var(--ink-600)', border: '1px solid var(--ink-200)', borderRadius: 7, cursor: 'pointer', fontFamily: 'inherit' }}>Cancel</button>
          <button type="submit" disabled={busy} style={{ padding: '8px 16px', fontSize: 12.5, fontWeight: 500, background: 'var(--ink-900)', color: 'white', borderRadius: 7, border: 'none', cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.6 : 1, fontFamily: 'inherit' }}>
            {busy ? 'Creating…' : 'Create strategy'}
          </button>
        </div>
      </form>
    </div>
  );
}

const inputStyle = {
  width: '100%', padding: '8px 12px', fontSize: 13,
  background: 'var(--ink-100)', border: '1px solid var(--ink-200)',
  borderRadius: 7, outline: 'none', color: 'var(--ink-900)', fontFamily: 'inherit'
};

function Field({ label, children }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontSize: 11, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500, marginBottom: 5 }}>{label}</div>
      {children}
    </label>
  );
}
