/* ============================================
   VELOX — Mobile App
   Screens: Login, Home, Strategies, Trades
   ============================================ */

/* MobileApp and sub-screens are defined below.
   app.jsx detects the device and mounts MobileApp instead of App on phones. */

/* ── Colours / tokens (reuse CSS vars from styles.css) ── */

const MobileApp = () => {
  const [authed, setAuthed] = React.useState(false);
  const [user, setUser]     = React.useState(null);
  const [page, setPage]     = React.useState("home");
  const [toasts, setToasts] = React.useState([]);

  const addToast = (t) => {
    const id = Math.random().toString(36).slice(2);
    setToasts(prev => [...prev, { ...t, id, ts: Date.now() }]);
    setTimeout(() => setToasts(prev => prev.filter(x => x.id !== id)), 3500);
  };

  const onLogin = (u = {}) => {
    setUser({ name: u.name || u.email || "Trader", uid: u.uid || "" });
    setAuthed(true);
  };

  const onLogout = () => {
    API.signOut().catch(() => {});
    setAuthed(false);
    setUser(null);
    setPage("home");
  };

  if (!authed) return <MobileLogin onLogin={onLogin} />;

  const renderPage = () => {
    switch (page) {
      case "home":       return <MobileHome user={user} onLogout={onLogout} addToast={addToast} uid={user.uid} />;
      case "strategies": return <MobileStrategies addToast={addToast} uid={user.uid} />;
      case "trades":     return <MobileTrades uid={user.uid} />;
      default:           return null;
    }
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100dvh", background: "var(--bg)", color: "var(--text-1)", fontFamily: "Inter, sans-serif", maxWidth: 480, margin: "0 auto", position: "relative" }}>
      {/* Page content — scrollable */}
      <div style={{ flex: 1, overflowY: "auto", paddingBottom: 72 }}>
        {renderPage()}
      </div>

      {/* Bottom nav */}
      <nav style={{
        position: "fixed", bottom: 0, left: "50%", transform: "translateX(-50%)",
        width: "100%", maxWidth: 480,
        background: "var(--surface)", borderTop: "1px solid var(--border)",
        display: "flex", zIndex: 100,
      }}>
        {[
          { id: "home",       label: "Home",       icon: "dashboard" },
          { id: "strategies", label: "Strategies", icon: "bot" },
          { id: "trades",     label: "Trades",     icon: "chart" },
        ].map(n => (
          <button key={n.id} onClick={() => setPage(n.id)}
            style={{
              flex: 1, padding: "10px 0 8px", display: "flex", flexDirection: "column",
              alignItems: "center", gap: 3, background: "none", border: "none", cursor: "pointer",
              color: page === n.id ? "var(--brand)" : "var(--text-3)",
              borderTop: page === n.id ? "2px solid var(--brand)" : "2px solid transparent",
              transition: "color .15s",
            }}>
            <Icon name={n.icon} size={20} />
            <span style={{ fontSize: 10, fontWeight: 600 }}>{n.label}</span>
          </button>
        ))}
      </nav>

      {/* Toasts */}
      <div style={{ position: "fixed", top: 16, left: "50%", transform: "translateX(-50%)", width: "calc(100% - 32px)", maxWidth: 440, zIndex: 200, display: "flex", flexDirection: "column", gap: 8 }}>
        {toasts.map(t => (
          <div key={t.id} style={{
            background: t.type === "warn" ? "var(--down)" : "var(--up)",
            color: "white", borderRadius: 12, padding: "10px 14px",
            fontSize: 13, fontWeight: 600, boxShadow: "0 4px 16px rgba(0,0,0,.2)",
            animation: "toastIn .2s",
          }}>
            {t.title}{t.body ? ` · ${t.body}` : ""}
          </div>
        ))}
      </div>
    </div>
  );
};

