/* ═══════════════════════════════════════════════════════════════
   SIGNAUX + VOLATILE screens
   ═══════════════════════════════════════════════════════════════ */

const { useState: useStateSig } = React;

function SignauxScreen({ onAction, stateShowcase = "active" }) {
  const { SIGNALS } = window.MOCK;
  const [filter, setFilter] = useStateSig("all");

  const filtered = SIGNALS.filter(s => {
    if (filter === "all") return true;
    if (filter === "long") return s.direction === "LONG";
    if (filter === "short") return s.direction === "SHORT";
    if (filter === "premium") return s.score >= 8;
    if (filter === "volume") return s.volume > 100;
    if (filter === "usa") return true;
    return true;
  });

  if (stateShowcase === "loading") {
    return (
      <div className="page">
        <SignauxHeader filter={filter} setFilter={setFilter} />
        <div className="signals-grid">
          {[0,1,2,3].map(i => <SignalSkeleton key={i}/>)}
        </div>
      </div>
    );
  }
  if (stateShowcase === "empty") {
    return (
      <div className="page">
        <SignauxHeader filter={filter} setFilter={setFilter} />
        <EmptyState/>
      </div>
    );
  }
  if (stateShowcase === "error") {
    return (
      <div className="page">
        <div className="conn-lost">
          <Icon.AlertTriangle size={14}/>
          <span><strong>Connexion OKX perdue.</strong> Dernière donnée reçue il y a 4min 12s.</span>
          <button className="btn sm" style={{ marginLeft:"auto" }}><Icon.Refresh size={12}/> Reconnecter</button>
        </div>
        <SignauxHeader filter={filter} setFilter={setFilter} />
        <div className="signals-grid">
          {filtered.slice(0, 4).map(s => <div key={s.id} style={{ opacity: 0.4, pointerEvents:"none" }}><SignalCard signal={s}/></div>)}
        </div>
      </div>
    );
  }

  return (
    <div className="page">
      <SignauxHeader filter={filter} setFilter={setFilter}/>
      <div className="signals-grid">
        {filtered.map(s => <SignalCard key={s.id} signal={s} onAction={onAction}/>)}
      </div>
    </div>
  );
}

function SignauxHeader({ filter, setFilter }) {
  const { SIGNALS } = window.MOCK;
  const [scanning, setScanning] = useStateSig(false);
  const [countdown, setCountdown] = useStateSig(15);
  React.useEffect(() => {
    const t = setInterval(() => setCountdown(c => c <= 1 ? 15 : c - 1), 1000);
    return () => clearInterval(t);
  }, []);
  async function doScan() {
    setScanning(true);
    await window.fbScan();
    setCountdown(15);
    setScanning(false);
    emitToast({ type: "success", msg: "Scan terminé" });
  }
  return (
    <>
      <div className="page-header">
        <div>
          <h2>Signaux</h2>
          <div className="sub mono">Scanner FoxBot · {SIGNALS.length} paires analysées</div>
        </div>
        <div style={{ display:"flex", alignItems:"center", gap:12 }}>
          <div className="next-scan">
            <Icon.Clock size={12} className="muted-icon"/>
            <span className="muted" style={{ fontSize:11 }}>Refresh dans</span>
            <span className="mono" style={{ color:"var(--text-primary)", fontWeight:500 }}>{countdown}s</span>
          </div>
          <button className="btn primary scan-btn" style={{ whiteSpace:"nowrap" }} onClick={doScan} disabled={scanning}>
            {scanning ? <span className="spinner"></span> : <Icon.Zap size={14}/>} {scanning ? "SCAN..." : "SCANNER"}
          </button>
        </div>
      </div>
      <div className="chips" style={{ paddingBottom:4 }}>
        {[
          { id:"all", label:"Tous", n: SIGNALS.length },
          { id:"long", label:"LONG", n: SIGNALS.filter(s=>s.direction==="LONG").length },
          { id:"short", label:"SHORT", n: SIGNALS.filter(s=>s.direction==="SHORT").length },
          { id:"premium", label:"Score ≥ 8", n: SIGNALS.filter(s=>s.score>=8).length },
          { id:"volume", label:"Volume > 100%", n: SIGNALS.filter(s=>s.volume>100).length },
          { id:"usa", label:"USA Session", n: 4 },
        ].map(c => (
          <div key={c.id} className={`chip ${filter===c.id?"active":""}`} onClick={()=>setFilter(c.id)}>
            {c.label} <span className="count">{c.n}</span>
          </div>
        ))}
      </div>
    </>
  );
}

