// Meridian mobile — sales-agent app. Reuses primitives.jsx (Icon, Pill, money…) + data.jsx.

const ME = agentById("sofia");
const initialsOf = (n) => n.split(" ").map((x) => x[0]).join("");

/* ---------- shared bits ---------- */
function MToast({ toast }) {
  if (!toast) return null;
  return <div className={`m-toast ${toast.tone === "ok" ? "is-ok" : ""}`}>{toast.title}</div>;
}

function StatChip({ label, value, sub, subColor }) {
  return (
    <div className="m-stat">
      <div className="m-stat-label">{label}</div>
      <div className="m-stat-value">{value}</div>
      {sub && <div className="m-stat-sub" style={{ color: subColor || "var(--text-muted)" }}>{sub}</div>}
    </div>
  );
}

function LeadRow({ lead, onClick }) {
  return (
    <button className="m-row" onClick={onClick}>
      <div className="m-avatar" style={{ background: "var(--brand-soft)", color: "var(--brand)" }}>{initialsOf(lead.name)}</div>
      <div className="m-row-stack">
        <div className="m-row-name">{lead.name}</div>
        <div className="m-row-meta">{devName(lead.dev)}{lead.unit ? " · " + lead.unit : ""}</div>
      </div>
      <div className="m-row-right">
        <Pill tone={lead.status} size="sm" dot>{lead.status}</Pill>
        <span className="m-row-time">{moneyK(lead.value)}</span>
      </div>
    </button>
  );
}

/* ---------- HOME ---------- */
function MHome({ go, openLead, toast }) {
  const m = METRICS;
  const myLeads = LEADS.filter((l) => l.owner === ME.id);
  const myTasks = TASKS.filter((t) => t.owner === ME.id && !t.done);
  const overdue = PAYMENTS.filter((p) => p.agent === ME.id && p.status === "Overdue");
  const greeting = new Date().getHours() < 12 ? "Good morning" : new Date().getHours() < 18 ? "Good afternoon" : "Good evening";
  const typeIcon = { call: "phone", mail: "mail", handshake: "handshake", doc: "doc", calendar: "calendar", payments: "payments" };

  return (
    <>
      <div className="m-header">
        <div className="m-header-row">
          <div style={{ flex: 1 }}>
            <div className="m-header-eyebrow">Monday, June 2</div>
            <div className="m-header-title m-serif" style={{ fontSize: 26 }}>{greeting}, {ME.name.split(" ")[0]}</div>
          </div>
          <div className="m-avatar" style={{ background: ME.color }}>{ME.initials}</div>
        </div>
      </div>
      <div className="m-content">
        <div className="m-stats">
          <StatChip label="New leads" value={m.newLeadsWeek} sub={"↑ " + m.newLeadsDelta} subColor="#1f8a52" />
          <StatChip label="Viewings" value={m.viewingsWeek} sub="4 today" />
          <StatChip label="Reservations" value={m.reservationsMonth} sub={moneyK(m.reservationsValue)} />
          <StatChip label="Pipeline" value={moneyK(m.pipelineValue)} sub="open deals" />
        </div>

        {overdue.length > 0 && (
          <button className="m-card" onClick={() => go("reservations")} style={{ flexDirection: "row", alignItems: "center", gap: 12, borderColor: "rgba(217,84,74,0.35)", background: "rgba(217,84,74,0.06)", cursor: "pointer", textAlign: "left" }}>
            <div className="m-task-icon" style={{ background: "rgba(217,84,74,0.15)", color: "#cf4436" }}><Icon name="clock" size={17} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 650 }}>{overdue.length} overdue payment{overdue.length > 1 ? "s" : ""}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{money(overdue.reduce((s, p) => s + p.amount, 0))} needs chasing</div>
            </div>
            <Icon name="chevronRight" size={16} />
          </button>
        )}

        <div>
          <div className="m-section-label" style={{ marginBottom: 10 }}>Today's tasks<button onClick={() => go("tasks")}>All →</button></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {myTasks.slice(0, 3).map((t) => (
              <div key={t.id} className="m-task">
                <button className={`m-check ${t.priority === "high" ? "is-high" : ""}`} />
                <div className="m-task-icon"><Icon name={typeIcon[t.type] || "note"} size={16} /></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.25 }}>{t.title}</div>
                  <div style={{ fontSize: 11.5, color: "var(--text-muted)", marginTop: 2 }}>{t.time}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div>
          <div className="m-section-label" style={{ marginBottom: 10 }}>Hot leads<button onClick={() => go("leads")}>All →</button></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {[...myLeads].sort((a, b) => b.score - a.score).slice(0, 4).map((l) => <LeadRow key={l.id} lead={l} onClick={() => openLead(l.id)} />)}
          </div>
        </div>
      </div>
    </>
  );
}