/* ════════════════════════════════════════
   LOGIN
════════════════════════════════════════ */
const MobileLogin = ({ onLogin }) => {
  const [step, setStep]       = React.useState("init");
  const [authMode, setAuthMode] = React.useState("signin");
  const [email, setEmail]     = React.useState("");
  const [password, setPassword] = React.useState("");
  const [mobile, setMobile]   = React.useState("");
  const [ucc, setUcc]         = React.useState("");
  const [consumerCode, setConsumerCode] = React.useState("");
  const [totp, setTotp]       = React.useState("");
  const [mpin, setMpin]       = React.useState("");
  const [maskedMobile, setMaskedMobile] = React.useState("");
  const [err, setErr]         = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [firebaseUser, setFirebaseUser] = React.useState(null);

  function maskMobile(m) {
    const d = m.replace(/\D/g, "");
    return d.length >= 10 ? `+91 ••••• ••${d.slice(-3)}` : m;
  }

  async function afterVeloxLogin(user) {
    setFirebaseUser(user);
    try {
      const connected = await API.isKotakConnected();
      if (connected) { onLogin({ uid: user.uid, name: user.displayName || user.email }); return; }
      const profile = await API.loadKotakProfile();
      if (profile?.mobile) {
        setMaskedMobile(maskMobile(profile.mobile));
        setStep("kotak-connect");
      } else {
        setStep("kotak-setup");
      }
    } catch { setStep("kotak-setup"); }
  }

  React.useEffect(() => {
    API.init(FIREBASE_CONFIG).then(async user => {
      if (user && !user.isAnonymous) await afterVeloxLogin(user);
      else setStep("velox");
    }).catch(() => setStep("velox"));
  }, []);

  const submitGoogle = async () => {
    setErr(""); setLoading(true);
    try { await afterVeloxLogin((await API.signInWithGoogle()).user); }
    catch (e) { setErr(e?.message || "Sign-in failed"); }
    finally { setLoading(false); }
  };

  const submitEmail = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    try {
      const u = authMode === "signup"
        ? await API.signUp(email, password)
        : await API.signIn(email, password);
      await afterVeloxLogin(u.user ?? u);
    } catch (ex) { setErr(ex?.message || "Failed"); }
    finally { setLoading(false); }
  };

  const submitKotakSetup = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    try {
      await API.kotakSaveProfile({ mobile, ucc, consumerCode: consumerCode || undefined });
      await API.kotakConnectDirect({ totp, mpin });
      onLogin({ uid: firebaseUser?.uid, name: firebaseUser?.displayName || firebaseUser?.email });
    } catch (ex) { setErr(ex?.message || "Kotak connect failed"); }
    finally { setLoading(false); }
  };

  const submitKotakConnect = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    try {
      await API.kotakConnectDirect({ totp, mpin });
      onLogin({ uid: firebaseUser?.uid, name: firebaseUser?.displayName || firebaseUser?.email });
    } catch (ex) { setErr(ex?.message || "Connect failed"); }
    finally { setLoading(false); }
  };

  const Card = ({ children }) => (
    <div style={{ minHeight: "100dvh", display: "flex", flexDirection: "column", justifyContent: "center", padding: "32px 24px", background: "var(--bg)" }}>
      {/* Brand */}
      <div style={{ textAlign: "center", marginBottom: 36 }}>
        <div style={{ width: 56, height: 56, borderRadius: 16, background: "var(--brand)", color: "white", fontSize: 28, fontWeight: 800, display: "inline-grid", placeItems: "center", marginBottom: 12 }}>V</div>
        <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "-0.5px" }}>Velox</div>
        <div style={{ fontSize: 13, color: "var(--text-3)", marginTop: 2 }}>Automated Trading</div>
      </div>
      {children}
    </div>
  );

  const Input = ({ label, ...props }) => (
    <div style={{ marginBottom: 14 }}>
      {label && <div style={{ fontSize: 12, fontWeight: 600, color: "var(--text-2)", marginBottom: 6 }}>{label}</div>}
      <input className="input" style={{ width: "100%", fontSize: 16, padding: "13px 14px", borderRadius: 12 }} {...props} />
    </div>
  );

  const Btn = ({ children, secondary, ...props }) => (
    <button {...props} style={{
      width: "100%", padding: "14px 0", borderRadius: 14, fontSize: 15, fontWeight: 700,
      background: secondary ? "var(--surface-2)" : "var(--brand)",
      color: secondary ? "var(--text-1)" : "white",
      border: "none", cursor: "pointer", marginBottom: 10,
      ...props.style,
    }}>{children}</button>
  );

  if (step === "init") return <Card><div style={{ textAlign: "center", color: "var(--text-3)" }}>Loading…</div></Card>;

  if (step === "velox") return (
    <Card>
      <div style={{ marginBottom: 6, fontSize: 20, fontWeight: 700 }}>
        {authMode === "signin" ? "Welcome back" : "Create account"}
      </div>
      <div style={{ fontSize: 13, color: "var(--text-3)", marginBottom: 24 }}>
        {authMode === "signin" ? "Sign in to your Velox account" : "Start trading algorithmically"}
      </div>
      {err && <div style={{ background: "color-mix(in srgb, var(--down) 15%, transparent)", color: "var(--down)", borderRadius: 10, padding: "10px 14px", fontSize: 13, marginBottom: 14 }}>{err}</div>}
      <Btn onClick={submitGoogle} secondary style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10 }}>
        <svg width="18" height="18" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
        Continue with Google
      </Btn>
      <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "8px 0 16px" }}>
        <div style={{ flex: 1, height: 1, background: "var(--border)" }}/>
        <span style={{ fontSize: 12, color: "var(--text-3)" }}>or</span>
        <div style={{ flex: 1, height: 1, background: "var(--border)" }}/>
      </div>
      <form onSubmit={submitEmail}>
        <Input label="Email" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" autoComplete="email"/>
        <Input label="Password" type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" autoComplete="current-password"/>
        <Btn type="submit" disabled={loading}>{loading ? "Please wait…" : authMode === "signin" ? "Sign in" : "Create account"}</Btn>
      </form>
      <div style={{ textAlign: "center", fontSize: 13, color: "var(--text-3)" }}>
        {authMode === "signin" ? "No account? " : "Already have one? "}
        <span style={{ color: "var(--brand)", fontWeight: 600, cursor: "pointer" }}
          onClick={() => setAuthMode(authMode === "signin" ? "signup" : "signin")}>
          {authMode === "signin" ? "Sign up" : "Sign in"}
        </span>
      </div>
    </Card>
  );

  if (step === "kotak-setup") return (
    <Card>
      <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 4 }}>Connect Kotak</div>
      <div style={{ fontSize: 13, color: "var(--text-3)", marginBottom: 24 }}>Link your Kotak Securities account</div>
      {err && <div style={{ background: "color-mix(in srgb, var(--down) 15%, transparent)", color: "var(--down)", borderRadius: 10, padding: "10px 14px", fontSize: 13, marginBottom: 14 }}>{err}</div>}
      <form onSubmit={submitKotakSetup}>
        <Input label="Mobile number" type="tel" value={mobile} onChange={e => setMobile(e.target.value)} placeholder="9xxxxxxxxx"/>
        <Input label="UCC" value={ucc} onChange={e => setUcc(e.target.value)} placeholder="YKAAO"/>
        <Input label="Consumer code (optional)" value={consumerCode} onChange={e => setConsumerCode(e.target.value)} placeholder="5f31ac53-…"/>
        <Input label="TOTP (6-digit)" type="number" value={totp} onChange={e => setTotp(e.target.value.slice(0, 6))} placeholder="000000" inputMode="numeric"/>
        <Input label="MPIN" type="password" value={mpin} onChange={e => setMpin(e.target.value)} placeholder="••••••"/>
        <Btn type="submit" disabled={loading}>{loading ? "Connecting…" : "Connect & Continue"}</Btn>
      </form>
    </Card>
  );

  if (step === "kotak-connect") return (
    <Card>
      <div style={{ fontSize: 20, fontWeight: 700, marginBottom: 4 }}>Reconnect Kotak</div>
      <div style={{ fontSize: 13, color: "var(--text-3)", marginBottom: 8 }}>Session expired for <b>{maskedMobile}</b></div>
      {err && <div style={{ background: "color-mix(in srgb, var(--down) 15%, transparent)", color: "var(--down)", borderRadius: 10, padding: "10px 14px", fontSize: 13, marginBottom: 14 }}>{err}</div>}
      <form onSubmit={submitKotakConnect}>
        <Input label="TOTP (6-digit)" type="number" value={totp} onChange={e => setTotp(e.target.value.slice(0, 6))} placeholder="000000" inputMode="numeric" autoFocus/>
        <Input label="MPIN" type="password" value={mpin} onChange={e => setMpin(e.target.value)} placeholder="••••••"/>
        <Btn type="submit" disabled={loading}>{loading ? "Connecting…" : "Connect"}</Btn>
      </form>
    </Card>
  );

  return null;
};