function SignalSkeleton() {
  return (
    <div className="signal-card" style={{ pointerEvents:"none" }}>
      <div style={{ display:"flex", alignItems:"center", gap:12 }}>
        <div className="skel" style={{ width:32, height:32, borderRadius:"50%" }}></div>
        <div style={{ display:"flex", flexDirection:"column", gap:4, flex:1 }}>
          <div className="skel" style={{ height:14, width:120 }}></div>
          <div className="skel" style={{ height:10, width:80 }}></div>
        </div>
        <div className="skel" style={{ height:24, width:60, borderRadius:999 }}></div>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12, padding:"12px 0", borderTop:"1px solid var(--border-subtle)", borderBottom:"1px solid var(--border-subtle)" }}>
        {[0,1,2,3,4,5].map(i => <div key={i} className="skel" style={{ height:14 }}></div>)}
      </div>
      <div className="skel" style={{ height:48 }}></div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8 }}>
        <div className="skel" style={{ height:36 }}></div>
        <div className="skel" style={{ height:36 }}></div>
      </div>
    </div>
  );
}

function EmptyState() {
  return (
    <div className="empty-state">
      <div className="empty-glyph">
        <Icon.Search size={28}/>
      </div>
      <h3>Aucun setup détecté</h3>
      <p>Le scanner n'a rien trouvé qui remplisse les critères FoxBot.<br/>Patiente jusqu'au prochain scan ou ajuste les filtres.</p>
      <div style={{ display:"flex", gap:8, marginTop:12 }}>
        <button className="btn ghost"><Icon.Filter size={13}/> Filtres</button>
        <button className="btn primary"><Icon.Zap size={13}/> Forcer un scan</button>
      </div>
    </div>
  );
}

function VolatileScreen({ onAction }) {
  const { VOLATILE } = window.MOCK;
  return (
    <div className="page">
      <div className="page-header">
        <div style={{ display:"flex", alignItems:"center", gap:14 }}>
          <div className="vol-icon-wrap">
            <Icon.Flame size={20}/>
          </div>
          <div>
            <h2>Volatile</h2>
            <div className="sub mono">Top 10 paires volatiles · tri par ATR%</div>
          </div>
        </div>
        <div style={{ display:"flex", alignItems:"center", gap:12 }}>
          <div className="next-scan">
            <Icon.Activity size={12} className="muted-icon"/>
            <span className="muted" style={{ fontSize:11 }}>ATR moyen</span>
            <span className="mono warn" style={{ fontWeight:500 }}>
              {VOLATILE.length ? (VOLATILE.reduce((s,v)=>s+v.atr,0)/VOLATILE.length).toFixed(2)+"%" : "—"}
            </span>
          </div>
          <button className="btn primary scan-btn vol-scan" style={{ whiteSpace:"nowrap" }} onClick={()=>window.fbScan().then(()=>emitToast({ type:"success", msg:"Scan volatiles terminé" }))}>
            <Icon.Flame size={14}/> SCAN VOLATILES
          </button>
        </div>
      </div>

      <div className="chips">
        {["Tous","ATR > 2%","ATR > 3%","Hot 🔥","LONG","SHORT"].map((t, i) => (
          <div key={t} className={`chip ${i===0?"active":""}`}>{t.replace("🔥","")} {i===3&&<span style={{color:"var(--warn)"}}>·</span>}</div>
        ))}
      </div>

      <div className="signals-grid">
        {VOLATILE.map(s => (
          <div key={s.id} style={{ position:"relative" }}>
            {s.hot && <div className="hot-badge"><Icon.Flame size={11}/> HOT</div>}
            <SignalCard signal={s} onAction={onAction}/>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { SignauxScreen, VolatileScreen });
