/* stream.jsx — Stream section for HomeDayOne.
   Matches the mobile design: filter pills · Coming up · Recent activity.
   `compact` prop = embedded in home scroll (no own scroll container). */

const STREAM_COMING = [
  { id: "cu1", icon: "trade",   logo: true,  title: "Weekly investing · VTI",  sub: "Automation",                             amount: -500,   when: "Fri · Jun 5",  cat: "automations" },
  { id: "cu2", icon: "card",    logo: false, title: "Netflix",                  sub: "Subscription · Yoshi card ••4417",       amount: -24.99, when: "Sun · Jun 8",   cat: "spending" },
  { id: "cu3", icon: "bank",    logo: false, title: "Pay day",                  sub: "Direct deposit to Yoshi brokerage ••3456", amount: 8200, when: "Mon · Jun 15",  cat: "income" },
];

const STREAM_RECENT = [
  { id: "r1", icon: "receipt", logo: false, title: "Whole Foods Market",        sub: "Card ••4417",                            amount: -142.38,  when: "Today",      amountLabel: null, cat: "spending" },
  { id: "r2", icon: "down",    logo: false, title: "Payroll · Northwind Labs",  sub: "Direct deposit",                         amount:  8200,    when: "Today",      amountLabel: null, cat: "income" },
  { id: "r3", icon: "trade",   logo: true,  title: "Weekly investing · VTI",   sub: "Every Friday · 11 weeks",                amount:  184,     when: "this month", amountLabel: "+$184", cat: "automations" },
  { id: "r4", icon: "trade",   logo: true,  title: "Swept idle cash",           sub: "Checking to Savings · Cash agent",       amount:  null,    when: "May 28",     amountLabel: "moved", cat: "automations" },
  { id: "r5", icon: "swap",    logo: false, title: "Sent to Maya Cohen",        sub: "Zelle ••4471",                           amount: -250,     when: "May 28",     amountLabel: null, cat: "transfers" },
];

const STREAM_FILTERS = [
  ["all",         "All"],
  ["automations", "Automations"],
  ["spending",    "Spending"],
  ["investments", "Investments"],
];

/* icon cell — Yoshi logo for agent moves, schematic icon otherwise */
const SIcon = ({ icon, logo }) => (
  <span style={{ width: 38, height: 38, flex: "none", display: "grid", placeItems: "center", color: "var(--ink-3)" }}>
    {logo
      ? <Logo size={22} color="var(--ink-2)" />
      : <Icon name={icon} size={19} stroke={1.5} color="var(--ink-3)" />}
  </span>
);

/* amount display: integer bold, decimals dimmed */
const SAmount = ({ amount, amountLabel, positive }) => {
  if (amountLabel) {
    return (
      <span style={{ fontFamily: "var(--f-mono)", fontSize: 13, fontVariantNumeric: "tabular-nums", color: positive ? "var(--accent-pos)" : "var(--ink-2)" }}>
        {amountLabel}
      </span>
    );
  }
  if (amount == null) return null;
  const abs = Math.abs(amount);
  const sign = amount >= 0 ? "+" : "−";
  const whole = Math.floor(abs).toLocaleString("en-US");
  const dec = (abs % 1).toFixed(2).slice(1); // ".38"
  const color = amount >= 0 ? "var(--accent-pos)" : "var(--ink)";
  return (
    <span style={{ fontFamily: "var(--f-mono)", fontSize: 13.5, fontVariantNumeric: "tabular-nums", color }}>
      {sign}${whole}<span style={{ color: "var(--ink-3)", fontSize: 11 }}>{dec}</span>
    </span>
  );
};