/* ════════════════════════════════════════
   HOME DASHBOARD
════════════════════════════════════════ */
const MobileHome = ({ user, onLogout, addToast, uid }) => {
  const [algos, setAlgos]       = React.useState([]);
  const [trades, setTrades]     = React.useState([]);
  const [kotakStatus, setKotakStatus] = React.useState(null);

  React.useEffect(() => {
    if (!uid) return;
    API.loadKotakProfile().then(p => setKotakStatus(p)).catch(() => {});
    // Listen to each algo's configs individually (avoids collectionGroup index requirement)
    const unsubs = MOBILE_ALGO_CATALOG.map(meta =>
      API.listenConfigs(meta.id, cfgs => {
        setAlgos(prev => {
          const running = cfgs.filter(c => c.running);
          const without = prev.filter(a => a.id !== meta.id);
          if (running.length === 0) return without;
          return [...without, { id: meta.id, label: meta.label, icon: meta.icon, configs: running, runningCount: running.length }];
        });
      })
    );
    const unsubTrades = API.listenTrades(t => setTrades(t), 100);
    return () => { unsubs.forEach(u => u()); unsubTrades(); };
  }, [uid]);

  const todayStart = new Date().setHours(0, 0, 0, 0);
  const todayTrades = trades.filter(t => (t.exitTs ?? 0) >= todayStart);
  const todayPnl = todayTrades.reduce((s, t) => s + (t.pnl ?? 0), 0);
  const todayWins = todayTrades.filter(t => (t.pnl ?? 0) > 0).length;
  const runningAlgos = algos.filter(a => a.running);

  const fmtM = (n) => (n >= 0 ? "+" : "") + "₹" + Math.abs(n).toFixed(0);
  const col   = (n) => n >= 0 ? "var(--up)" : "var(--down)";

  const now = new Date();
  const istMs = now.getTime() + 5.5 * 3600 * 1000;
  const ist = new Date(istMs);
  const h = ist.getUTCHours(), m = ist.getUTCMinutes();
  const mins = h * 60 + m;
  const isOpen = now.getDay() !== 0 && now.getDay() !== 6 && mins >= 9 * 60 + 15 && mins < 15 * 60 + 30;

  return (
    <div style={{ padding: "20px 16px 0" }}>
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
        <div>
          <div style={{ fontSize: 13, color: "var(--text-3)" }}>Good {h < 12 ? "morning" : h < 17 ? "afternoon" : "evening"},</div>
          <div style={{ fontSize: 18, fontWeight: 700 }}>{user?.name?.split(" ")[0] || "Trader"}</div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 600, color: isOpen ? "var(--up)" : "var(--text-3)" }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: isOpen ? "var(--up)" : "var(--text-3)", display: "inline-block" }}/>
            {isOpen ? "Market open" : "Closed"}
          </div>
          <button onClick={onLogout} style={{ background: "var(--surface-2)", border: "none", borderRadius: 10, padding: "6px 12px", fontSize: 12, color: "var(--text-2)", cursor: "pointer" }}>
            Sign out
          </button>
        </div>
      </div>

      {/* Today P&L card */}
      <div style={{
        background: "linear-gradient(135deg, var(--brand) 0%, color-mix(in srgb, var(--brand) 70%, #000) 100%)",
        borderRadius: 20, padding: "22px 20px", marginBottom: 16, color: "white",
      }}>
        <div style={{ fontSize: 12, opacity: 0.75, marginBottom: 6, fontWeight: 600 }}>TODAY'S P&L</div>
        <div style={{ fontSize: 36, fontWeight: 800, letterSpacing: "-1px", marginBottom: 4 }}>
          {todayTrades.length === 0 ? "₹0" : fmtM(todayPnl)}
        </div>
        <div style={{ fontSize: 13, opacity: 0.8 }}>
          {todayTrades.length} trades · {todayWins} wins
        </div>
      </div>

      {/* Kotak status */}
      {kotakStatus && (
        <div style={{
          background: "var(--surface)", borderRadius: 14, padding: "12px 16px", marginBottom: 16,
          display: "flex", alignItems: "center", gap: 10, border: "1px solid var(--border)",
        }}>
          <span style={{ width: 9, height: 9, borderRadius: "50%", background: kotakStatus.isConnected ? "var(--up)" : "var(--down)", flexShrink: 0 }}/>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Kotak {kotakStatus.isConnected ? "Connected" : "Disconnected"}</div>
            {kotakStatus.ucc && <div style={{ fontSize: 11, color: "var(--text-3)" }}>UCC: {kotakStatus.ucc}</div>}
          </div>
        </div>
      )}

      {/* Running strategies */}
      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 10 }}>
        Running Strategies
      </div>
      {runningAlgos.length === 0 ? (
        <div style={{ background: "var(--surface)", borderRadius: 14, padding: "20px 16px", textAlign: "center", color: "var(--text-3)", fontSize: 13, marginBottom: 16 }}>
          No strategies running
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 16 }}>
          {runningAlgos.map(a => (
            <div key={a.id} style={{ background: "var(--surface)", borderRadius: 14, padding: "14px 16px", border: "1px solid color-mix(in srgb, var(--up) 30%, var(--border))" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: a.configs.length > 0 ? 8 : 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 18 }}>{a.icon}</span>
                  <span style={{ fontWeight: 700, fontSize: 14 }}>{a.label}</span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--up)", fontWeight: 700 }}>
                  <span className="pulse" style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--up)" }}/>
                  LIVE
                </div>
              </div>
              {a.configs.map(c => (
                <div key={c.id} style={{ fontSize: 12, color: "var(--text-2)", background: "var(--surface-2)", borderRadius: 8, padding: "5px 10px", display: "inline-block", marginRight: 6 }}>
                  {c.name ?? "Untitled"}
                </div>
              ))}
            </div>
          ))}
        </div>
      )}

      {/* Recent trades */}
      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-3)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 10 }}>
        Recent Trades
      </div>
      {trades.slice(0, 5).length === 0 ? (
        <div style={{ background: "var(--surface)", borderRadius: 14, padding: "20px 16px", textAlign: "center", color: "var(--text-3)", fontSize: 13 }}>
          No trades yet
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {trades.slice(0, 5).map(t => (
            <div key={t.id} style={{ background: "var(--surface)", borderRadius: 14, padding: "12px 14px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontWeight: 600, fontSize: 13 }}>{t.sym ?? "—"}</div>
                <div style={{ fontSize: 11, color: "var(--text-3)" }}>{t.algoId} · {t.exitReason}</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={{ fontWeight: 700, fontSize: 14, color: col(t.pnl ?? 0) }}>{fmtM(t.pnl ?? 0)}</div>
                <div style={{ fontSize: 11, color: "var(--text-3)" }}>{(t.pnlPct ?? 0).toFixed(1)}%</div>
              </div>
            </div>
          ))}
        </div>
      )}
      <div style={{ height: 16 }}/>
    </div>
  );
};