/* ---------- LEADS ---------- */
function MLeads({ openLead }) {
  const [filter, setFilter] = React.useState("mine");
  const [q, setQ] = React.useState("");
  const [searching, setSearching] = React.useState(false);
  const base = LEADS.filter((l) => l.owner === ME.id);
  const filters = [
    { id: "mine", label: "All", pred: () => true },
    { id: "new", label: "New", pred: (l) => l.status === "New" },
    { id: "active", label: "Active", pred: (l) => ["Qualified", "Viewing", "Offer"].includes(l.status) },
    { id: "reserved", label: "Reserved", pred: (l) => l.status === "Reservation" },
    { id: "hot", label: "Hot", pred: (l) => l.score >= 75 },
  ];
  let rows = base.filter(filters.find((f) => f.id === filter).pred);
  if (q.trim()) rows = rows.filter((l) => (l.name + l.email).toLowerCase().includes(q.toLowerCase()));

  return (
    <>
      <div className="m-header">
        <div className="m-header-row">
          <div style={{ flex: 1 }}>
            <div className="m-header-title">Leads</div>
            <div className="m-header-eyebrow">{base.length} assigned to you</div>
          </div>
          <button className="m-iconbtn" onClick={() => setSearching((v) => !v)}><Icon name="search" size={18} /></button>
        </div>
        {searching && (
          <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search leads…"
            style={{ marginTop: 10, width: "100%", height: 40, borderRadius: 12, border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--text)", padding: "0 14px", font: "inherit", fontSize: 14, outline: "none" }} />
        )}
        <div className="m-chips" style={{ marginTop: 12, marginBottom: -2 }}>
          {filters.map((f) => (
            <button key={f.id} className={`m-chip ${filter === f.id ? "is-active" : ""}`} onClick={() => setFilter(f.id)}>
              {f.label}<span style={{ opacity: 0.7 }}>{base.filter(f.pred).length}</span>
            </button>
          ))}
        </div>
      </div>
      <div className="m-content">
        {rows.map((l) => <LeadRow key={l.id} lead={l} onClick={() => openLead(l.id)} />)}
        {rows.length === 0 && <div style={{ textAlign: "center", color: "var(--text-muted)", padding: "40px 0", fontSize: 13 }}>No leads match.</div>}
      </div>
    </>
  );
}

/* ---------- LEAD DETAIL ---------- */
function MLeadDetail({ leadId, back, toast }) {
  const base = leadById(leadId) || LEADS[0];
  const c = { ...ACTIVE_LEAD, ...base };
  const unit = c.unit ? unitByCode(c.unit) : null;
  const STAGES = ["New", "Qualified", "Viewing", "Offer", "Reservation", "Closed"];
  const stageIdx = STAGES.indexOf(c.status);
  const acts = [
    { label: "Call", icon: "phone", t: "Calling " + c.name.split(" ")[0] },
    { label: "WhatsApp", icon: "chat", t: "WhatsApp opened" },
    { label: "Email", icon: "mail", t: "Email composer" },
    { label: "Viewing", icon: "calendar", t: "Booking viewing" },
  ];

  return (
    <>
      <div className="m-header">
        <button className="m-back" onClick={back}><Icon name="chevronLeft" size={18} />Leads</button>
        <div className="m-header-row" style={{ marginTop: 8 }}>
          <div className="m-avatar" style={{ background: "var(--brand)", width: 46, height: 46, fontSize: 17 }}>{initialsOf(c.name)}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="m-header-title" style={{ fontSize: 21 }}>{c.name}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 3 }}>
              <Pill tone={c.status} size="sm" dot>{c.status}</Pill>
              <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>Score {c.score}</span>
            </div>
          </div>
        </div>
      </div>
      <div className="m-content">
        <div className="m-actions">
          {acts.map((a) => (
            <button key={a.label} className="m-action" onClick={() => toast({ tone: "ok", title: a.t })}>
              <div className="m-action-ic"><Icon name={a.icon} size={17} /></div>
              <span>{a.label}</span>
            </button>
          ))}
        </div>

        <div className="m-card">
          <div className="m-stages">
            {STAGES.map((s, i) => (
              <div key={s} className="m-stage-seg">
                <div className="m-stage-bar" style={{ background: i <= stageIdx ? STAGE_COLOR[c.status] : "var(--surface-2)" }} />
                <div className="m-stage-lbl" style={{ color: i === stageIdx ? "var(--text)" : "var(--text-faint)", fontWeight: i === stageIdx ? 700 : 500 }}>{s}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="m-card">
          <div className="m-card-title">Interested in</div>
          {unit ? (
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: 10, flexShrink: 0, background: "var(--brand-softer)", color: "var(--brand)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="building" size={20} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <strong className="m-mono" style={{ fontSize: 13, whiteSpace: "nowrap" }}>{unit.code}</strong>
                  <Pill tone={unit.status} size="sm">{unit.status}</Pill>
                </div>
                <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 3 }}>{unit.type} · {unit.size} m² · {unit.view}</div>
              </div>
              <strong style={{ fontSize: 15, whiteSpace: "nowrap" }}>{money(unit.price)}</strong>
            </div>
          ) : (
            <div style={{ fontSize: 13, color: "var(--text-muted)" }}>No unit matched yet · looking at <strong style={{ color: "var(--text)" }}>{devName(c.dev)}</strong>, budget {moneyK(c.budget)}.</div>
          )}
        </div>

        <div className="m-card">
          <div className="m-card-title">Buyer profile</div>
          <div className="m-kv">
            <div><span>Max budget</span><strong>{money(c.budget)}</strong></div>
            <div><span>Deal value</span><strong>{money(c.value)}</strong></div>
            <div><span>Source</span><strong>{c.source}</strong></div>
            <div><span>Created</span><strong>{c.created}</strong></div>
          </div>
          <div style={{ fontSize: 12.5, color: "var(--text-muted)", display: "flex", flexDirection: "column", gap: 2, paddingTop: 4, borderTop: "1px solid var(--border)" }}>
            <span>{c.email}</span><span>{c.phone}</span>
          </div>
        </div>

        <div className="m-card">
          <div className="m-card-title">Notes</div>
          {c.notes.map((n, i) => (
            <div key={i} className="m-note">
              <div className="m-note-head"><strong>{n.author}</strong><span>{n.time}</span></div>
              <div className="m-note-body">{n.text}</div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

/* ---------- PIPELINE ---------- */
const M_STAGES = ["New", "Qualified", "Viewing", "Offer", "Reservation", "Closed"];
function MPipeline({ openLead, toast }) {
  const [, force] = React.useReducer((x) => x + 1, 0);
  const [stage, setStage] = React.useState("Viewing");
  const base = LEADS.filter((l) => l.owner === ME.id && l.status !== "Lost");
  const rows = base.filter((l) => l.status === stage);
  const move = (lead, dir) => {
    const i = M_STAGES.indexOf(lead.status);
    const ni = i + dir;
    if (ni < 0 || ni >= M_STAGES.length) return;
    lead.status = M_STAGES[ni];
    toast({ tone: "ok", title: `${lead.name.split(" ")[0]} → ${lead.status}` });
    force();
  };

  return (
    <>
      <div className="m-header">
        <div className="m-header-title">Pipeline</div>
        <div className="m-header-eyebrow">{base.length} open · {moneyK(base.reduce((s, l) => s + l.value, 0))} value</div>
        <div className="m-chips" style={{ marginTop: 12, marginBottom: -2 }}>
          {M_STAGES.map((s) => (
            <button key={s} className={`m-chip ${stage === s ? "is-active" : ""}`} onClick={() => setStage(s)}>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: STAGE_COLOR[s] }} />
              {s}<span style={{ opacity: 0.7 }}>{base.filter((l) => l.status === s).length}</span>
            </button>
          ))}
        </div>
      </div>
      <div className="m-content">
        {rows.map((l) => (
          <div key={l.id} className="m-deal">
            <button onClick={() => openLead(l.id)} style={{ display: "flex", alignItems: "center", gap: 11, flex: 1, minWidth: 0, border: 0, background: "transparent", color: "var(--text)", textAlign: "left", padding: 0, cursor: "pointer" }}>
              <div className="m-avatar" style={{ background: "var(--brand-soft)", color: "var(--brand)", width: 34, height: 34, fontSize: 12 }}>{initialsOf(l.name)}</div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="m-row-name" style={{ fontSize: 14 }}>{l.name}</div>
                <div className="m-row-meta">{devName(l.dev)} · {moneyK(l.value)}</div>
              </div>
            </button>
            <div className="m-deal-move">
              <button className="m-movebtn" disabled={M_STAGES.indexOf(l.status) === 0} onClick={() => move(l, -1)}><Icon name="chevronLeft" size={15} /></button>
              <button className="m-movebtn" disabled={M_STAGES.indexOf(l.status) === M_STAGES.length - 1} onClick={() => move(l, 1)}><Icon name="chevronRight" size={15} /></button>
            </div>
          </div>
        ))}
        {rows.length === 0 && <div style={{ textAlign: "center", color: "var(--text-muted)", padding: "40px 0", fontSize: 13 }}>No deals in {stage}.</div>}
      </div>
    </>
  );
}

/* ---------- INVENTORY ---------- */
function MInventory({ toast }) {
  const [dev, setDev] = React.useState("marina");
  const [status, setStatus] = React.useState("all");
  let units = UNITS.filter((u) => u.dev === dev);
  if (status !== "all") units = units.filter((u) => u.status === status);

  return (
    <>
      <div className="m-header">
        <div className="m-header-title">Inventory</div>
        <div className="m-header-eyebrow">98 units · 35 available</div>
        <div className="m-chips" style={{ marginTop: 12 }}>
          {DEVELOPMENTS.map((d) => (
            <button key={d.id} className={`m-dev ${dev === d.id ? "is-active" : ""}`} onClick={() => { setDev(d.id); setStatus("all"); }}>
              <div className="m-dev-name">{d.name}</div>
              <div className="m-dev-meta">{d.city} · {d.available} available</div>
            </button>
          ))}
        </div>
        <div className="m-chips" style={{ marginTop: 8, marginBottom: -2 }}>
          {["all", "Available", "Reserved", "Sold"].map((s) => (
            <button key={s} className={`m-chip ${status === s ? "is-active" : ""}`} onClick={() => setStatus(s)}>{s === "all" ? "All" : s}</button>
          ))}
        </div>
      </div>
      <div className="m-content">
        {units.map((u) => (
          <div key={u.id} className="m-unit" onClick={() => toast({ title: u.code + " · " + money(u.price) })}>
            <div className="m-unit-img">
              <span className="m-unit-code">{u.code}</span>
              <Pill tone={u.status} size="sm">{u.status}</Pill>
            </div>
            <div className="m-unit-body">
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 10 }}>
                <strong style={{ fontSize: 15, whiteSpace: "nowrap" }}>{u.type}</strong>
                <span style={{ fontSize: 12, color: "var(--text-muted)", whiteSpace: "nowrap" }}>Floor {u.floor}</span>
              </div>
              <div className="m-unit-specs">
                <span><Icon name="bed" size={14} />{u.beds} bed</span>
                <span><Icon name="ruler" size={14} />{u.size} m²</span>
                <span><Icon name="eye" size={14} />{u.view}</span>
              </div>
              <div className="m-unit-price">{money(u.price)}</div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

/* ---------- TASKS ---------- */
function MTasks({ openLead, toast }) {
  const base = TASKS.filter((t) => t.owner === ME.id);
  const [done, setDone] = React.useState(() => new Set(base.filter((t) => t.done).map((t) => t.id)));
  const [filter, setFilter] = React.useState("open");
  const typeIcon = { call: "phone", mail: "mail", handshake: "handshake", doc: "doc", calendar: "calendar", payments: "payments" };
  const toggle = (id, title) => setDone((s) => { const n = new Set(s); if (n.has(id)) n.delete(id); else { n.add(id); toast({ tone: "ok", title: "Task done" }); } return n; });
  const rows = base.filter((t) => filter === "open" ? !done.has(t.id) : filter === "done" ? done.has(t.id) : true);

  return (
    <>
      <div className="m-header">
        <div className="m-header-title">Tasks</div>
        <div className="m-header-eyebrow">{base.filter((t) => !done.has(t.id)).length} open today</div>
        <div className="m-chips" style={{ marginTop: 12, marginBottom: -2 }}>
          {["open", "done", "all"].map((f) => <button key={f} className={`m-chip ${filter === f ? "is-active" : ""}`} style={{ textTransform: "capitalize" }} onClick={() => setFilter(f)}>{f}</button>)}
        </div>
      </div>
      <div className="m-content">
        {rows.map((t) => {
          const isDone = done.has(t.id);
          return (
            <div key={t.id} className="m-task" style={{ opacity: isDone ? 0.55 : 1 }}>
              <button className={`m-check ${t.priority === "high" && !isDone ? "is-high" : ""} ${isDone ? "is-done" : ""}`} onClick={() => toggle(t.id, t.title)}>{isDone && <Icon name="check" size={13} />}</button>
              <div className="m-task-icon"><Icon name={typeIcon[t.type] || "note"} size={16} /></div>
              <button onClick={() => openLead(t.lead)} style={{ flex: 1, minWidth: 0, border: 0, background: "transparent", textAlign: "left", color: "var(--text)", padding: 0, cursor: "pointer" }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.25, textDecoration: isDone ? "line-through" : "none" }}>{t.title}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-muted)", marginTop: 2 }}>{t.time}{t.priority === "high" && !isDone && <span style={{ color: "#d9544a" }}> · high</span>}</div>
              </button>
            </div>
          );
        })}
        {rows.length === 0 && <div style={{ textAlign: "center", color: "var(--text-muted)", padding: "40px 0", fontSize: 13 }}>Nothing here.</div>}
      </div>
    </>
  );
}

/* ---------- RESERVATIONS ---------- */
function MReservations({ back, openLead }) {
  const base = PAYMENTS.filter((p) => p.agent === ME.id);
  const paid = base.filter((p) => p.status === "Paid").reduce((s, p) => s + p.amount, 0);
  const pending = base.filter((p) => p.status === "Pending").reduce((s, p) => s + p.amount, 0);
  const overdue = base.filter((p) => p.status === "Overdue");
  return (
    <>
      <div className="m-header">
        <button className="m-back" onClick={back}><Icon name="chevronLeft" size={18} />Home</button>
        <div className="m-header-title" style={{ marginTop: 8, fontSize: 22 }}>Reservations</div>
      </div>
      <div className="m-content">
        <div className="m-stats" style={{ gridTemplateColumns: "1fr 1fr 1fr" }}>
          <StatChip label="Collected" value={moneyK(paid)} />
          <StatChip label="Pending" value={moneyK(pending)} />
          <StatChip label="Overdue" value={moneyK(overdue.reduce((s, p) => s + p.amount, 0))} subColor="#cf4436" />
        </div>
        {base.map((p) => {
          const l = leadById(p.lead);
          return (
            <button key={p.id} className="m-row" onClick={() => l && openLead(l.id)} style={{ alignItems: "center" }}>
              <div className="m-row-stack">
                <div className="m-row-name" style={{ fontSize: 14 }}>{l ? l.name : "—"}</div>
                <div className="m-row-meta"><span className="m-mono">{p.unit}</span> · {p.kind}</div>
              </div>
              <div className="m-row-right">
                <strong style={{ fontSize: 14 }}>{money(p.amount)}</strong>
                <Pill tone={p.status} size="sm" dot>{p.status}</Pill>
              </div>
            </button>
          );
        })}
      </div>
    </>
  );
}

/* ---------- COPILOT SHEET ---------- */
function MCopilot({ open, onClose }) {
  if (!open) return null;
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 50, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
      <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.4)" }} onClick={onClose} />
      <div style={{ position: "relative", background: "var(--surface)", borderTopLeftRadius: 24, borderTopRightRadius: 24, padding: "16px 18px 40px", display: "flex", flexDirection: "column", gap: 12, maxHeight: "70%" }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: "var(--border-strong)", alignSelf: "center" }} />
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div className="m-action-ic" style={{ width: 32, height: 32 }}><Icon name="sparkles" size={16} /></div>
          <div style={{ fontWeight: 650, fontSize: 15 }}>Copilot</div>
          <span style={{ fontSize: 11, color: "var(--text-muted)" }}>Lite · read-only</span>
        </div>
        <div style={{ fontSize: 13.5, color: "var(--text-muted)", lineHeight: 1.5 }}>Ask me to summarize a lead, match a buyer to available units, or draft a follow-up message.</div>
        {["Match a buyer to units", "Summarize a lead", "Draft a follow-up"].map((s) => (
          <button key={s} style={{ padding: "12px 14px", borderRadius: 12, border: "1px solid var(--border)", background: "var(--bg)", color: "var(--text)", fontSize: 13.5, fontWeight: 550, textAlign: "left", cursor: "pointer" }}>{s}</button>
        ))}
      </div>
    </div>
  );
}

/* ---------- ROOT ---------- */
const TABS = [
  { id: "home", label: "Home", icon: "home" },
  { id: "leads", label: "Leads", icon: "leads", badge: 6 },
  { id: "pipeline", label: "Pipeline", icon: "pipeline" },
  { id: "inventory", label: "Inventory", icon: "building" },
  { id: "tasks", label: "Tasks", icon: "tasks", badge: 5 },
];

function MobileApp({ dark, accent, currency }) {
  const [screen, setScreen] = React.useState("home");
  const [leadId, setLeadId] = React.useState(null);
  const [copilot, setCopilot] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  setCurrency(currency);
  const showToast = (t) => { setToast(t); setTimeout(() => setToast(null), 2200); };
  const openLead = (id) => { if (!id) return; setLeadId(id); setScreen("lead"); };
  const tab = ["home", "leads", "pipeline", "inventory", "tasks"].includes(screen) ? screen : (screen === "lead" ? "leads" : screen === "reservations" ? "home" : screen);

  return (
    <div className={`m-app ${dark ? "m-dark" : ""}`} style={{ "--brand": accent }}>
      {screen === "home" && <MHome go={setScreen} openLead={openLead} toast={showToast} />}
      {screen === "leads" && <MLeads openLead={openLead} />}
      {screen === "lead" && <MLeadDetail leadId={leadId} back={() => setScreen("leads")} toast={showToast} />}
      {screen === "pipeline" && <MPipeline openLead={openLead} toast={showToast} />}
      {screen === "inventory" && <MInventory toast={showToast} />}
      {screen === "tasks" && <MTasks openLead={openLead} toast={showToast} />}
      {screen === "reservations" && <MReservations back={() => setScreen("home")} openLead={openLead} />}

      {!["lead", "reservations"].includes(screen) && (
        <button className="m-fab" onClick={() => setCopilot(true)}><Icon name="sparkles" size={20} /></button>
      )}

      <nav className="m-tabbar">
        {TABS.map((tb) => (
          <button key={tb.id} className={`m-tab ${tab === tb.id ? "is-active" : ""}`} onClick={() => setScreen(tb.id)} style={{ position: "relative" }}>
            <div style={{ position: "relative" }}>
              <Icon name={tb.icon} size={22} strokeWidth={tab === tb.id ? 2 : 1.7} />
              {tb.badge && <span className="m-tab-badge">{tb.badge}</span>}
            </div>
            <span>{tb.label}</span>
          </button>
        ))}
      </nav>

      <MCopilot open={copilot} onClose={() => setCopilot(false)} />
      <MToast toast={toast} />
    </div>
  );
}

Object.assign(window, { MobileApp });
