/* ============================================================
   JTSense App — views: Signals · Alerts · Watchlist · Analytics · Settings
   ============================================================ */

/* ---------------- SIGNALS ---------------- */
function SignalsView({ signals }) {
  const J = window.JT;
  const [filter, setFilter] = useState("ALL");
  const [minConf, setMinConf] = useState(70);
  const types = ["ALL", ...J.SIG_TYPES];
  const rows = signals.filter(s => (filter === "ALL" || s.type === filter) && s.confidence >= minConf);
  return (
    <div className="grid" style={{ gridTemplateColumns: "1fr" }}>
      <Card>
        <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {types.map(t => (
              <span key={t} className={"chan-pick " + (filter === t ? "on" : "")} onClick={() => setFilter(t)}>{t}</span>
            ))}
          </div>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--f-mono)", fontSize: 12, color: "var(--tx-mute)" }}>
            <span>Min confidence</span>
            <input type="range" min="70" max="96" value={minConf} onChange={e => setMinConf(+e.target.value)} style={{ accentColor: "#2b8cff" }} />
            <span style={{ color: "var(--blue-bright)", width: 34 }}>{minConf}%</span>
          </div>
        </div>
      </Card>
      <Card title={`Signal Stream · ${rows.length} matching`}>
        <table className="tbl">
          <thead><tr><th>Type</th><th>Signal</th><th>Source</th><th>Confidence</th><th>Detected</th></tr></thead>
          <tbody>
            {rows.map(s => (
              <tr key={s.id}>
                <td><TypeChip type={s.type} /></td>
                <td><b style={{ color: "var(--tx)" }}>{s.label}</b></td>
                <td className="mono" style={{ color: "var(--tx-mute)", fontSize: 12 }}>{s.source}</td>
                <td>
                  <span className="score-bar"><i style={{ width: s.confidence + "%", background: J.typeColor[s.type] }} /></span>
                  <span className="mono" style={{ marginLeft: 8, fontSize: 12, color: J.typeColor[s.type] }}>{s.confidence}%</span>
                </td>
                <td className="mono" style={{ color: "var(--tx-dim)", fontSize: 12 }}>{J.fmt.ago(s.ts)}</td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan="5"><div className="empty">No signals match these filters yet.</div></td></tr>}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

/* ---------------- ALERTS ---------------- */
function AlertsView({ rules, setRules, toast }) {
  const J = window.JT;
  const [creating, setCreating] = useState(false);
  const [form, setForm] = useState({ name: "", type: "WHALE", value: "", conf: 85, channels: ["dashboard"] });

  function toggleChan(c) {
    setForm(f => ({ ...f, channels: f.channels.includes(c) ? f.channels.filter(x => x !== c) : [...f.channels, c] }));
  }
  function create() {
    if (!form.name.trim() || !form.value.trim()) { toast("Incomplete rule", "Give the rule a name and threshold.", "warn"); return; }
    const r = { id: Date.now(), name: form.name, type: form.type, op: ">", value: form.value, conf: form.conf, channels: form.channels, active: true, triggered: 0 };
    setRules(rs => [r, ...rs]);
    setCreating(false);
    setForm({ name: "", type: "WHALE", value: "", conf: 85, channels: ["dashboard"] });
    toast("Alert rule created", `"${r.name}" is now live.`, "ok");
  }
  function toggle(id) { setRules(rs => rs.map(r => r.id === id ? { ...r, active: !r.active } : r)); }
  function del(id) { setRules(rs => rs.filter(r => r.id !== id)); toast("Rule deleted", "The alert rule was removed.", "warn"); }

  return (
    <div className="grid" style={{ gridTemplateColumns: "1fr" }}>
      <div className="grid" style={{ gridTemplateColumns: "repeat(3,1fr)" }}>
        <MiniStat lab="Active Rules" val={rules.filter(r => r.active).length} sub={`of ${rules.length} total`} color="var(--blue-bright)" />
        <MiniStat lab="Triggered · 24h" val={rules.reduce((a, r) => a + r.triggered, 0)} sub="across all rules" color="var(--up)" />
        <MiniStat lab="Channels" val="3" sub="dashboard · telegram · webhook" />
      </div>

      <Card title="Alert Rules" more={creating ? "Cancel" : "+ New rule"} onMore={() => setCreating(c => !c)}>
        {creating && (
          <div style={{ border: "1px solid var(--line-strong)", borderRadius: 12, padding: 18, marginBottom: 18, background: "var(--panel-3)" }}>
            <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr 1fr", gap: 12 }}>
              <div>
                <label className="lab" style={lblS}>Rule name</label>
                <input className="inp" style={{ width: "100%" }} placeholder="e.g. Whale accumulation" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
              </div>
              <div>
                <label className="lab" style={lblS}>Signal type</label>
                <select className="sel" style={{ width: "100%" }} value={form.type} onChange={e => setForm({ ...form, type: e.target.value })}>
                  {J.SIG_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <label className="lab" style={lblS}>Threshold</label>
                <input className="inp" style={{ width: "100%" }} placeholder="> 100 ETH" value={form.value} onChange={e => setForm({ ...form, value: e.target.value })} />
              </div>
            </div>
            <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--f-mono)", fontSize: 12, color: "var(--tx-mute)" }}>
                <span>Min confidence</span>
                <input type="range" min="60" max="98" value={form.conf} onChange={e => setForm({ ...form, conf: +e.target.value })} style={{ accentColor: "#2b8cff" }} />
                <span style={{ color: "var(--blue-bright)" }}>{form.conf}%</span>
              </div>
              <div style={{ display: "flex", gap: 8, marginLeft: "auto" }}>
                {["dashboard", "telegram", "webhook"].map(c => (
                  <span key={c} className={"chan-pick " + (form.channels.includes(c) ? "on" : "")} onClick={() => toggleChan(c)}>{c}</span>
                ))}
              </div>
            </div>
            <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={create}>Create rule</button>
          </div>
        )}

        {rules.map(r => (
          <div className="rule" key={r.id}>
            <div className={"toggle " + (r.active ? "on" : "")} onClick={() => toggle(r.id)}><i /></div>
            <div className="rdesc">
              <h4>{r.name}</h4>
              <div className="rmeta">
                <TypeChip type={r.type} /> &nbsp; {r.op} {r.value} · conf ≥ {r.conf}% · {r.channels.join(" · ")} · triggered {r.triggered}×
              </div>
            </div>
            <span className="star" style={{ color: "var(--tx-dim)", fontSize: 18 }} title="Delete" onClick={() => del(r.id)}>✕</span>
          </div>
        ))}
        {rules.length === 0 && <div className="empty"><div className="ei">🔔</div>No alert rules yet. Create one to get notified in realtime.</div>}
      </Card>
    </div>
  );
}
const lblS = { display: "block", fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--tx-mute)", marginBottom: 7 };

/* ---------------- WATCHLIST ---------------- */
function WatchlistView({ watch, toggleWatch, go }) {
  if (watch.length === 0) {
    return (
      <Card>
        <div className="empty">
          <div className="ei">★</div>
          <div style={{ fontSize: 16, color: "var(--tx-soft)", marginBottom: 6 }}>Your watchlist is empty</div>
          <div style={{ fontSize: 13, marginBottom: 20 }}>Star wallets and narratives to pin them here for one-glance monitoring.</div>
          <button className="btn btn-ghost" onClick={() => go("wallets")}>Browse Wallets →</button>
        </div>
      </Card>
    );
  }
  return (
    <Card title={`Watchlist · ${watch.length} pinned`}>
      <table className="tbl">
        <thead><tr><th>Item</th><th>Kind</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {watch.map(w => (
            <tr key={w.key}>
              <td><b className={w.kind === "Wallet" ? "addr" : ""} style={{ color: "var(--tx)" }}>{w.label}</b></td>
              <td><span className="chip" style={{ fontSize: 10 }}>{w.kind}</span></td>
              <td><span className="live-pill" style={{ fontSize: 11 }}>Monitoring</span></td>
              <td><span className="star on" onClick={() => toggleWatch(w)}>★</span></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

/* ---------------- ANALYTICS ---------------- */
function AnalyticsView() {
  const J = window.JT;
  return (
    <div className="grid" style={{ gridTemplateColumns: "1fr" }}>
      <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr" }}>
        <Card title="Signal Volume · 14d">
          <Bars data={J.volume.map(v => v.n)} color="#4ea2ff" h={150} />
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontFamily: "var(--f-mono)", fontSize: 11, color: "var(--tx-dim)" }}>
            <span>14d ago</span><span>today</span>
          </div>
        </Card>
        <Card title="Source Breakdown">
          {J.sources.map(s => (
            <div key={s.name} style={{ marginBottom: 12 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--f-mono)", fontSize: 12, marginBottom: 5 }}>
                <span style={{ color: "var(--tx-soft)" }}>{s.name}</span><span style={{ color: s.color }}>{s.pct}%</span>
              </div>
              <div style={{ height: 7, borderRadius: 4, background: "var(--panel-3)", overflow: "hidden" }}>
                <div style={{ width: s.pct + "%", height: "100%", background: s.color, borderRadius: 4 }} />
              </div>
            </div>
          ))}
        </Card>
      </div>
      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr 1fr" }}>
        <Card title="Confidence Distribution">
          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            <Donut value={88} color="#4ea2ff" label="avg conf" />
            <div style={{ fontFamily: "var(--f-mono)", fontSize: 12, color: "var(--tx-mute)", lineHeight: 2 }}>
              <div><span style={{ color: "var(--up)" }}>●</span> High (&gt;85%) · 64%</div>
              <div><span style={{ color: "var(--amber)" }}>●</span> Med (75–85%) · 28%</div>
              <div><span style={{ color: "var(--down)" }}>●</span> Low (&lt;75%) · 8%</div>
            </div>
          </div>
        </Card>
        <Card title="Inference Latency">
          <div style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 38, color: "var(--blue-bright)" }}>{J.live.latency}<span style={{ fontSize: 18, color: "var(--tx-mute)" }}>ms</span></div>
          <div style={{ fontFamily: "var(--f-mono)", fontSize: 12, color: "var(--tx-mute)", margin: "4px 0 14px" }}>p50 · JTVO infer-l</div>
          <Spark data={J.kpiSpark.confidence.slice(-10)} color="#4ea2ff" w={220} h={44} />
        </Card>
        <Card title="Signal Types">
          {J.SIG_TYPES.map((t, i) => {
            const pct = [38, 22, 18, 14, 8][i];
            return (
              <div key={t} style={{ marginBottom: 11 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--f-mono)", fontSize: 12, marginBottom: 5 }}>
                  <span style={{ color: J.typeColor[t] }}>{t}</span><span style={{ color: "var(--tx-mute)" }}>{pct}%</span>
                </div>
                <div style={{ height: 6, borderRadius: 3, background: "var(--panel-3)", overflow: "hidden" }}>
                  <div style={{ width: pct + "%", height: "100%", background: J.typeColor[t], borderRadius: 3 }} />
                </div>
              </div>
            );
          })}
        </Card>
      </div>
    </div>
  );
}

/* ---------------- SETTINGS ---------------- */
function SettingsView({ user, onLogout, toast }) {
  const [tg, setTg] = useState(true);
  const [wh, setWh] = useState(false);
  const [push, setPush] = useState(true);
  const [hook, setHook] = useState("https://your-server.com/jtsense-hook");
  return (
    <div className="grid" style={{ gridTemplateColumns: "1fr", maxWidth: 760 }}>
      <Card title="Profile">
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <div className="avatar" style={{ width: 52, height: 52, fontSize: 20 }}>{(user.name || "A")[0]}</div>
          <div>
            <div style={{ fontFamily: "var(--f-display)", fontWeight: 600, fontSize: 18 }}>{user.name}</div>
            <div style={{ fontFamily: "var(--f-mono)", fontSize: 13, color: "var(--tx-mute)" }}>{user.email}</div>
          </div>
          <span className="chip" style={{ marginLeft: "auto" }}>PRO · JTVO</span>
        </div>
      </Card>

      <Card title="Notification Channels">
        <SetRow lab="Dashboard alerts" sd="Realtime in-app notifications" on={push} set={setPush} />
        <SetRow lab="Telegram" sd="Push signals to your Telegram channel or DM" on={tg} set={setTg} />
        <SetRow lab="Webhook" sd="POST every alert to your endpoint" on={wh} set={setWh} />
        {wh && (
          <div style={{ marginTop: 14 }}>
            <label style={lblS}>Webhook URL</label>
            <input className="inp" style={{ width: "100%" }} value={hook} onChange={e => setHook(e.target.value)} />
          </div>
        )}
        <button className="btn btn-primary" style={{ marginTop: 18 }} onClick={() => toast("Settings saved", "Your notification preferences were updated.", "ok")}>Save changes</button>
      </Card>

      <Card title="Account">
        <div className="set-row">
          <div><div className="sl">Sign out</div><div className="sd">End your session and return to login.</div></div>
          <button className="btn btn-ghost" onClick={onLogout}>Log out</button>
        </div>
      </Card>
    </div>
  );
}
function SetRow({ lab, sd, on, set }) {
  return (
    <div className="set-row">
      <div><div className="sl">{lab}</div><div className="sd">{sd}</div></div>
      <div className={"toggle " + (on ? "on" : "")} onClick={() => set(v => !v)}><i /></div>
    </div>
  );
}

Object.assign(window, { SignalsView, AlertsView, WatchlistView, AnalyticsView, SettingsView });