/* ════════════════════════════════════════
   STRATEGIES
════════════════════════════════════════ */
const MOBILE_ALGO_CATALOG = [
  { id: "momentum-burst",   icon: "⚡", label: "Momentum Burst",   tagline: "Catches sudden directional moves" },
  { id: "candle-burst",     icon: "🕯️", label: "Candle Burst",     tagline: "Candlestick patterns on 1-min spot" },
  { id: "max-profit",       icon: "📈", label: "Max Profit",       tagline: "Cluster momentum across watchlist" },
  { id: "option-dip-buyer", icon: "🎯", label: "Option Dip Buyer", tagline: "Buys options on price dips" },
  { id: "advance-candle",   icon: "🕯", label: "Advance Candle",   tagline: "Three-Line Strike, Morning & Evening Star" },
];

/* Per-algo config listener hook */
const useAlgoConfigs = (algoId, uid) => {
  const [configs, setConfigs] = React.useState([]);
  React.useEffect(() => {
    if (!uid) return;
    const unsub = API.listenConfigs(algoId, setConfigs);
    return () => unsub();
  }, [algoId, uid]);
  return configs;
};

/* Format config value for display */
const fmtVal = (v) => {
  if (typeof v === "boolean") return v ? "true" : "false";
  if (Array.isArray(v)) return `[${v.length} items]`;
  if (v !== null && typeof v === "object") return `{${Object.keys(v).join(", ")}}`;
  return String(v);
};