const StreamRow = ({ item, last, onOpen }) => {
  const pos = item.amount > 0 || (item.amountLabel && item.amountLabel.startsWith("+"));
  const tappable = !!onOpen;
  return (
    <button type="button" disabled={!tappable} className={tappable ? "press" : undefined} onClick={tappable ? () => onOpen(item) : undefined} style={{
      width: "100%", textAlign: "left", background: "none", border: "none", font: "inherit", color: "inherit", cursor: tappable ? "pointer" : "default",
      display: "grid", gridTemplateColumns: "42px 1fr auto", gap: 10,
      alignItems: "center", padding: "10px 18px",
      borderBottom: last ? "none" : "1px solid var(--rule)",
    }}>
      <SIcon icon={item.icon} logo={item.logo} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "var(--f-display)", fontSize: 14, fontWeight: 500, letterSpacing: "-0.005em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {item.title}
        </div>
        <div style={{ fontFamily: "var(--f-display)", fontSize: 11.5, color: "var(--ink-3)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {item.sub}
        </div>
      </div>
      <div style={{ textAlign: "right", whiteSpace: "nowrap" }}>
        <SAmount amount={item.amount} amountLabel={item.amountLabel} positive={pos} />
        <div style={{ fontFamily: "var(--f-display)", fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{item.when}</div>
      </div>
    </button>
  );
};

const StreamView = ({ externals = [], compact = false, onOpen }) => {
  const hasInvest = externals.some((e) => e.type === "Brokerage" || e.type === "Crypto");
  const [filter, setFilter] = useState("all");
  const [searchOpen, setSearchOpen] = useState(false);
  const [query, setQuery] = useState("");

  const filterRows = (rows) => {
    let out = rows;
    if (filter !== "all") out = out.filter((r) => r.cat === filter || (filter === "investments" && r.cat === "income" && r.logo));
    if (query.trim()) out = out.filter((r) => `${r.title} ${r.sub}`.toLowerCase().includes(query.trim().toLowerCase()));
    return out;
  };

  const coming  = filterRows(STREAM_COMING);
  const recent  = filterRows(STREAM_RECENT);

  return (
    <div style={{ flex: compact ? undefined : 1, minHeight: 0, display: "flex", flexDirection: "column" }}>

      {/* filter pills + search */}
      <div style={{ flex: "none", padding: "0 18px 10px", display: "flex", alignItems: "center", gap: 0 }}>
        <div className="hcar" style={{ display: "flex", gap: 7, overflowX: "auto", flex: 1, minWidth: 0 }}>
          {STREAM_FILTERS.map(([k, l]) => {
            const on = filter === k;
            return (
              <button key={k} className="press" onClick={() => setFilter(k)} style={{
                flex: "none", padding: "5px 13px", borderRadius: 999,
                background: on ? "color-mix(in srgb, var(--ink) 15%, var(--bg-2))" : "var(--bg-2)",
                color: on ? "var(--ink)" : "var(--ink-2)",
                border: `1px solid ${on ? "color-mix(in srgb, var(--ink) 15%, var(--rule-2))" : "var(--rule-2)"}`,
                fontFamily: "var(--f-display)", fontSize: 12, fontWeight: 600,
                whiteSpace: "nowrap", cursor: "pointer",
              }}>{l}</button>
            );
          })}
        </div>
        <button className="press" onClick={() => { setSearchOpen(o => !o); setQuery(""); }}
          style={{ flex: "none", marginLeft: 8, background: "none", border: "none", padding: 2, display: "flex", color: searchOpen ? "var(--ink)" : "var(--ink-3)", cursor: "pointer" }}>
          <Icon name={searchOpen ? "close" : "search"} size={17} stroke={1.5} />
        </button>
      </div>

      {searchOpen && (
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 12px", margin: "0 18px 10px", background: "var(--bg-2)", border: "1px solid var(--rule-2)", borderRadius: 10 }}>
          <Icon name="search" size={14} color="var(--ink-3)" stroke={1.5} />
          <input autoFocus value={query} onChange={e => setQuery(e.target.value)} placeholder="Search activity"
            style={{ flex: 1, border: "none", background: "transparent", outline: "none", color: "var(--ink)", fontFamily: "var(--f-display)", fontSize: 13 }} />
          {query && <button className="press" onClick={() => setQuery("")} style={{ background: "none", border: "none", display: "flex", color: "var(--ink-3)", padding: 0 }}><Icon name="close" size={13} /></button>}
        </div>
      )}

      <div style={{ borderTop: "1px solid var(--rule)" }} />

      {/* coming up */}
      {coming.length > 0 && (
        <div>
          <div style={{ padding: "14px 18px 8px", fontFamily: "var(--f-display)", fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em" }}>Coming up</div>
          {coming.map((item, i) => <StreamRow key={item.id} item={item} last={i === coming.length - 1} onOpen={onOpen} />)}
        </div>
      )}

      {/* recent activity */}
      {recent.length > 0 && (
        <div>
          <div style={{ padding: "18px 18px 8px", borderTop: coming.length > 0 ? "1px solid var(--rule)" : "none", fontFamily: "var(--f-display)", fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em" }}>Recent activity</div>
          {recent.map((item, i) => <StreamRow key={item.id} item={item} last={i === recent.length - 1} onOpen={onOpen} />)}
        </div>
      )}

      {coming.length === 0 && recent.length === 0 && (
        <div style={{ padding: "32px 18px", textAlign: "center", fontFamily: "var(--f-display)", fontSize: 13, color: "var(--ink-3)" }}>
          {query ? `No activity matches "${query}".` : "Nothing in this filter yet."}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { StreamView });
