// Tempo — Stratégies page (TradeSyncer-style)
// Hybrid model: the user creates named strategies (Supabase table `strategies`).
// Per-strategy stats are derived from trades whose `setup` field === strategy name.
// Exposes: StrategyPage({ state }), StrategyMobile({ state }).

// ─── Data: load strategies + per-strategy stat helpers ──────────────
function useStrategies(state) {
  const [rows, setRows] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  const load = React.useCallback(async () => {
    if (!window.sb) { setLoading(false); return; }
    setLoading(true);
    const { data, error } = await window.sb.from('strategies')
      .select('*').order('created_at', { ascending: false });
    if (error) {
      // PGRST205 = table missing (migration pas encore exécutée) → on reste silencieux.
      if (error.code !== 'PGRST205') console.warn('[Tempo] strategies load:', error.message);
      setError(error.code === 'PGRST205' ? 'missing' : error.message);
      setRows([]); setLoading(false);
      return;
    }
    setError(''); setRows(data || []); setLoading(false);
  }, []);

  React.useEffect(() => { load(); }, [load]);

  async function addStrategy({ name, rules }) {
    const trimmed = (name || '').trim();
    if (!trimmed) return { error: { message: 'Nom vide.' } };
    let uid = state?.user?.id;
    if (!uid && window.sb) {
      try { const { data } = await window.sb.auth.getUser(); uid = data?.user?.id; } catch (e) {}
    }
    if (!uid) return { error: { message: 'Tu dois être connecté.' } };
    const row = { user_id: uid, name: trimmed, rules: (rules || '').trim() || null };
    const { data, error } = await window.sb.from('strategies').insert(row).select().single();
    if (error) { console.error('[Tempo] addStrategy', error); return { error }; }
    setRows(prev => [data, ...prev]);
    return { data };
  }

  async function removeStrategy(id) {
    setRows(prev => prev.filter(r => r.id !== id));
    const { error } = await window.sb.from('strategies').delete().eq('id', id);
    if (error) { console.error('[Tempo] removeStrategy', error); load(); }
  }

  return { rows, loading, error, addStrategy, removeStrategy, reload: load };
}

// Aggregate per-strategy stats from the trades already loaded in app state.
// A trade belongs to a strategy when t.setup === strategy.name.
function useStrategyStats(strategies, trades) {
  return React.useMemo(() => {
    const bySetup = {};
    for (const t of (trades || [])) {
      const key = (t.setup || '').trim();
      if (!key) continue;
      (bySetup[key] = bySetup[key] || []).push(t);
    }
    const map = {};
    for (const s of strategies) {
      const subset = bySetup[(s.name || '').trim()] || [];
      map[s.id] = computeStats(subset);
    }
    return map;
  }, [strategies, trades]);
}

// ─── SVG progress ring (win rate au centre) ─────────────────────────
function ProgressRing({ value = 0, size = 92, stroke = 8, count = 0 }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = Math.max(0, Math.min(100, value));
  const dash = (pct / 100) * c;
  // Couleur de l'anneau selon le win rate (aucune couleur en dur).
  const ringColor = count === 0 ? 'var(--fg-4)'
    : pct >= 50 ? 'var(--green)'
    : pct >= 35 ? 'var(--blue)'
    : 'var(--red)';
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line-2)" strokeWidth={stroke} />
        <circle
          cx={size / 2} cy={size / 2} r={r} fill="none"
          stroke={ringColor} strokeWidth={stroke} strokeLinecap="round"
          strokeDasharray={`${dash} ${c}`}
          style={{ transition: 'stroke-dasharray .6s var(--ease)' }}
        />
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
      }}>
        <span className="num" style={{ fontSize: size * 0.26, fontWeight: 700, letterSpacing: '-.02em', lineHeight: 1 }}>
          {count === 0 ? '—' : Math.round(pct) + '%'}
        </span>
        <span style={{ fontSize: 9.5, color: 'var(--fg-3)', fontWeight: 500, marginTop: 2 }}>Win rate</span>
      </div>
    </div>
  );
}

