// Dashboard — Supabase-backed (with localStorage fallback for local dev)
const { useState, useEffect, useRef, useMemo } = React;

// ---------- localStorage helpers (used only when Supabase isn't configured) ----------
const lsGet = (k, fallback) => {
  try {
    const raw = localStorage.getItem(k);
    if (raw == null) return fallback;
    return JSON.parse(raw);
  } catch (e) {
    return fallback;
  }
};
const lsSet = (k, v) => {
  try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {}
};

// ---------- Date helpers ----------
const todayStr = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};
const nowTimeStr = () => {
  const d = new Date();
  let h = d.getHours();
  const m = String(d.getMinutes()).padStart(2, "0");
  const ap = h >= 12 ? "PM" : "AM";
  h = h % 12; if (h === 0) h = 12;
  return `${h}:${m} ${ap}`;
};
const computeStreak = (logs) => {
  if (!logs || logs.length === 0) return 0;
  const dates = new Set(logs.map(l => l.date));
  let streak = 0;
  const d = new Date();
  for (let i = 0; i < 365; i++) {
    const ds = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
    if (dates.has(ds)) {
      streak++;
      d.setDate(d.getDate() - 1);
    } else {
      if (i === 0) { d.setDate(d.getDate() - 1); continue; }
      break;
    }
  }
  return streak;
};

// ---------- Sidebar ----------
const SidebarIcon = ({ k }) => {
  const common = { width: 18, height: 18, viewBox: "0 0 18 18", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (k) {
    case "home": return <svg {...common}><path d="M3 8 L9 3 L15 8 V15 H3 Z" /></svg>;
    case "stack": return <svg {...common}><rect x="3" y="4" width="12" height="3" rx="1" /><rect x="3" y="9" width="12" height="3" rx="1" /><rect x="3" y="14" width="12" height="2" rx="1" /></svg>;
    case "labs": return <svg {...common}><path d="M7 3 V7 L4 13 C3.5 14 4 15 5 15 H13 C14 15 14.5 14 14 13 L11 7 V3" /></svg>;
    case "timeline": return <svg {...common}><path d="M3 9 H15 M6 6 V12 M12 6 V12" /></svg>;
    case "learn": return <svg {...common}><path d="M3 4 H9 V15 H3 Z M9 4 L15 4 V15 L9 15" /></svg>;
    case "supply": return <svg {...common}><path d="M6 2 H12 V5 M5 5 H13 V16 H5 Z M7 9 H11" /></svg>;
    case "splat": return <svg viewBox="0 0 80 60" width="18" height="14"><path d="M18 44 Q12 20 40 16 Q68 20 62 44 Q64 52 58 52 Q50 48 40 52 Q30 48 22 52 Q16 52 18 44 Z" fill="currentColor" /></svg>;
    case "signout": return <svg {...common}><path d="M11 3 H4 V15 H11 M8 9 H15 M12 6 L15 9 L12 12" /></svg>;
    default: return <svg {...common}><circle cx="9" cy="9" r="6" /></svg>;
  }
};

const Sidebar = ({ active, onNav, onAppNav, stackCount, lowSupplyCount, streak, onSignOut, userEmail }) => (
  <aside className="sidebar">
    {onSignOut && (
      <div
        onClick={onSignOut}
        className="sb-item"
        title={userEmail ? `Signed in as ${userEmail}` : "Sign out"}
        style={{
          marginBottom: 6,
          color: "var(--muted)",
          fontFamily: "var(--mono)",
          fontSize: 11,
          textTransform: "uppercase",
          letterSpacing: "0.1em",
        }}
      >
        <span className="ic"><SidebarIcon k="signout" /></span>
        Sign out
      </div>
    )}
    <div className="sb-section">Dashboard</div>
    <div className={`sb-item ${active === "today" ? "active" : ""}`} onClick={() => onNav("today")}><span className="ic"><SidebarIcon k="home" /></span>Today</div>
    <div className={`sb-item ${active === "stack" ? "active" : ""}`} onClick={() => onNav("stack")}><span className="ic"><SidebarIcon k="stack" /></span>My Stack<span className="count">{stackCount}</span></div>
    <div className={`sb-item ${active === "timeline" ? "active" : ""}`} onClick={() => onNav("timeline")}><span className="ic"><SidebarIcon k="timeline" /></span>Cycle Timeline</div>
    <div className={`sb-item ${active === "labs" ? "active" : ""}`} onClick={() => onNav("labs")}><span className="ic"><SidebarIcon k="labs" /></span>Labs &amp; Biomarkers</div>
    <div className={`sb-item ${active === "supply" ? "active" : ""}`} onClick={() => onNav("supply")}><span className="ic"><SidebarIcon k="supply" /></span>Supply{lowSupplyCount > 0 && <span className="count">{lowSupplyCount}</span>}</div>

    <div className="sb-section" style={{ marginTop: 16 }}>Learn</div>
    <div className="sb-item" onClick={() => onAppNav && onAppNav("learn")}><span className="ic"><SidebarIcon k="learn" /></span>Weekly Reader</div>
    <div className="sb-item" onClick={() => onAppNav && onAppNav("index")}><span className="ic"><SidebarIcon k="learn" /></span>Peptide Index</div>

    <div className="sb-section" style={{ marginTop: 16 }}>Pal</div>
    <div className={`sb-item ${active === "chat" ? "active" : ""}`} onClick={() => onNav("chat")}><span className="ic" style={{ color: "var(--splat-deep)" }}><SidebarIcon k="splat" /></span>Chat with Splat</div>

    <div style={{ marginTop: "auto", padding: 10 }}>
      <div style={{ background: "var(--cream-2)", border: "1px solid var(--line)", borderRadius: 12, padding: 12, fontSize: 12 }}>
        <div style={{ fontFamily: "var(--mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--muted)", marginBottom: 6 }}>Streak</div>
        <div style={{ fontFamily: "var(--serif)", fontSize: 28, lineHeight: 1 }}>{streak} days</div>
        <div style={{ color: "var(--muted)", marginTop: 2 }}>on schedule, pal 🫧</div>
      </div>
    </div>
  </aside>
);

// ---------- Modal shell ----------
const Modal = ({ onClose, title, children, width = 520 }) => (
  <>
    <div
      onClick={onClose}
      style={{ position: "fixed", inset: 0, background: "rgba(15,31,44,0.4)", zIndex: 90, animation: "fade 0.2s ease" }}
    />
    <div
      style={{
        position: "fixed", top: "50%", left: "50%", transform: "translate(-50%, -50%)",
        width, maxWidth: "92vw", maxHeight: "84vh", overflow: "hidden",
        background: "var(--cream)", border: "1.5px solid var(--ink)", borderRadius: 18,
        boxShadow: "0 12px 0 var(--ink)", zIndex: 91, display: "flex", flexDirection: "column",
      }}
    >
      <div style={{
        padding: "16px 20px", borderBottom: "1px solid var(--line)",
        display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--cream)",
      }}>
        <span className="caps" style={{ color: "var(--splat-deep)", fontFamily: "var(--mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.12em" }}>{title}</span>
        <button className="btn" onClick={onClose}>Close ×</button>
      </div>
      <div style={{ padding: 20, overflowY: "auto" }}>{children}</div>
    </div>
  </>
);