/* Config action sheet */
const ConfigSheet = ({ config, algoId, onClose, addToast }) => {
  const [loading, setLoading] = React.useState(false);
  const [editMode, setEditMode] = React.useState(false);
  const [edits, setEdits] = React.useState({});

  React.useEffect(() => {
    // seed edits with current primitive values only
    const init = {};
    Object.entries(config.config ?? {}).forEach(([k, v]) => {
      if (typeof v !== "object" && !Array.isArray(v)) init[k] = v;
    });
    setEdits(init);
  }, [config.id]);

  const act = async (fn, successMsg) => {
    setLoading(true);
    try { await fn(); addToast({ type: "up", title: successMsg }); onClose(); }
    catch (e) { addToast({ type: "warn", title: "Failed", body: e?.message ?? String(e) }); }
    finally { setLoading(false); }
  };

  const saveEdits = () => {
    const merged = { ...config.config };
    Object.entries(edits).forEach(([k, v]) => {
      // coerce back to original type
      const orig = config.config?.[k];
      if (typeof orig === "number") merged[k] = Number(v);
      else if (typeof orig === "boolean") merged[k] = v === "true" || v === true;
      else merged[k] = v;
    });
    act(() => API.saveConfig(algoId, config.id, { ...config, config: merged }), "Config saved");
  };

  const SmallBtn = ({ onClick, children, danger, disabled: dis }) => (
    <button onClick={onClick} disabled={dis || loading}
      style={{
        flex: 1, padding: "9px 6px", borderRadius: 10, fontSize: 13, fontWeight: 700,
        border: "none", cursor: "pointer",
        background: danger ? "color-mix(in srgb, var(--down) 12%, var(--surface-2))" : "var(--surface-2)",
        color: danger ? "var(--down)" : "var(--text-1)", opacity: (dis || loading) ? 0.5 : 1,
      }}>{children}</button>
  );

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.5)", zIndex: 300, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}
      onClick={onClose}>
      <div style={{ background: "var(--surface)", borderRadius: "20px 20px 0 0", padding: "16px 16px 32px", maxHeight: "88dvh", display: "flex", flexDirection: "column" }}
        onClick={e => e.stopPropagation()}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--border)", margin: "0 auto 14px" }}/>

        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 700 }}>{config.name ?? "Untitled"}</div>
            <div style={{ fontSize: 11, color: config.running ? "var(--up)" : "var(--text-3)", fontWeight: 600 }}>
              {config.running ? "● Running" : "Stopped"}
            </div>
          </div>
          <button onClick={() => setEditMode(e => !e)}
            style={{ padding: "6px 14px", borderRadius: 999, border: "none", cursor: "pointer", fontSize: 12, fontWeight: 700,
              background: editMode ? "var(--brand)" : "var(--surface-2)",
              color: editMode ? "white" : "var(--text-2)" }}>
            {editMode ? "Editing" : "✎ Edit"}
          </button>
        </div>

        {/* Params — scrollable */}
        <div style={{ overflowY: "auto", flex: 1, marginBottom: 14 }}>
          {config.config && Object.keys(config.config).length > 0 && (
            <div style={{ background: "var(--surface-2)", borderRadius: 12, overflow: "hidden", marginBottom: 12 }}>
              {Object.entries(config.config).map(([k, v], i) => {
                const isEditable = typeof v !== "object" && !Array.isArray(v);
                return (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 14px", borderTop: i > 0 ? "1px solid var(--border)" : "none", fontSize: 12, gap: 10 }}>
                    <span style={{ color: "var(--text-3)", flexShrink: 0 }}>{k}</span>
                    {editMode && isEditable ? (
                      typeof v === "boolean"
                        ? <select value={String(edits[k] ?? v)}
                            onChange={e => setEdits(p => ({ ...p, [k]: e.target.value }))}
                            style={{ fontSize: 12, padding: "4px 8px", borderRadius: 8, border: "1px solid var(--border)", background: "var(--surface)", color: "var(--text-1)", minWidth: 80 }}>
                            <option value="true">true</option>
                            <option value="false">false</option>
                          </select>
                        : <input type={typeof v === "number" ? "number" : "text"}
                            value={edits[k] ?? v}
                            onChange={e => setEdits(p => ({ ...p, [k]: e.target.value }))}
                            style={{ fontSize: 12, padding: "4px 8px", borderRadius: 8, border: "1px solid var(--brand)", background: "var(--surface)", color: "var(--text-1)", width: 90, textAlign: "right", fontFamily: "monospace" }}/>
                    ) : (
                      <span style={{ fontWeight: 600, fontFamily: "monospace", color: isEditable ? "var(--text-1)" : "var(--text-3)", textAlign: "right" }}>{fmtVal(v)}</span>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Actions */}
        {editMode ? (
          <div style={{ display: "flex", gap: 8 }}>
            <SmallBtn onClick={() => setEditMode(false)}>Cancel</SmallBtn>
            <button onClick={saveEdits} disabled={loading}
              style={{ flex: 2, padding: "10px", borderRadius: 10, fontSize: 14, fontWeight: 700, border: "none", cursor: "pointer", background: "var(--brand)", color: "white" }}>
              Save changes
            </button>
          </div>
        ) : (
          <>
            {/* Start/Stop full width */}
            <button disabled={loading} onClick={() => act(() => API.setConfigRunning(algoId, config.id, !config.running), config.running ? "Stopped" : "Started")}
              style={{ width: "100%", padding: "11px", borderRadius: 12, fontSize: 14, fontWeight: 700, border: "none", cursor: "pointer", marginBottom: 8,
                background: config.running ? "color-mix(in srgb, var(--down) 15%, var(--surface-2))" : "var(--up)",
                color: config.running ? "var(--down)" : "white" }}>
              {config.running ? "⏹  Stop" : "▶  Start"}
            </button>
            {/* Duplicate + Delete row */}
            <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
              <SmallBtn onClick={() => act(() => API.saveConfig(algoId, null, { name: (config.name ?? "Untitled") + " copy", config: config.config ?? {}, running: false }), "Duplicated")}>
                ⧉ Duplicate
              </SmallBtn>
              <SmallBtn danger onClick={() => { if (!window.confirm(`Delete "${config.name ?? "Untitled"}"?`)) return; act(() => API.deleteConfig(algoId, config.id), "Deleted"); }}>
                🗑 Delete
              </SmallBtn>
            </div>
            <button onClick={onClose} style={{ width: "100%", padding: "9px", borderRadius: 10, fontSize: 13, fontWeight: 600, border: "none", cursor: "pointer", background: "transparent", color: "var(--text-3)" }}>
              Cancel
            </button>
          </>
        )}
      </div>
    </div>
  );
};

/* Single algo card with its own live configs */
const AlgoCard = ({ meta, uid, addToast }) => {
  const configs = useAlgoConfigs(meta.id, uid);
  const [sheet, setSheet] = React.useState(null); // config to show in action sheet
  const anyRunning = configs.some(c => c.running);

  return (
    <>
      <div style={{ background: "var(--surface)", borderRadius: 16, overflow: "hidden", border: `1px solid ${anyRunning ? "color-mix(in srgb, var(--up) 40%, var(--border))" : "var(--border)"}` }}>
        {/* Algo header */}
        <div style={{ padding: "14px 16px", display: "flex", alignItems: "center", gap: 12, borderBottom: configs.length > 0 ? "1px solid var(--border)" : "none" }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: anyRunning ? "color-mix(in srgb, var(--up) 15%, var(--surface-2))" : "var(--surface-2)", display: "grid", placeItems: "center", fontSize: 22, flexShrink: 0 }}>
            {meta.icon}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{meta.label}</div>
            <div style={{ fontSize: 11, color: "var(--text-3)" }}>{meta.tagline}</div>
          </div>
          {anyRunning && (
            <div style={{ fontSize: 10, fontWeight: 700, color: "var(--up)", display: "flex", alignItems: "center", gap: 4, background: "color-mix(in srgb, var(--up) 12%, transparent)", padding: "4px 8px", borderRadius: 999 }}>
              <span className="pulse" style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--up)" }}/>
              LIVE
            </div>
          )}
        </div>

        {/* Configs */}
        {configs.length === 0 ? (
          <div style={{ padding: "12px 16px", fontSize: 12, color: "var(--text-3)" }}>
            No configs yet — create one from desktop
          </div>
        ) : (
          configs.map((c, i) => (
            <div key={c.id}
              onClick={() => setSheet(c)}
              style={{
                padding: "13px 16px", display: "flex", alignItems: "center", gap: 12,
                borderTop: "1px solid var(--border)", cursor: "pointer",
                background: c.running ? "color-mix(in srgb, var(--up) 5%, var(--surface))" : "var(--surface)",
                WebkitTapHighlightColor: "transparent",
              }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{c.name ?? "Untitled"}</div>
                <div style={{ fontSize: 11, color: c.running ? "var(--up)" : "var(--text-3)", fontWeight: c.running ? 600 : 400 }}>
                  {c.running ? "● Running" : "Tap to manage"}
                </div>
              </div>
              {/* Toggle switch */}
              <button onClick={e => { e.stopPropagation(); API.setConfigRunning(meta.id, c.id, !c.running).catch(() => {}); }}
                style={{
                  width: 50, height: 28, borderRadius: 999, border: "none", cursor: "pointer",
                  background: c.running ? "var(--up)" : "var(--surface-3)",
                  position: "relative", transition: "background .2s", flexShrink: 0,
                }}>
                <span style={{
                  position: "absolute", top: 4, left: c.running ? 24 : 4,
                  width: 20, height: 20, borderRadius: "50%", background: "white",
                  transition: "left .2s", boxShadow: "0 1px 4px rgba(0,0,0,.25)",
                }}/>
              </button>
              <span style={{ color: "var(--text-3)", fontSize: 16 }}>›</span>
            </div>
          ))
        )}
      </div>

      {/* Action sheet */}
      {sheet && <ConfigSheet config={sheet} algoId={meta.id} addToast={addToast} onClose={() => setSheet(null)}/>}
    </>
  );
};

const MobileStrategies = ({ addToast, uid }) => (
  <div style={{ padding: "20px 16px 0" }}>
    <div style={{ fontSize: 20, fontWeight: 800, marginBottom: 4 }}>Strategies</div>
    <div style={{ fontSize: 13, color: "var(--text-3)", marginBottom: 20 }}>Tap a config to manage · toggle to start/stop</div>
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {MOBILE_ALGO_CATALOG.map(meta => (
        <AlgoCard key={meta.id} meta={meta} uid={uid} addToast={addToast}/>
      ))}
    </div>
    <div style={{ height: 16 }}/>
  </div>
);

/* ════════════════════════════════════════
   TRADES
════════════════════════════════════════ */
const MobileTrades = ({ uid }) => {
  const [trades, setTrades]     = React.useState([]);
  const [dateRange, setDateRange] = React.useState("today");
  const [algoFilter, setAlgoFilter] = React.useState("all");

  React.useEffect(() => {
    if (!uid) return;
    const unsub = API.listenTrades(setTrades, 500);
    return () => unsub();
  }, [uid]);

  const filtered = trades.filter(t => {
    if (algoFilter !== "all" && t.algoId !== algoFilter) return false;
    const now = Date.now();
    const today = new Date().setHours(0, 0, 0, 0);
    if (dateRange === "today" && (t.exitTs ?? 0) < today)             return false;
    if (dateRange === "week"  && (t.exitTs ?? 0) < now - 7 * 86400_000) return false;
    if (dateRange === "month" && (t.exitTs ?? 0) < now - 30 * 86400_000) return false;
    return true;
  });

  const algos = [...new Set(trades.map(t => t.algoId).filter(Boolean))];
  const totalPnl = filtered.reduce((s, t) => s + (t.pnl ?? 0), 0);
  const wins = filtered.filter(t => (t.pnl ?? 0) > 0);
  const winRate = filtered.length ? (wins.length / filtered.length * 100) : 0;

  const fmtM  = (n) => (n >= 0 ? "+" : "") + "₹" + Math.abs(n).toFixed(0);
  const col   = (n) => n >= 0 ? "var(--up)" : "var(--down)";
  const fmtTime = (ts) => ts ? new Date(ts).toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit" }) : "—";
  const fmtDate = (ts) => ts ? new Date(ts).toLocaleDateString("en-IN", { day: "numeric", month: "short" }) : "—";
  const reasonColor = (r) => r === "TP" ? "var(--up)" : r === "SL" ? "var(--down)" : "var(--text-2)";

  return (
    <div style={{ padding: "20px 16px 0" }}>
      <div style={{ fontSize: 20, fontWeight: 800, marginBottom: 16 }}>Strategy Trades</div>

      {/* Summary row */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 16 }}>
        {[
          ["P&L", fmtM(totalPnl), col(totalPnl)],
          ["Trades", filtered.length, "var(--text-1)"],
          ["Win %", winRate.toFixed(0) + "%", winRate >= 50 ? "var(--up)" : "var(--down)"],
        ].map(([l, v, c]) => (
          <div key={l} style={{ background: "var(--surface)", borderRadius: 14, padding: "12px 10px", textAlign: "center" }}>
            <div style={{ fontSize: 10, color: "var(--text-3)", fontWeight: 700, marginBottom: 4 }}>{l}</div>
            <div style={{ fontSize: 16, fontWeight: 800, color: c }}>{v}</div>
          </div>
        ))}
      </div>

      {/* Date filter */}
      <div style={{ display: "flex", gap: 6, marginBottom: 10, overflowX: "auto", paddingBottom: 4 }}>
        {[["today","Today"],["week","7d"],["month","30d"],["all","All"]].map(([v,l]) => (
          <button key={v} onClick={() => setDateRange(v)}
            style={{
              flexShrink: 0, padding: "6px 14px", borderRadius: 999, border: "none", cursor: "pointer", fontSize: 12, fontWeight: 600,
              background: dateRange === v ? "var(--brand)" : "var(--surface-2)",
              color: dateRange === v ? "white" : "var(--text-2)",
            }}>{l}</button>
        ))}
      </div>

      {/* Algo filter */}
      {algos.length > 1 && (
        <div style={{ display: "flex", gap: 6, marginBottom: 14, overflowX: "auto", paddingBottom: 4 }}>
          {["all", ...algos].map(a => (
            <button key={a} onClick={() => setAlgoFilter(a)}
              style={{
                flexShrink: 0, padding: "6px 14px", borderRadius: 999, border: "none", cursor: "pointer", fontSize: 12, fontWeight: 600,
                background: algoFilter === a ? "var(--surface-3)" : "var(--surface-2)",
                color: algoFilter === a ? "var(--text-1)" : "var(--text-3)",
              }}>{a === "all" ? "All" : a}</button>
          ))}
        </div>
      )}

      {/* Trade cards */}
      {filtered.length === 0 ? (
        <div style={{ background: "var(--surface)", borderRadius: 16, padding: "32px 16px", textAlign: "center", color: "var(--text-3)", fontSize: 13 }}>
          No trades in this period
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {filtered.map(t => (
            <div key={t.id} style={{ background: "var(--surface)", borderRadius: 14, padding: "14px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{t.sym ?? "—"}</div>
                  <div style={{ fontSize: 11, color: "var(--text-3)" }}>{t.algoId} · {t.configName ?? "—"}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontWeight: 800, fontSize: 15, color: col(t.pnl ?? 0) }}>{fmtM(t.pnl ?? 0)}</div>
                  <div style={{ fontSize: 11, color: "var(--text-3)" }}>{(t.pnlPct ?? 0).toFixed(1)}%</div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                <span style={{ fontSize: 10, padding: "3px 8px", borderRadius: 999, background: "var(--surface-2)", color: reasonColor(t.exitReason), fontWeight: 700 }}>
                  {t.exitReason}
                </span>
                <span style={{ fontSize: 11, color: "var(--text-3)" }}>{fmtDate(t.exitTs)} · {fmtTime(t.entryTs)}→{fmtTime(t.exitTs)}</span>
                <span style={{ fontSize: 10, padding: "3px 8px", borderRadius: 999, background: t.dummyMode ? "color-mix(in srgb, var(--brand) 15%, transparent)" : "color-mix(in srgb, var(--down) 15%, transparent)", color: t.dummyMode ? "var(--brand)" : "var(--down)", fontWeight: 700 }}>
                  {t.dummyMode ? "🧪" : "⚠️"}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}
      <div style={{ height: 16 }}/>
    </div>
  );
};