// ─── Mini ligne de stat (Gains / Pertes / Total) ────────────────────
function StatLine({ label, value, tone }) {
  const color = tone === 'green' ? 'var(--green-text)' : tone === 'red' ? 'var(--red-text)' : 'var(--fg)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0' }}>
      <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>{label}</span>
      <span className="num" style={{ fontSize: 13, fontWeight: 600, color }}>{value}</span>
    </div>
  );
}

// ─── Formulaire "Nouvelle stratégie" (inline / sheet) ───────────────
function StrategyForm({ onSubmit, onCancel, busy }) {
  const [name, setName] = React.useState('');
  const [rules, setRules] = React.useState('');
  const [err, setErr] = React.useState('');
  const submit = async (e) => {
    e && e.preventDefault();
    if (!name.trim()) { setErr('Donne un nom à ta stratégie.'); return; }
    setErr('');
    const res = await onSubmit({ name, rules });
    if (res?.error) { setErr(res.error.message || 'Erreur lors de la création.'); return; }
    setName(''); setRules('');
  };
  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div>
        <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>Nom de la stratégie</label>
        <input
          autoFocus value={name} onChange={e => setName(e.target.value)}
          placeholder="Ex. ORB 5min, Breakout NQ…" className="input"
          style={{ width: '100%' }}
        />
      </div>
      <div>
        <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-2)', display: 'block', marginBottom: 6 }}>Règles (optionnel)</label>
        <textarea
          value={rules} onChange={e => setRules(e.target.value)}
          placeholder="Conditions d'entrée, gestion du risque, sortie…" className="input"
          rows={3} style={{ width: '100%', resize: 'vertical', lineHeight: 1.5, fontFamily: 'inherit' }}
        />
      </div>
      <div style={{ fontSize: 11, color: 'var(--fg-3)', background: 'var(--blue-soft)', border: '1px solid var(--blue-border)', borderRadius: 8, padding: '8px 10px' }}>
        Les stats sont calculées sur les trades dont le champ <span className="mono" style={{ color: 'var(--blue-600)' }}>setup</span> correspond exactement au nom de la stratégie.
      </div>
      {err && <div style={{ fontSize: 12, color: 'var(--red-text)' }}>{err}</div>}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <button type="button" onClick={onCancel} className="btn btn-outline-blue tap" style={{ borderColor: 'var(--line)', color: 'var(--fg-2)' }}>Annuler</button>
        <button type="submit" disabled={busy} className="btn btn-blue tap">{busy ? 'Création…' : 'Créer la stratégie'}</button>
      </div>
    </form>
  );
}