// ---------- Toast ----------
const Toast = ({ msg }) => msg ? (
  <div style={{
    position: "fixed", bottom: 30, left: "50%", transform: "translateX(-50%)",
    background: "var(--ink)", color: "var(--cream)", padding: "10px 18px",
    borderRadius: 999, fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.06em",
    zIndex: 95, boxShadow: "0 4px 0 rgba(0,0,0,0.2)",
  }}>{msg}</div>
) : null;

// ---------- Tiles ----------
const StackTile = ({ stack, onToggle, onSelect, onAdd, onRemove }) => {
  const doneCount = stack.filter(s => s.done).length;
  return (
    <div className="card tile stack-tile">
      <h3>
        <span>Today's Stack · {doneCount} of {stack.length} logged</span>
        <span className="tile-action" onClick={onAdd}>+ Add peptide</span>
      </h3>
      <div className="stack-list">
        {stack.length === 0 && (
          <div style={{ padding: 18, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
            Your stack is empty. <span style={{ color: "var(--splat-deep)", cursor: "pointer", textDecoration: "underline" }} onClick={onAdd}>Add a peptide</span> to get started.
          </div>
        )}
        {stack.map((s, i) => {
          const p = PEPTIDES.find(x => x.id === s.id);
          if (!p) return null;
          return (
            <div key={s._key || i} className={`stack-row ${s.done ? "done" : ""}`} onClick={() => onSelect(p)} style={{ position: "relative" }}>
              <div className="chip" style={{ background: p.color }}>{p.name[0]}</div>
              <div>
                <div className="nm">{p.name}</div>
                <div className="sub">{p.tagline}</div>
              </div>
              <div className="dose">{s.dose}</div>
              <div className="when">{s.when}</div>
              <div
                className="tick"
                onClick={(e) => { e.stopPropagation(); onToggle(i); }}
                title={s.done ? "Logged" : "Mark done"}
              >
                {s.done ? "✓" : ""}
              </div>
              <span
                onClick={(e) => { e.stopPropagation(); if (window.confirm(`Remove ${p.name} from stack?`)) onRemove(i); }}
                title="Remove from stack"
                style={{
                  position: "absolute", top: 4, right: 4, width: 18, height: 18, borderRadius: "50%",
                  display: "grid", placeItems: "center", fontSize: 11, color: "var(--muted)",
                  cursor: "pointer", lineHeight: 1,
                }}
                onMouseEnter={(e) => { e.currentTarget.style.background = "var(--coral)"; e.currentTarget.style.color = "white"; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--muted)"; }}
              >×</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const SplatTile = ({ tipIndex, tips, onOpenChat, onCycleTip }) => (
  <div className="card tile splat-tile">
    <div className="pic">
      <div className="splat-floating">
        <Splat size={180} expression={tips[tipIndex].expression} />
      </div>
      <div style={{ position: "absolute", top: 12, left: 14 }}>
        <span className="caps" style={{ color: "var(--splat-deep)" }}>● Splat · online</span>
      </div>
      <button
        onClick={onCycleTip}
        style={{
          position: "absolute", bottom: 12, right: 14,
          fontFamily: "var(--mono)", fontSize: 10,
          background: "rgba(255,255,255,0.8)", padding: "4px 10px",
          borderRadius: 999, border: "1px solid var(--ink)",
          cursor: "pointer", textTransform: "uppercase", letterSpacing: "0.1em",
        }}
      >next tip →</button>
    </div>
    <div className="caption">
      <div className="bubble">
        <strong style={{ color: "var(--splat-deep)" }}>{tips[tipIndex].tag}</strong><br />
        {tips[tipIndex].text}
      </div>
      <button className="splat-chat-btn" onClick={onOpenChat}>
        <SplatBadge size={20} expression="happy" />
        Chat with Splat
      </button>
    </div>
  </div>
);

const Timeline = ({ rows, editMode, onToggleEdit, onChangeRow, onSave }) => {
  const weeks = Array.from({ length: 12 }, (_, i) => i + 1);
  const today = 5.4;
  const colors = { reta: "#2F8C3A", tesa: "#F26B4A", motsc: "#F2C94C", ghkcu: "#7FB8D6", mt2: "#B9A7D6" };
  const fallback = (id) => {
    const p = PEPTIDES.find(x => x.id === id);
    return (p && p.color) || "#5FBF5F";
  };
  return (
    <div className="card tile timeline-tile">
      <h3>
        <span>Cycle Timeline · 12 weeks</span>
        <span className="tile-action" onClick={editMode ? onSave : onToggleEdit}>
          {editMode ? "Save" : "Edit protocol"}
        </span>
      </h3>
      <div className="timeline-wrap">
        <div className="timeline-grid">
          <div />
          <div className="timeline-weeks">
            {weeks.map(w => (
              <span key={w} className={Math.floor(today) + 1 === w ? "current" : ""}>W{w}</span>
            ))}
          </div>
        </div>

        {rows.map((row, idx) => {
          const p = PEPTIDES.find(x => x.id === row.id);
          if (!p) return null;
          const left = (row.start / 12) * 100;
          const width = ((row.end - row.start) / 12) * 100;
          const color = colors[row.id] || fallback(row.id);
          return (
            <div key={row._key || idx} className="timeline-row">
              <div className="timeline-label">
                <span className="mini-chip" style={{ background: color }} />
                {p.name}
              </div>
              <div className="timeline-bar-track" style={{ position: "relative" }}>
                {!editMode && (
                  <div
                    className={`timeline-bar ${row.striped ? "striped" : ""}`}
                    style={{
                      left: `${left}%`, width: `${width}%`,
                      background: color, opacity: row.active ? 1 : 0.55,
                    }}
                  >{row.label}</div>
                )}
                {editMode && (
                  <div style={{
                    display: "flex", gap: 8, alignItems: "center",
                    padding: "4px 6px", fontFamily: "var(--mono)", fontSize: 11,
                  }}>
                    <span style={{ color: "var(--muted)" }}>start</span>
                    <input
                      type="number" min="0" max="12" value={row.start}
                      onChange={(e) => onChangeRow(idx, { start: Math.max(0, Math.min(12, +e.target.value || 0)) })}
                      style={{ width: 50, padding: "3px 6px", border: "1px solid var(--ink)", borderRadius: 6, fontFamily: "var(--mono)" }}
                    />
                    <span style={{ color: "var(--muted)" }}>end</span>
                    <input
                      type="number" min="0" max="12" value={row.end}
                      onChange={(e) => onChangeRow(idx, { end: Math.max(0, Math.min(12, +e.target.value || 0)) })}
                      style={{ width: 50, padding: "3px 6px", border: "1px solid var(--ink)", borderRadius: 6, fontFamily: "var(--mono)" }}
                    />
                    <label style={{ display: "flex", alignItems: "center", gap: 4, color: "var(--muted)" }}>
                      <input type="checkbox" checked={!!row.active} onChange={(e) => onChangeRow(idx, { active: e.target.checked })} />
                      active
                    </label>
                  </div>
                )}
                {idx === 0 && !editMode && (
                  <div className="timeline-today" style={{ left: `${(today / 12) * 100}%` }} />
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const Biomarkers = () => (
  <div className="card tile biomarker-tile">
    <h3><span>Biomarkers · last 10 weeks</span><span className="tile-action">See all</span></h3>
    <div className="biomarker-grid">
      {BIOMARKERS.map((b, i) => (
        <div key={i} className="bio-card">
          <div className="lbl">
            <span>{b.lbl}</span>
            <span className={`delta ${b.dir}`}>{b.delta}</span>
          </div>
          <div className="val">{b.val}<span className="unit">{b.unit}</span></div>
          <Sparkline data={b.chart} color={b.dir === "up" ? "#2F8C3A" : b.dir === "down" ? "#2F8C3A" : "#B37A10"} />
        </div>
      ))}
    </div>
  </div>
);

const LabsTile = ({ labs, onUpload }) => {
  const inputRef = useRef(null);
  return (
    <div className="card tile labs-tile">
      <h3><span>Labs &amp; Uploads</span><span className="tile-action">Request panel</span></h3>
      <input
        ref={inputRef}
        type="file"
        accept=".pdf,image/*"
        style={{ display: "none" }}
        onChange={(e) => {
          const f = e.target.files && e.target.files[0];
          if (f) onUpload(f.name);
          e.target.value = "";
        }}
      />
      <div className="lab-upload" onClick={() => inputRef.current && inputRef.current.click()} style={{ cursor: "pointer" }}>
        <div className="icon">+</div>
        <div>
          <div className="msg">Drop a PDF or photo of your lab results</div>
          <div className="sub">Splat will rewrite acronyms and flag anything worth a doctor's eye.</div>
        </div>
      </div>
      <div style={{ marginTop: 16 }}>
        {labs.map((l, i) => (
          <div key={l._key || i} className="lab-row">
            <div>
              <div className="lab-nm">{l.nm}</div>
              <div className="lab-date">{l.date}</div>
            </div>
            <span className={`pill ${l.status === "Flagged" ? "coral" : l.status === "Processing" ? "sun" : "green"}`}>{l.status}</span>
            <span className="mono" style={{ color: "var(--muted)" }}>{l.fileName ? "PDF" : "PDF"}</span>
            <span className="mono" style={{ color: "var(--ink)", cursor: "pointer" }}>open →</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const SupplyTile = ({ supply, onReorder }) => (
  <div className="card tile supply-tile">
    <h3><span>Supply · cabinet check</span><span className="tile-action" onClick={onReorder}>Reorder list</span></h3>
    {supply.map((s, i) => {
      const p = PEPTIDES.find(x => x.id === s.id);
      if (!p) return null;
      return (
        <div key={s._key || i} className="supply-row">
          <div className="vial">
            <span className="cap" />
            <span style={{
              position: "absolute", left: 0, right: 0, bottom: 0,
              height: `${s.level}%`, background: p.color,
              borderTop: "1.5px solid var(--ink)",
            }} />
          </div>
          <div>
            <div className="nm">{p.name}</div>
            <div className="sub">
              {s.low ? <span style={{ color: "var(--coral)" }}>● reorder soon</span> : `${s.level}% remaining`}
            </div>
          </div>
          <div className="pct">{s.level}%</div>
          <div className="days">{s.daysLeft} days left</div>
        </div>
      );
    })}
  </div>
);

const ArticlesMini = ({ onNav }) => {
  const artMap = {
    titration: Chart_Titration, amino: Chart_AminoChain, routine: Chart_Routine,
    mitoflex: Chart_MitoFlex, thermometer: Chart_Thermometer, faq: Chart_FAQ,
    receptor: Chart_Receptor, halflife: Chart_HalfLife, stacks: Chart_Stacks,
    bruise: Chart_Bruise, subq: Chart_SubQ, skinproto: Chart_SkinProto,
    qa: Chart_QA, sites: Chart_Sites,
  };
  return (
    <div className="card articles-tile">
      <h3 style={{ fontFamily: "var(--mono)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.14em", color: "var(--muted)", margin: "0 0 14px", display: "flex", justifyContent: "space-between" }}>
        <span>For you · Splat's Reader</span>
        <span
          onClick={() => onNav && onNav("learn")}
          style={{ color: "var(--ink)", fontFamily: "var(--mono)", fontSize: 10, cursor: "pointer", padding: "3px 8px", borderRadius: 999, background: "var(--cream-2)" }}
        >
          browse all →
        </span>
      </h3>
      {ARTICLES.slice(0, 4).map((a, i) => {
        const Art = artMap[a.art];
        const openArticle = () => onNav && onNav("article", a.id);
        return (
          <div key={a.id || i} className="mini-article" onClick={openArticle} style={{ cursor: "pointer" }}>
            <div className="thumb" style={{ display: "block", position: "relative" }}>
              {Art ? <Art /> : null}
            </div>
            <div>
              <div className="tag">{a.tag} · {a.readTime}</div>
              <div className="mini-title">{a.title}</div>
              <div className="meta">matches: {i % 2 === 0 ? "Retatrutide" : "Tesamorelin"} in your stack</div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

// Recent activity
const RecentActivity = ({ logs, symptoms }) => {
  const items = useMemo(() => {
    const a = (logs || []).map(l => ({ kind: "dose", date: l.date, time: l.when, text: `Logged ${l.dose} ${(PEPTIDES.find(p => p.id === l.id) || {}).name || l.id}` }));
    const b = (symptoms || []).map(s => ({ kind: "symptom", date: s.date, time: "", text: `Symptom: ${s.text}` }));
    return [...a, ...b].sort((x, y) => (y.date + " " + (y.time || "")).localeCompare(x.date + " " + (x.time || ""))).slice(0, 5);
  }, [logs, symptoms]);
  if (items.length === 0) return null;
  return (
    <div className="card tile" style={{ gridColumn: "span 12" }}>
      <h3><span>Recent activity</span><span className="tile-action">{items.length} entries</span></h3>
      <div style={{ display: "grid", gap: 8 }}>
        {items.map((it, i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, alignItems: "center",
            padding: "10px 14px", border: "1px solid var(--line)", borderRadius: 12, background: "var(--cream)",
          }}>
            <span className={`pill ${it.kind === "dose" ? "green" : "sun"}`} style={{ textTransform: "uppercase", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.1em" }}>
              {it.kind}
            </span>
            <span style={{ fontSize: 13 }}>{it.text}</span>
            <span className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>{it.date}{it.time ? ` · ${it.time}` : ""}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ---------- Modals: AddPeptide, LogDose, LogSymptom, ReorderList ----------
const AddPeptideModal = ({ onClose, onPick, currentIds }) => {
  const [q, setQ] = useState("");
  const list = PEPTIDES.filter(p => !currentIds.includes(p.id) && (p.name.toLowerCase().includes(q.toLowerCase()) || p.tag.toLowerCase().includes(q.toLowerCase())));
  return (
    <Modal onClose={onClose} title="Add a peptide to your stack" width={560}>
      <input
        autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search peptides…"
        style={{
          width: "100%", padding: "10px 14px", border: "1.5px solid var(--ink)", borderRadius: 10,
          fontFamily: "var(--mono)", fontSize: 13, marginBottom: 14, background: "var(--paper)",
        }}
      />
      <div style={{ display: "grid", gap: 8, maxHeight: 420, overflowY: "auto" }}>
        {list.length === 0 && (
          <div style={{ padding: 16, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
            No matches. Try another search.
          </div>
        )}
        {list.map(p => (
          <div key={p.id} onClick={() => onPick(p)} style={{
            display: "grid", gridTemplateColumns: "44px 1fr auto", gap: 12, alignItems: "center",
            padding: 12, border: "1px solid var(--line)", borderRadius: 12, cursor: "pointer", background: "var(--cream)",
          }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--ink)"; e.currentTarget.style.background = "var(--paper)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.background = "var(--cream)"; }}
          >
            <div style={{
              width: 44, height: 44, borderRadius: 12, background: p.color, color: "white",
              display: "grid", placeItems: "center", fontFamily: "var(--serif)", fontSize: 22,
            }}>{p.name[0]}</div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{p.name}</div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{p.tagline}</div>
            </div>
            <span className="pill green" style={{ fontSize: 10 }}>{p.tag}</span>
          </div>
        ))}
      </div>
    </Modal>
  );
};

const LogDoseModal = ({ onClose, stack, onSave }) => {
  const [pid, setPid] = useState((stack[0] && stack[0].id) || "");
  const [dose, setDose] = useState("");
  const [when, setWhen] = useState(nowTimeStr());
  useEffect(() => {
    const s = stack.find(x => x.id === pid);
    if (s && !dose) setDose(s.dose);
  }, [pid]);
  const submit = (e) => {
    e.preventDefault();
    if (!pid) return;
    onSave({ id: pid, dose: dose || "—", when: when || nowTimeStr(), date: todayStr() });
  };
  return (
    <Modal onClose={onClose} title="Log a dose">
      <form onSubmit={submit} style={{ display: "grid", gap: 14 }}>
        <div>
          <label style={{ fontFamily: "var(--mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--muted)" }}>Peptide</label>
          <select value={pid} onChange={(e) => setPid(e.target.value)} style={{
            width: "100%", padding: "10px 12px", marginTop: 6,
            border: "1.5px solid var(--ink)", borderRadius: 10, fontFamily: "var(--mono)", fontSize: 13, background: "var(--paper)",
          }}>
            {stack.length === 0 && <option value="">— stack is empty —</option>}
            {stack.map(s => {
              const p = PEPTIDES.find(x => x.id === s.id);
              return p ? <option key={s.id} value={s.id}>{p.name}</option> : null;
            })}
          </select>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div>
            <label style={{ fontFamily: "var(--mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--muted)" }}>Dose</label>
            <input value={dose} onChange={(e) => setDose(e.target.value)} placeholder="e.g. 4 mg"
              style={{ width: "100%", padding: "10px 12px", marginTop: 6, border: "1.5px solid var(--ink)", borderRadius: 10, fontFamily: "var(--mono)", fontSize: 13, background: "var(--paper)" }}
            />
          </div>
          <div>
            <label style={{ fontFamily: "var(--mono)", fontSize: 10, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--muted)" }}>Time</label>
            <input value={when} onChange={(e) => setWhen(e.target.value)} placeholder="e.g. 7:30 AM"
              style={{ width: "100%", padding: "10px 12px", marginTop: 6, border: "1.5px solid var(--ink)", borderRadius: 10, fontFamily: "var(--mono)", fontSize: 13, background: "var(--paper)" }}
            />
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 6 }}>
          <button type="button" className="btn" onClick={onClose}>Cancel</button>
          <button type="submit" className="btn ink" disabled={!pid}>Save log →</button>
        </div>
      </form>
    </Modal>
  );
};

const LogSymptomModal = ({ onClose, onSave }) => {
  const [text, setText] = useState("");
  const submit = (e) => {
    e.preventDefault();
    const t = text.trim();
    if (!t) return;
    onSave({ date: todayStr(), text: t });
  };
  return (
    <Modal onClose={onClose} title="Log a symptom">
      <form onSubmit={submit} style={{ display: "grid", gap: 14 }}>
        <textarea
          autoFocus value={text} onChange={(e) => setText(e.target.value)}
          placeholder="What are you noticing? Pain, mood, energy, GI, sleep…"
          rows={5}
          style={{
            width: "100%", padding: "12px 14px", border: "1.5px solid var(--ink)", borderRadius: 10,
            fontFamily: "var(--sans, inherit)", fontSize: 14, background: "var(--paper)", resize: "vertical",
          }}
        />
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <button type="button" className="btn" onClick={onClose}>Cancel</button>
          <button type="submit" className="btn ink" disabled={!text.trim()}>Save symptom →</button>
        </div>
      </form>
    </Modal>
  );
};

const ReorderModal = ({ onClose, supply, onSend }) => {
  const [picks, setPicks] = useState(() => supply.filter(s => s.low).map(s => s.id));
  const toggle = (id) => setPicks(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);
  return (
    <Modal onClose={onClose} title="Reorder list">
      <div style={{ display: "grid", gap: 8 }}>
        {supply.map(s => {
          const p = PEPTIDES.find(x => x.id === s.id);
          if (!p) return null;
          const checked = picks.includes(s.id);
          return (
            <label key={s._key || s.id} style={{
              display: "grid", gridTemplateColumns: "auto 36px 1fr auto", gap: 12, alignItems: "center",
              padding: "10px 14px", border: "1px solid var(--line)", borderRadius: 12, cursor: "pointer",
              background: checked ? "var(--paper)" : "var(--cream)",
            }}>
              <input type="checkbox" checked={checked} onChange={() => toggle(s.id)} />
              <div style={{ width: 24, height: 24, borderRadius: 6, background: p.color }} />
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{p.name}</div>
                <div style={{ fontSize: 12, color: "var(--muted)" }}>{s.level}% · {s.daysLeft} days left</div>
              </div>
              {s.low && <span className="pill coral" style={{ fontSize: 10 }}>low</span>}
            </label>
          );
        })}
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 8 }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn ink" disabled={picks.length === 0} onClick={() => onSend(picks)}>Send to cart ({picks.length}) →</button>
        </div>
      </div>
    </Modal>
  );
};

// ============================================================================
// Data layer: maps between DB row shape (snake_case + when_) and the local
// shape the UI uses (camelCase, `when`, `id` for peptide_id).
// ============================================================================
const fromDb = {
  stack: (r) => ({ _key: r.id, _row: r.id, id: r.peptide_id, dose: r.dose, when: r.when_, done: !!r.done, note: r.note, locked: !!r.locked, position: r.position }),
  log:   (r) => ({ _key: r.id, _row: r.id, id: r.peptide_id, dose: r.dose, when: r.when_, date: r.date }),
  symp:  (r) => ({ _key: r.id, _row: r.id, date: r.date, text: r.text }),
  lab:   (r) => ({ _key: r.id, _row: r.id, nm: r.name, date: r.date, status: r.status, fileName: r.file_name }),
  sup:   (r) => ({ _key: r.id, _row: r.id, id: r.peptide_id, level: r.level, daysLeft: r.days_left, low: !!r.low }),
  tl:    (r) => ({ _key: r.id, _row: r.id, id: r.peptide_id, start: r.start_week, end: r.end_week, label: r.label, active: !!r.active, striped: !!r.striped }),
};

// ---------- Main Dashboard ----------
const Dashboard = ({ onOpenChat, onSelectPeptide, onNav, tipIndex, tips, cycleTip, session, onSignOut }) => {
  const useSupabase = typeof window.SUPABASE_CONFIGURED === "function" && window.SUPABASE_CONFIGURED() && !!session;
  const userId = session && session.user && session.user.id;
  const userEmail = session && session.user && session.user.email;

  // Persisted state — loaded from Supabase (if signed in & configured) or localStorage (fallback).
  const [stack, setStack] = useState(() => useSupabase ? [] : lsGet("pp_dash_stack", []));
  const [logs, setLogs] = useState(() => useSupabase ? [] : lsGet("pp_dash_logs", []));
  const [symptoms, setSymptoms] = useState(() => useSupabase ? [] : lsGet("pp_dash_symptoms", []));
  const [labs, setLabs] = useState(() => useSupabase ? [] : lsGet("pp_dash_labs", []));
  const [supply, setSupply] = useState(() => useSupabase ? [] : lsGet("pp_dash_supply", []));
  const [timeline, setTimeline] = useState(() => useSupabase ? [] : lsGet("pp_dash_timeline", []));
  // Always land on the Today tab when the dashboard mounts. Section
  // changes during the session aren't persisted across reloads.
  const [activeSection, setActiveSection] = useState("today");
  const [loading, setLoading] = useState(useSupabase);

  // UI state
  const [modal, setModal] = useState(null); // 'add' | 'logDose' | 'logSymptom' | 'reorder'
  const [toast, setToast] = useState("");
  const [editTimeline, setEditTimeline] = useState(false);
  const [draftTimeline, setDraftTimeline] = useState(timeline);

  // Persist (localStorage fallback only — Supabase persistence happens in actions)
  useEffect(() => { if (!useSupabase) lsSet("pp_dash_stack", stack); }, [stack, useSupabase]);
  useEffect(() => { if (!useSupabase) lsSet("pp_dash_logs", logs); }, [logs, useSupabase]);
  useEffect(() => { if (!useSupabase) lsSet("pp_dash_symptoms", symptoms); }, [symptoms, useSupabase]);
  useEffect(() => { if (!useSupabase) lsSet("pp_dash_labs", labs); }, [labs, useSupabase]);
  useEffect(() => { if (!useSupabase) lsSet("pp_dash_supply", supply); }, [supply, useSupabase]);
  useEffect(() => { if (!useSupabase) lsSet("pp_dash_timeline", timeline); }, [timeline, useSupabase]);

  // Initial load from Supabase
  useEffect(() => {
    if (!useSupabase) return;
    const sb = window.getSupabase();
    if (!sb) return;
    let cancelled = false;
    setLoading(true);
    Promise.all([
      sb.from("peptide_stack").select("*").eq("user_id", userId).order("position", { ascending: true }).order("created_at", { ascending: true }),
      sb.from("dose_logs").select("*").eq("user_id", userId).order("created_at", { ascending: true }),
      sb.from("symptoms").select("*").eq("user_id", userId).order("created_at", { ascending: true }),
      sb.from("labs").select("*").eq("user_id", userId).order("created_at", { ascending: false }),
      sb.from("supply").select("*").eq("user_id", userId).order("created_at", { ascending: true }),
      sb.from("timeline").select("*").eq("user_id", userId).order("created_at", { ascending: true }),
    ])
      .then(([stk, lg, sy, lb, sp, tl]) => {
        if (cancelled) return;
        if (stk.data) setStack(stk.data.map(fromDb.stack));
        if (lg.data) setLogs(lg.data.map(fromDb.log));
        if (sy.data) setSymptoms(sy.data.map(fromDb.symp));
        if (lb.data) setLabs(lb.data.map(fromDb.lab));
        if (sp.data) setSupply(sp.data.map(fromDb.sup));
        if (tl.data) setTimeline(tl.data.map(fromDb.tl));
      })
      .catch((e) => {
        console.warn("Initial dashboard load failed", e);
        setToast("Could not load your data — try refresh");
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => { cancelled = true; };
  }, [useSupabase, userId]);

  // Toast auto-dismiss
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(""), 2200);
    return () => clearTimeout(t);
  }, [toast]);

  const streak = useMemo(() => computeStreak(logs), [logs]);
  const lowSupplyCount = useMemo(() => supply.filter(s => s.low).length, [supply]);

  // ---------- Mutations (optimistic + Supabase write-through) ----------
  const sb = () => (useSupabase ? window.getSupabase() : null);

  const toggleStack = async (i) => {
    const target = stack[i];
    if (!target) return;
    const nowDone = !target.done;
    const optimisticLog = nowDone ? { _key: `tmp-${Date.now()}`, id: target.id, dose: target.dose, when: target.when, date: todayStr() } : null;

    setStack(prev => prev.map((s, idx) => idx === i ? { ...s, done: nowDone } : s));
    if (optimisticLog) {
      setLogs(L => [...L, optimisticLog]);
      setToast(`Logged ${(PEPTIDES.find(p => p.id === target.id) || {}).name || target.id}`);
    }

    const client = sb();
    if (!client) return;
    try {
      if (target._row) {
        await client.from("peptide_stack").update({ done: nowDone }).eq("id", target._row);
      }
      if (optimisticLog) {
        const { data, error } = await client.from("dose_logs").insert({
          user_id: userId, peptide_id: target.id, dose: target.dose, when_: target.when, date: optimisticLog.date,
        }).select().single();
        if (!error && data) {
          setLogs(L => L.map(l => l._key === optimisticLog._key ? fromDb.log(data) : l));
        }
      }
    } catch (e) {
      console.warn("toggleStack persist failed", e);
      setToast("Couldn't save — try again");
    }
  };

  const removeFromStack = async (i) => {
    const target = stack[i];
    if (!target) return;
    setStack(prev => prev.filter((_, idx) => idx !== i));
    setToast("Removed from stack");
    const client = sb();
    if (!client || !target._row) return;
    try {
      await client.from("peptide_stack").delete().eq("id", target._row);
    } catch (e) {
      console.warn("removeFromStack persist failed", e);
      setToast("Couldn't save — try again");
    }
  };

  const addToStack = async (p) => {
    const tmpKey = `tmp-${Date.now()}`;
    const optimistic = { _key: tmpKey, id: p.id, dose: "—", when: "8:00 AM", done: false };
    setStack(prev => [...prev, optimistic]);
    setModal(null);
    setToast(`${p.name} added to stack`);

    const client = sb();
    if (!client) return;
    try {
      const { data, error } = await client.from("peptide_stack").insert({
        user_id: userId, peptide_id: p.id, dose: "—", when_: "8:00 AM", done: false, position: stack.length,
      }).select().single();
      if (error) throw error;
      if (data) {
        setStack(prev => prev.map(s => s._key === tmpKey ? fromDb.stack(data) : s));
      }
    } catch (e) {
      console.error("addToStack persist failed", e);
      setStack(prev => prev.filter(s => s._key !== tmpKey));
      const detail = (e && (e.message || e.error_description || e.details)) || "";
      setToast("Couldn't save: " + (detail.slice(0, 80) || "unknown error — check console"));
    }
  };

  const saveDoseLog = async (entry) => {
    const tmpKey = `tmp-${Date.now()}`;
    const optimistic = { _key: tmpKey, ...entry };
    setLogs(L => [...L, optimistic]);
    setModal(null);
    setToast("Dose logged");

    const client = sb();
    if (!client) return;
    try {
      const { data, error } = await client.from("dose_logs").insert({
        user_id: userId, peptide_id: entry.id, dose: entry.dose, when_: entry.when, date: entry.date,
      }).select().single();
      if (error) throw error;
      if (data) setLogs(L => L.map(l => l._key === tmpKey ? fromDb.log(data) : l));
    } catch (e) {
      console.warn("saveDoseLog persist failed", e);
      setLogs(L => L.filter(l => l._key !== tmpKey));
      setToast("Couldn't save — try again");
    }
  };

  const saveSymptom = async (entry) => {
    const tmpKey = `tmp-${Date.now()}`;
    const optimistic = { _key: tmpKey, ...entry };
    setSymptoms(S => [...S, optimistic]);
    setModal(null);
    setToast("Symptom saved");

    const client = sb();
    if (!client) return;
    try {
      const { data, error } = await client.from("symptoms").insert({
        user_id: userId, date: entry.date, text: entry.text,
      }).select().single();
      if (error) throw error;
      if (data) setSymptoms(S => S.map(s => s._key === tmpKey ? fromDb.symp(data) : s));
    } catch (e) {
      console.warn("saveSymptom persist failed", e);
      setSymptoms(S => S.filter(s => s._key !== tmpKey));
      setToast("Couldn't save — try again");
    }
  };

  const reorderSend = () => {
    setModal(null);
    setToast("Queued for reorder ✓");
  };

  const uploadLab = async (fileName) => {
    const tmpKey = `tmp-${Date.now()}`;
    const dateStr = new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }).toUpperCase();
    const newLab = {
      _key: tmpKey,
      nm: fileName.replace(/\.[^.]+$/, ""),
      date: dateStr,
      status: "Processing",
      fileName,
    };
    setLabs(L => [newLab, ...L]);
    setToast("Lab uploaded — processing");

    const client = sb();
    let savedRowId = null;
    if (client) {
      try {
        const { data, error } = await client.from("labs").insert({
          user_id: userId, name: newLab.nm, date: dateStr, status: "Processing", file_name: fileName,
        }).select().single();
        if (error) throw error;
        if (data) {
          savedRowId = data.id;
          setLabs(L => L.map(l => l._key === tmpKey ? fromDb.lab(data) : l));
        }
      } catch (e) {
        console.warn("uploadLab persist failed", e);
      }
    }

    // Faux processing transition
    setTimeout(async () => {
      const newStatus = Math.random() < 0.7 ? "Normal" : "Flagged";
      setLabs(L => L.map(l => {
        if (l.fileName === fileName && l.status === "Processing") return { ...l, status: newStatus };
        return l;
      }));
      if (client && savedRowId) {
        try {
          await client.from("labs").update({ status: newStatus }).eq("id", savedRowId);
        } catch (e) {
          console.warn("uploadLab status update failed", e);
        }
      }
    }, 1500);
  };

  // Timeline edit handlers
  const beginEditTimeline = () => { setDraftTimeline(timeline); setEditTimeline(true); };
  const changeDraftRow = (idx, patch) => setDraftTimeline(d => d.map((r, i) => i === idx ? { ...r, ...patch } : r));
  const saveTimeline = async () => {
    setTimeline(draftTimeline);
    setEditTimeline(false);
    setToast("Protocol updated");

    const client = sb();
    if (!client) return;
    // Diff against the previous timeline and update changed rows.
    try {
      await Promise.all(draftTimeline.map((row) => {
        if (!row._row) return null;
        const prev = timeline.find(t => t._row === row._row);
        if (!prev) return null;
        const changed =
          prev.start !== row.start || prev.end !== row.end ||
          prev.active !== row.active || prev.striped !== row.striped ||
          prev.label !== row.label;
        if (!changed) return null;
        return client.from("timeline").update({
          start_week: row.start,
          end_week: row.end,
          active: row.active,
          striped: row.striped,
          label: row.label,
        }).eq("id", row._row);
      }).filter(Boolean));
    } catch (e) {
      console.warn("saveTimeline persist failed", e);
      setToast("Couldn't save timeline — try again");
    }
  };

  // ---------- Render sections ----------
  const renderToday = () => (
    <div className="dash-grid">
      <StackTile stack={stack} onToggle={toggleStack} onSelect={onSelectPeptide} onAdd={() => setModal("add")} onRemove={removeFromStack} />
      <SplatTile tipIndex={tipIndex} tips={tips} onOpenChat={onOpenChat} onCycleTip={cycleTip} />
      <Timeline
        rows={editTimeline ? draftTimeline : timeline}
        editMode={editTimeline}
        onToggleEdit={beginEditTimeline}
        onChangeRow={changeDraftRow}
        onSave={saveTimeline}
      />
      <Biomarkers />
      <LabsTile labs={labs} onUpload={uploadLab} />
      <SupplyTile supply={supply} onReorder={() => setModal("reorder")} />
      <RecentActivity logs={logs} symptoms={symptoms} />
      <div style={{ gridColumn: "span 12" }}><ArticlesMini onNav={onNav} /></div>
    </div>
  );

  const renderStack = () => (
    <div className="dash-grid">
      <div style={{ gridColumn: "span 12" }}>
        <StackTile stack={stack} onToggle={toggleStack} onSelect={onSelectPeptide} onAdd={() => setModal("add")} onRemove={removeFromStack} />
      </div>
      <RecentActivity logs={logs} symptoms={symptoms} />
    </div>
  );

  const renderTimeline = () => (
    <div className="dash-grid">
      <div style={{ gridColumn: "span 12" }}>
        <Timeline
          rows={editTimeline ? draftTimeline : timeline}
          editMode={editTimeline}
          onToggleEdit={beginEditTimeline}
          onChangeRow={changeDraftRow}
          onSave={saveTimeline}
        />
      </div>
    </div>
  );

  const renderLabs = () => (
    <div className="dash-grid">
      <div style={{ gridColumn: "span 12" }}>
        <LabsTile labs={labs} onUpload={uploadLab} />
      </div>
      <div style={{ gridColumn: "span 12" }}>
        <Biomarkers />
      </div>
    </div>
  );

  const renderSupply = () => (
    <div className="dash-grid">
      <div style={{ gridColumn: "span 12" }}>
        <SupplyTile supply={supply} onReorder={() => setModal("reorder")} />
      </div>
    </div>
  );

  const renderChat = () => (
    <div style={{ marginTop: 8 }}>
      <ChatWindow inline={true} />
    </div>
  );

  const sectionRenderers = {
    today: renderToday, stack: renderStack, timeline: renderTimeline, labs: renderLabs, supply: renderSupply, chat: renderChat,
  };
  const renderActive = sectionRenderers[activeSection] || renderToday;

  const headerForSection = () => {
    switch (activeSection) {
      case "stack": return { kicker: "MY STACK", title: <>Manage your daily stack. <em style={{ color: "var(--splat-deep)" }}>Add, log, retire.</em></> };
      case "timeline": return { kicker: "PROTOCOL", title: <>Your 12-week cycle. <em style={{ color: "var(--splat-deep)" }}>Edit any time.</em></> };
      case "labs": return { kicker: "LABS & BIOMARKERS", title: <>Drop a PDF. <em style={{ color: "var(--splat-deep)" }}>Splat reads it.</em></> };
      case "supply": return { kicker: "CABINET", title: <>What's left in the fridge. <em style={{ color: "var(--splat-deep)" }}>Reorder before you run out.</em></> };
      case "chat": return { kicker: "SPLAT · YOUR PEPTIDE PAL", title: <>Ask me anything. <em style={{ color: "var(--splat-deep)" }}>I can see your dashboard.</em></> };
      default: {
        const today = new Date();
        const days = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
        const months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
        const dateLine = `${days[today.getDay()]} · ${months[today.getMonth()]} ${today.getDate()}, ${today.getFullYear()}`;
        const userName = (typeof localStorage !== "undefined" && localStorage.getItem("pp_name")) || "";
        const firstName = userName ? userName.split(" ")[0] : "";
        const greeting = firstName ? `${dateLine}  ·  Welcome back, ${firstName}.` : `${dateLine}  ·  Welcome to your dashboard.`;
        const empty = stack.length === 0;
        return {
          kicker: greeting,
          title: empty
            ? <>Let's set up your stack. <em style={{ color: "var(--splat-deep)" }}>Add your first peptide to get started.</em></>
            : <>Tracking <em style={{ color: "var(--splat-deep)" }}>{stack.length} peptide{stack.length === 1 ? "" : "s"}</em> right now.</>,
        };
      }
    }
  };
  const head = headerForSection();

  return (
    <div className="dash">
      <Sidebar
        active={activeSection}
        onNav={setActiveSection}
        onAppNav={onNav}
        stackCount={stack.length}
        lowSupplyCount={lowSupplyCount}
        streak={streak}
        onSignOut={onSignOut}
        userEmail={userEmail}
      />
      <main className="dash-main">
        <div className="dash-header">
          <div>
            <div className="greeting">
              <span className="today">{head.kicker}</span>
            </div>
            <h1>{head.title}</h1>
            <div style={{ display: "flex", gap: 8, marginTop: 14, flexWrap: "wrap" }}>
              <span className="pill green">● Streak {streak} day{streak === 1 ? "" : "s"}</span>
              <span className="pill sky">● {stack.length} peptide{stack.length === 1 ? "" : "s"} active</span>
              <span className="pill sun">📓 {logs.length} dose log{logs.length === 1 ? "" : "s"}</span>
              {lowSupplyCount > 0 && <span className="pill coral">⚠ {lowSupplyCount} low supply</span>}
            </div>
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn" onClick={() => setModal("logSymptom")}>Log symptom</button>
            <button className="btn ink" onClick={() => setModal("logDose")}>+ Log a dose</button>
          </div>
        </div>

        {loading ? (
          <div style={{
            display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 18,
            padding: "80px 20px", color: "var(--muted)", fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.1em",
          }}>
            <span className="loader3 md" aria-hidden="true"><b/><b/><b/></span>
            <span style={{ textTransform: "uppercase" }}>Loading your dashboard…</span>
          </div>
        ) : renderActive()}
      </main>

      {modal === "add" && (
        <AddPeptideModal
          onClose={() => setModal(null)}
          onPick={addToStack}
          currentIds={stack.map(s => s.id)}
        />
      )}
      {modal === "logDose" && (
        <LogDoseModal onClose={() => setModal(null)} stack={stack} onSave={saveDoseLog} />
      )}
      {modal === "logSymptom" && (
        <LogSymptomModal onClose={() => setModal(null)} onSave={saveSymptom} />
      )}
      {modal === "reorder" && (
        <ReorderModal onClose={() => setModal(null)} supply={supply} onSend={reorderSend} />
      )}

      <Toast msg={toast} />
    </div>
  );
};

Object.assign(window, { Dashboard });