// ─── Carte d'une stratégie ──────────────────────────────────────────
function StrategyCard({ s, st, onDelete, compact }) {
  const [confirm, setConfirm] = React.useState(false);
  const total = st.count || 0;
  const pf = Number.isFinite(st.profitFactor) ? st.profitFactor : (st.profitFactor === Infinity ? '∞' : 0);
  return (
    <div className="card lift" style={{ padding: compact ? 16 : 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Header: nom + supprimer */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-.015em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
          {s.rules
            ? <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 3, lineHeight: 1.4, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{s.rules}</div>
            : <div style={{ fontSize: 11.5, color: 'var(--fg-4)', marginTop: 3 }}>Aucune règle définie</div>}
        </div>
        {confirm ? (
          <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
            <button onClick={() => { onDelete(s.id); }} className="tap" title="Confirmer la suppression"
              style={{ height: 28, padding: '0 10px', borderRadius: 7, border: 'none', background: 'var(--red-soft)', color: 'var(--red-text)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer' }}>Supprimer</button>
            <button onClick={() => setConfirm(false)} className="tap" title="Annuler"
              style={{ width: 28, height: 28, borderRadius: 7, border: '1px solid var(--line)', background: 'var(--bg-card)', color: 'var(--fg-3)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{Ico.x}</button>
          </div>
        ) : (
          <button onClick={() => setConfirm(true)} className="tap" title="Supprimer la stratégie"
            style={{ width: 28, height: 28, borderRadius: 7, border: '1px solid var(--line)', background: 'var(--bg-card)', color: 'var(--fg-3)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg className="ico" width="14" height="14" viewBox="0 0 16 16"><path d="M3 4h10M6.5 4V2.5h3V4M5 4l.6 9h4.8L11 4"/></svg>
          </button>
        )}
      </div>

      {/* Corps: anneau + stats lignes */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <ProgressRing value={st.winRate} count={total} size={compact ? 84 : 92} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <StatLine label="Gains" value={total === 0 ? '—' : st.wins} tone={st.wins > 0 ? 'green' : null} />
          <div style={{ height: 1, background: 'var(--line)' }} />
          <StatLine label="Pertes" value={total === 0 ? '—' : st.losses} tone={st.losses > 0 ? 'red' : null} />
          <div style={{ height: 1, background: 'var(--line)' }} />
          <StatLine label="Total trades" value={total} />
        </div>
      </div>

      {/* Footer: Profit Factor + Total P&L */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 12, borderTop: '1px solid var(--line)' }}>
        <div>
          <div style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '.04em', fontWeight: 600 }}>PROFIT FACTOR</div>
          <div className="num" style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>
            {total === 0 ? '—' : (pf === '∞' ? '∞' : (typeof pf === 'number' ? pf.toFixed(2) : pf))}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '.04em', fontWeight: 600 }}>TOTAL P&amp;L</div>
          <div className={'num ' + (st.netPnl >= 0 ? 'pos' : 'neg')} style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-.02em', marginTop: 2 }}>
            {total === 0 ? '—' : fmtMoney(st.netPnl, true)}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── État vide ──────────────────────────────────────────────────────
function StrategyEmpty({ onCreate, compact }) {
  return (
    <div className="card" style={{ padding: compact ? '40px 20px' : '56px 24px', textAlign: 'center' }}>
      <div style={{ width: 48, height: 48, borderRadius: 12, background: 'var(--blue-soft)', color: 'var(--blue-600)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
        {Ico.strategy}
      </div>
      <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>Aucune stratégie créée</div>
      <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginBottom: 18, maxWidth: 320, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.5 }}>
        Crée une stratégie pour suivre ses performances. Tag tes trades avec le même nom dans le champ <span className="mono" style={{ color: 'var(--fg-2)' }}>setup</span> pour alimenter ses stats.
      </div>
      <button onClick={onCreate} className="btn btn-blue tap">{Ico.plus} Nouvelle stratégie</button>
    </div>
  );
}

// ─── Migration manquante ────────────────────────────────────────────
function StrategyMigrationNote() {
  return (
    <div className="card" style={{ padding: '24px', textAlign: 'center' }}>
      <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Table « strategies » introuvable</div>
      <div style={{ fontSize: 12.5, color: 'var(--fg-3)', lineHeight: 1.5 }}>
        Exécute la migration SQL fournie dans Supabase pour activer les stratégies.
      </div>
    </div>
  );
}

// ─── Desktop ────────────────────────────────────────────────────────
function StrategyPage({ state }) {
  const st = state || {};
  const trades = st.trades || [];
  const { rows, loading, error, addStrategy, removeStrategy } = useStrategies(st);
  const statsById = useStrategyStats(rows, trades);
  const [showForm, setShowForm] = React.useState(false);
  const [busy, setBusy] = React.useState(false);

  const handleCreate = async (payload) => {
    setBusy(true);
    const res = await addStrategy(payload);
    setBusy(false);
    if (!res?.error) setShowForm(false);
    return res;
  };

  // Total P&L cumulé sur toutes les stratégies (trades taggés).
  const totals = React.useMemo(() => {
    let pnl = 0, count = 0;
    for (const s of rows) { const x = statsById[s.id]; if (x) { pnl += x.netPnl; count += x.count; } }
    return { pnl, count };
  }, [rows, statsById]);

  return (
    <div className="scroll" style={{ width: '100%', height: '100%', overflow: 'auto' }}>
      <PageHeader title="Stratégies" />
      <div style={{ padding: '20px 24px 40px' }}>
        {/* Barre titre + action */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 18 }}>
          <div>
            <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-.025em', margin: 0 }}>Stratégies</h1>
            <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 4 }}>
              {rows.length > 0
                ? `${rows.length} stratégie${rows.length > 1 ? 's' : ''} · ${totals.count} trade${totals.count > 1 ? 's' : ''} taggé${totals.count > 1 ? 's' : ''}`
                : 'Suis la performance de chacune de tes approches'}
            </div>
          </div>
          {!showForm && error !== 'missing' && (
            <button onClick={() => setShowForm(true)} className="btn btn-blue tap">{Ico.plus} Nouvelle stratégie</button>
          )}
        </div>

        {/* Formulaire inline */}
        {showForm && (
          <div className="card stagger" style={{ padding: 18, marginBottom: 18, maxWidth: 520 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>Nouvelle stratégie</div>
            <StrategyForm onSubmit={handleCreate} onCancel={() => setShowForm(false)} busy={busy} />
          </div>
        )}

        {/* Contenu */}
        {error === 'missing' ? (
          <StrategyMigrationNote />
        ) : loading ? (
          <div className="card" style={{ padding: '32px 20px', textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Chargement des stratégies…</div>
        ) : rows.length === 0 ? (
          (!showForm && <StrategyEmpty onCreate={() => setShowForm(true)} />)
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 16 }}>
            {rows.map(s => (
              <StrategyCard key={s.id} s={s} st={statsById[s.id] || computeStats([])} onDelete={removeStrategy} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Mobile ─────────────────────────────────────────────────────────
function StrategyMobile({ state }) {
  const st = state || {};
  const trades = st.trades || [];
  const { rows, loading, error, addStrategy, removeStrategy } = useStrategies(st);
  const statsById = useStrategyStats(rows, trades);
  const [sheet, setSheet] = React.useState(false);
  const [busy, setBusy] = React.useState(false);

  const handleCreate = async (payload) => {
    setBusy(true);
    const res = await addStrategy(payload);
    setBusy(false);
    if (!res?.error) setSheet(false);
    return res;
  };

  return (
    <div style={{ padding: '14px 20px 24px', position: 'relative' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-.025em', margin: 0 }}>Stratégies</h1>
        {error !== 'missing' && (
          <button onClick={() => setSheet(true)} className="btn btn-blue tap" style={{ fontSize: 12 }}>{Ico.plus} Nouvelle</button>
        )}
      </div>

      {error === 'missing' ? (
        <StrategyMigrationNote />
      ) : loading ? (
        <div className="card" style={{ padding: '28px 16px', textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Chargement…</div>
      ) : rows.length === 0 ? (
        <StrategyEmpty onCreate={() => setSheet(true)} compact />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {rows.map(s => (
            <StrategyCard key={s.id} s={s} st={statsById[s.id] || computeStats([])} onDelete={removeStrategy} compact />
          ))}
        </div>
      )}

      {/* Bottom sheet */}
      {sheet && (
        <div
          onClick={() => setSheet(false)}
          style={{ position: 'fixed', inset: 0, zIndex: 50, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'flex-end' }}
        >
          <div
            onClick={e => e.stopPropagation()}
            className="stagger"
            style={{
              width: '100%', background: 'var(--bg-card)', borderTopLeftRadius: 18, borderTopRightRadius: 18,
              borderTop: '1px solid var(--line)', padding: '18px 20px calc(20px + env(safe-area-inset-bottom))',
              maxHeight: '85vh', overflowY: 'auto',
            }}
          >
            <div style={{ width: 36, height: 4, borderRadius: 2, background: 'var(--line-2)', margin: '0 auto 16px' }} />
            <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 14 }}>Nouvelle stratégie</div>
            <StrategyForm onSubmit={handleCreate} onCancel={() => setSheet(false)} busy={busy} />
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { StrategyPage, StrategyMobile });
