// =============================================================================
// DASHBOARD TAB
// Daily orchestration — Launch My Day, Wind Down, 72-hr prep, week strip,
// inbox triage, tasks, finance/trading/news/store snapshots.
//
// Data: emails, tasks, habits, meetings72, calendarEvents, finance, content, store.
// All sourced from the active adapter — no business data baked in.
// =============================================================================

(function () {
  const { useState } = React;
  const { C, EVT } = window.JD_THEME;
  const { card, ct, inp, bg, br, bgg, Empty, Loading, ErrorBox } = window.JD_STYLES;

  function Dashboard() {
    // Adapter reads
    const emails        = window.useJarvisData("emails");
    const tasks         = window.useJarvisData("tasks");
    const meetings72Q   = window.useJarvisData("meetings72");
    const calEventsQ    = window.useJarvisData("calendarEvents");
    const financeQ      = window.useJarvisData("finance");
    const contentQ      = window.useJarvisData("content");

    const { prepChecks, setPrepChecks, storeMsg, setStoreMsg, storeMsgs, sendStoreBoss } = window.useShared();

    // Local interaction state (per-session, never persisted)
    const [replyOpen, setReplyOpen] = useState(null);
    const [replyMode, setReplyMode] = useState("options");
    const [replyText, setReplyText] = useState("");
    const [launchStep, setLaunchStep] = useState(0);
    const [launchAnswers, setLaunchAnswers] = useState({ mental: "", focus: 5, stress: "" });
    const [launchPlan, setLaunchPlan] = useState("");
    const [windOpen, setWindOpen] = useState(false);
    const [windAnswers, setWindAnswers] = useState({ day: "", done: "", prod: "", mood: 5, principles: "" });
    const [windSummary, setWindSummary] = useState("");

    const today = new Date();
    const emailList = emails.data || [];
    const taskList = tasks.data || [];
    const m72 = meetings72Q.data || [];
    const calEvents = calEventsQ.data || {};
    const fin = financeQ.data || {};
    const platformActivity = (contentQ.data && contentQ.data.platformActivity) || [];

    const openTasks = taskList.filter(t => !t.done);
    const doneTasks = taskList.filter(t => t.done);
    const top3 = openTasks.slice(0, 3);
    const rest = openTasks.slice(3);

    const generateLaunchPlan = async () => {
      try {
        const plan = await window.JD.mutate("generateLaunchPlan", launchAnswers);
        setLaunchPlan(plan || "");
      } catch (e) {
        setLaunchPlan("Adapter error: " + e.message);
      }
      setLaunchStep(4);
    };
    const saveWindDown = async () => {
      try {
        const summary = await window.JD.mutate("saveWindDown", windAnswers);
        setWindSummary(summary || "");
      } catch (e) {
        setWindSummary("Adapter error: " + e.message);
      }
    };
    const toggleTask = async (id) => {
      await window.JD.mutate("toggleTask", id);
      tasks.reload();
    };
    const dismissEmail = async (id) => {
      await window.JD.mutate("dismissEmail", id);
      emails.reload();
    };
    const sendReply = async (emailId) => {
      await window.JD.mutate("sendReply", { emailId, text: replyText });
      setReplyOpen(null);
      setReplyText("");
      emails.reload();
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {/* Launch My Day + Wind Down */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div style={card({ border: "0.5px solid rgba(159,117,9,0.3)" })}>
            <div style={ct}>Launch My Day</div>
            {launchPlan ? (
              <div style={{ fontSize: 15, color: "rgba(222,214,185,0.82)", lineHeight: 1.7, whiteSpace: "pre-line" }}>{launchPlan}</div>
            ) : launchStep === 0 ? (
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div style={{ fontSize: 16, color: "rgba(222,214,185,0.7)" }}>Start your day with intention.</div>
                <button onClick={() => setLaunchStep(1)} style={bg}>Launch Day</button>
              </div>
            ) : launchStep === 1 ? (
              <div>
                <div style={{ fontSize: 16, color: C.cream, marginBottom: 8 }}>How is your mental today?</div>
                <textarea value={launchAnswers.mental} onChange={e => setLaunchAnswers(a => ({ ...a, mental: e.target.value }))} style={{ ...inp, minHeight: 50, resize: "vertical" }} placeholder="What is on your mind..." />
                <button onClick={() => setLaunchStep(2)} style={{ ...bg, marginTop: 8 }}>Next</button>
              </div>
            ) : launchStep === 2 ? (
              <div>
                <div style={{ fontSize: 16, color: C.cream, marginBottom: 8 }}>Focus level: {launchAnswers.focus}/10</div>
                <input type="range" min={0} max={10} value={launchAnswers.focus} onChange={e => setLaunchAnswers(a => ({ ...a, focus: +e.target.value }))} style={{ width: "100%", marginBottom: 10 }} />
                <button onClick={() => setLaunchStep(3)} style={bg}>Next</button>
              </div>
            ) : (
              <div>
                <div style={{ fontSize: 16, color: C.cream, marginBottom: 8 }}>Any stress or priorities to flag?</div>
                <textarea value={launchAnswers.stress} onChange={e => setLaunchAnswers(a => ({ ...a, stress: e.target.value }))} style={{ ...inp, minHeight: 50, resize: "vertical" }} placeholder="Optional..." />
                <button onClick={generateLaunchPlan} style={{ ...bg, marginTop: 8 }}>Generate Day Plan</button>
              </div>
            )}
          </div>
          <div style={card({ border: "0.5px solid rgba(139,127,212,0.3)" })}>
            <div style={ct}>Wind Down</div>
            {windSummary ? (
              <div style={{ fontSize: 15, color: "rgba(222,214,185,0.82)", lineHeight: 1.7, whiteSpace: "pre-line" }}>{windSummary}</div>
            ) : !windOpen ? (
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div style={{ fontSize: 16, color: "rgba(222,214,185,0.7)" }}>End your day with reflection. 30 min.</div>
                <button onClick={() => setWindOpen(true)} style={{ ...bg, borderColor: "rgba(139,127,212,0.4)", color: C.purple }}>Begin</button>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <textarea value={windAnswers.day} onChange={e => setWindAnswers(a => ({ ...a, day: e.target.value }))} style={{ ...inp, minHeight: 36, resize: "vertical" }} placeholder="How did today go?" />
                <textarea value={windAnswers.done} onChange={e => setWindAnswers(a => ({ ...a, done: e.target.value }))} style={{ ...inp, minHeight: 36, resize: "vertical" }} placeholder="Tasks accomplished?" />
                <textarea value={windAnswers.prod} onChange={e => setWindAnswers(a => ({ ...a, prod: e.target.value }))} style={{ ...inp, minHeight: 36, resize: "vertical" }} placeholder="Productivity? Distractions?" />
                <div style={{ fontSize: 15, color: C.cream }}>Mood: {windAnswers.mood}/10</div>
                <input type="range" min={0} max={10} value={windAnswers.mood} onChange={e => setWindAnswers(a => ({ ...a, mood: +e.target.value }))} style={{ width: "100%" }} />
                <textarea value={windAnswers.principles} onChange={e => setWindAnswers(a => ({ ...a, principles: e.target.value }))} style={{ ...inp, minHeight: 36, resize: "vertical" }} placeholder="Principles alignment today?" />
                <button onClick={saveWindDown} style={bg}>Save Wind Down</button>
              </div>
            )}
          </div>
        </div>

        {/* 72-Hour Prep Alerts */}
        <div style={card({ border: "0.5px solid rgba(212,160,23,0.25)" })}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <div style={{ width: 6, height: 6, borderRadius: "50%", background: C.yellow }} />
            <div style={{ fontSize: 13, letterSpacing: "0.2em", textTransform: "uppercase", color: C.yellow }}>CRM Prep Alerts — Next 72 Hours</div>
          </div>
          {meetings72Q.loading ? <Loading /> :
           meetings72Q.error ? <ErrorBox message={meetings72Q.error.message} /> :
           m72.length === 0 ? <Empty label="No meetings in the next 72 hours" sub="Connect calendar via adapter to populate" /> : (
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {m72.map((m, i) => (
                <div key={i} style={{ flex: 1, minWidth: 220, background: C.card2, borderRadius: 8, padding: "16px 18px", minHeight: 110, border: "0.5px solid " + C.border }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
                    <div style={{ width: 6, height: 6, borderRadius: "50%", background: EVT[m.type]?.c || C.muted }} />
                    <div style={{ fontSize: 15, color: C.cream }}>{m.title}</div>
                  </div>
                  <div style={{ fontSize: 14, color: C.muted, marginBottom: 8 }}>{m.date} · {m.time}</div>
                  {prepChecks[i] === true
                    ? <div style={{ fontSize: 14, color: C.green, opacity: 0.6 }}>Prepped ✓</div>
                    : <div style={{ display: "flex", gap: 6 }}>
                        <button onClick={() => setPrepChecks(p => ({ ...p, [i]: true }))} style={bgg}>Prepped</button>
                        <button onClick={() => setPrepChecks(p => ({ ...p, [i]: "no" }))} style={br}>Need Prep</button>
                      </div>}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* This Week Strip */}
        <div style={card()}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
            <div style={ct}>This Week</div>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {Object.entries(EVT).map(([k, v]) => (
                <div key={k} style={{ display: "flex", alignItems: "center", gap: 4 }}>
                  <div style={{ width: 7, height: 7, borderRadius: "50%", background: v.c }} />
                  <span style={{ fontSize: 13, color: "rgba(222,214,185,0.82)" }}>{v.l}</span>
                </div>
              ))}
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 6 }}>
            {(() => {
              const dow = today.getDay();
              const mondayOffset = dow === 0 ? -6 : 1 - dow;
              const monday = new Date(today); monday.setDate(today.getDate() + mondayOffset);
              const dn = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
              return Array.from({ length: 7 }, (_, i) => {
                const d = new Date(monday); d.setDate(monday.getDate() + i);
                const day = d.getDate();
                const evs = calEvents[day] || [];
                const isToday = d.toDateString() === today.toDateString();
                return (
                  <div key={i} style={{ background: isToday ? "rgba(159,117,9,0.12)" : C.card2, borderRadius: 8, padding: "16px 12px", minHeight: 340, border: "0.5px solid " + (isToday ? "rgba(159,117,9,0.4)" : C.border) }}>
                    <div style={{ fontSize: 13, color: C.muted, letterSpacing: "0.1em", marginBottom: 2 }}>{dn[i]}</div>
                    <div style={{ fontSize: 17, color: isToday ? C.gold : C.cream, marginBottom: 6 }}>{day}</div>
                    {evs.map((e, j) => (
                      <div key={j} style={{ display: "flex", gap: 4, marginBottom: 4 }}>
                        <div style={{ width: 5, height: 5, borderRadius: "50%", background: EVT[e.type]?.c, marginTop: 3, flexShrink: 0 }} />
                        <div>
                          <div style={{ fontSize: 13, color: "rgba(222,214,185,0.72)", lineHeight: 1.3 }}>{e.t}</div>
                          <div style={{ fontSize: 12, color: C.muted }}>{e.time}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                );
              });
            })()}
          </div>
        </div>

        {/* Inbox + Tasks */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div style={card()}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
              <div style={ct}>Inbox</div>
              <div style={{ display: "flex", gap: 5 }}>
                {["red", "yellow", "green"].map(u => (
                  <span key={u} style={{ fontSize: 13, padding: "2px 7px", borderRadius: 10, background: u === "red" ? "rgba(224,82,82,0.15)" : u === "yellow" ? "rgba(212,160,23,0.15)" : "rgba(62,207,142,0.1)", color: u === "red" ? C.red : u === "yellow" ? C.yellow : C.green, border: "0.5px solid " + (u === "red" ? "rgba(224,82,82,0.3)" : u === "yellow" ? "rgba(212,160,23,0.3)" : "rgba(62,207,142,0.25)"), letterSpacing: "0.08em" }}>
                    {u === "red" ? "Now" : u === "yellow" ? "Today" : "Later"}
                  </span>
                ))}
              </div>
            </div>
            {emails.loading ? <Loading /> :
             emails.error ? <ErrorBox message={emails.error.message} /> :
             emailList.length === 0 ? <Empty label="Inbox clear" sub="Connect Gmail/Outlook via adapter to triage" /> : (
              <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                {emailList.map(e => (
                  <div key={e.id}>
                    <div onClick={() => setReplyOpen(replyOpen === e.id ? null : e.id)} style={{ display: "flex", gap: 8, padding: "9px 10px", borderRadius: 8, cursor: "pointer", alignItems: "flex-start", background: e.urgency === "red" ? "rgba(224,82,82,0.1)" : e.urgency === "yellow" ? "rgba(212,160,23,0.1)" : "rgba(62,207,142,0.07)", border: "0.5px solid " + (e.urgency === "red" ? "rgba(224,82,82,0.2)" : e.urgency === "yellow" ? "rgba(212,160,23,0.2)" : "rgba(62,207,142,0.15)") }}>
                      <div style={{ width: 26, height: 26, borderRadius: "50%", background: e.bg, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 500, color: C.bg, flexShrink: 0 }}>{e.init}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 15, fontWeight: 500, color: C.cream }}>{e.from}</div>
                        <div style={{ fontSize: 14, color: "rgba(222,214,185,0.7)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.subject}</div>
                      </div>
                      <div style={{ fontSize: 13, color: C.muted, flexShrink: 0 }}>{e.time}</div>
                      <button onClick={ev => { ev.stopPropagation(); dismissEmail(e.id); }} style={{ background: "transparent", border: "0.5px solid " + C.border, borderRadius: 4, color: C.muted, cursor: "pointer", fontSize: 14, padding: "2px 6px", fontFamily: "Georgia,serif", flexShrink: 0 }}>×</button>
                    </div>
                    {replyOpen === e.id && (
                      <div style={{ background: C.card2, borderRadius: 8, padding: 10, marginTop: 3, border: "0.5px solid rgba(159,117,9,0.2)" }}>
                        <div style={{ fontSize: 13, color: C.gold, letterSpacing: "0.14em", marginBottom: 8, textTransform: "uppercase" }}>Reply to {e.from}</div>
                        <div style={{ display: "flex", gap: 5, marginBottom: 8 }}>
                          {["options", "free", "edit"].map(m => (
                            <button key={m} onClick={() => setReplyMode(m)} style={{ fontSize: 13, padding: "4px 10px", borderRadius: 5, border: "0.5px solid " + (replyMode === m ? "rgba(159,117,9,0.5)" : C.border), background: replyMode === m ? "rgba(159,117,9,0.15)" : "transparent", color: replyMode === m ? C.gold : C.muted, cursor: "pointer", fontFamily: "Georgia,serif" }}>
                              {m === "options" ? "AI Options" : m === "free" ? "Free Type" : "Pick & Edit"}
                            </button>
                          ))}
                        </div>
                        {replyMode === "options"
                          ? <Empty label="AI draft options will appear here" sub="Wire adapter.draftReply() to populate" />
                          : <textarea value={replyText} onChange={ev => setReplyText(ev.target.value)} placeholder={replyMode === "free" ? "Type raw — Jarvis polishes it..." : "Edit selected draft..."} style={{ ...inp, resize: "vertical", minHeight: 50 }} />}
                        <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", marginTop: 6 }}>
                          <button onClick={() => setReplyOpen(null)} style={{ fontSize: 14, padding: "5px 12px", background: "transparent", border: "0.5px solid " + C.border, borderRadius: 6, color: C.muted, cursor: "pointer", fontFamily: "Georgia,serif" }}>Cancel</button>
                          <button onClick={() => sendReply(e.id)} style={bg}>Send</button>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          <div style={card()}>
            <div style={ct}>Tasks</div>
            <div style={{ fontSize: 13, color: C.gold, letterSpacing: "0.14em", marginBottom: 6, opacity: 0.7, textTransform: "uppercase" }}>AI Top 3</div>
            {tasks.loading ? <Loading /> :
             tasks.error ? <ErrorBox message={tasks.error.message} /> :
             top3.length === 0 ? <Empty label="No tasks yet" sub="Adapter returned an empty task list" /> : (
              <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 10 }}>
                {top3.map((t, i) => (
                  <div key={t.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", background: "rgba(159,117,9,0.07)", borderRadius: 8, border: "0.5px solid rgba(159,117,9,0.15)" }}>
                    <div style={{ fontSize: 16, fontWeight: 500, color: C.gold, minWidth: 16 }}>{i + 1}</div>
                    <div onClick={() => toggleTask(t.id)} style={{ width: 13, height: 13, borderRadius: 3, border: "1.5px solid rgba(159,117,9,0.4)", background: "transparent", cursor: "pointer", flexShrink: 0 }} />
                    <div style={{ flex: 1, fontSize: 15, color: C.cream }}>{t.text}</div>
                    <span style={{ fontSize: 13, padding: "2px 7px", borderRadius: 10, background: t.tc + "18", color: t.tc, border: "0.5px solid " + t.tc + "30", flexShrink: 0 }}>{t.type}</span>
                  </div>
                ))}
              </div>
            )}
            {(rest.length > 0 || doneTasks.length > 0) && (
              <div style={{ borderTop: "0.5px solid " + C.border, paddingTop: 8 }}>
                <div style={{ fontSize: 13, color: C.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 6 }}>All Open</div>
                {rest.map(t => (
                  <div key={t.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 0", borderBottom: "0.5px solid " + C.border }}>
                    <div onClick={() => toggleTask(t.id)} style={{ width: 13, height: 13, borderRadius: 3, border: "1.5px solid " + C.border, background: "transparent", cursor: "pointer", flexShrink: 0 }} />
                    <div style={{ flex: 1, fontSize: 15, color: "rgba(222,214,185,0.82)" }}>{t.text}</div>
                    <span style={{ fontSize: 13, padding: "2px 7px", borderRadius: 10, background: t.tc + "18", color: t.tc, border: "0.5px solid " + t.tc + "30", flexShrink: 0 }}>{t.type}</span>
                  </div>
                ))}
                {doneTasks.map(t => (
                  <div key={t.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 0", borderBottom: "0.5px solid " + C.border, opacity: 0.4 }}>
                    <div onClick={() => toggleTask(t.id)} style={{ width: 13, height: 13, borderRadius: 3, border: "1.5px solid " + C.gold, background: C.gold, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, cursor: "pointer" }}>
                      <span style={{ color: C.bg, fontSize: 12, fontWeight: "bold" }}>✓</span>
                    </div>
                    <div style={{ flex: 1, fontSize: 15, color: "rgba(222,214,185,0.78)", textDecoration: "line-through" }}>{t.text}</div>
                    <span style={{ fontSize: 13, padding: "2px 7px", borderRadius: 10, background: t.tc + "18", color: t.tc, border: "0.5px solid " + t.tc + "30", flexShrink: 0 }}>{t.type}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Finance + Trading snapshot */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div style={card()}>
            <div style={ct}>Business Finance · Novo</div>
            <div style={{ fontSize: 36, color: C.cream, fontVariantNumeric: "tabular-nums", margin: "6px 0 2px" }}>{fin.novoBalance || "—"}</div>
            <div style={{ fontSize: 14, color: C.muted, marginBottom: 12 }}>{fin.novoBalance ? "via adapter" : "Connect bank source via adapter"}</div>
            <div style={{ fontSize: 13, color: C.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 6 }}>30-Day Cash Flow</div>
            <div style={{ height: 60, marginBottom: 8 }}>
              {(fin.series || []).length > 0 ? (
                <svg width="100%" height="60" viewBox="0 0 300 60" preserveAspectRatio="none">
                  <polyline points={fin.series.map((d, i) => (i * 10) + "," + (60 - (d.in / 5000) * 55)).join(" ")} fill="none" stroke={C.green} strokeWidth="1.5" />
                  <polyline points={fin.series.map((d, i) => (i * 10) + "," + (60 - (d.out / 5000) * 55)).join(" ")} fill="none" stroke={C.red} strokeWidth="1.5" />
                </svg>
              ) : <Empty label="No transactions" />}
            </div>
            {[["Revenue MTD", fin.revenueMTD], ["Expenses MTD", fin.expensesMTD], ["Net MTD", fin.netMTD]].map(([l, v]) => (
              <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "0.5px solid " + C.border, fontSize: 15 }}>
                <span style={{ color: "rgba(222,214,185,0.7)" }}>{l}</span><span style={{ color: C.muted }}>{v || "—"}</span>
              </div>
            ))}
          </div>
          <div style={card()}>
            <div style={ct}>Trading · Alpaca</div>
            <div style={{ fontSize: 36, color: C.cream, fontVariantNumeric: "tabular-nums", margin: "6px 0 2px" }}>{fin.alpacaBalance || "—"}</div>
            <div style={{ fontSize: 14, color: C.muted, marginBottom: 12 }}>{fin.alpacaBalance ? "via adapter" : "Connect trading source via adapter"}</div>
            {(fin.pendingTrades || []).map((tr, i) => (
              <div key={i} style={{ padding: "8px 10px", background: "rgba(212,160,23,0.1)", borderRadius: 8, border: "0.5px solid rgba(212,160,23,0.25)", marginBottom: 10 }}>
                <div style={{ fontSize: 14, color: C.yellow, marginBottom: 6 }}>{tr.symbol} {tr.side} · {tr.qty} shares · Approval Needed</div>
                <div style={{ fontSize: 12, color: C.muted, marginBottom: 8 }}>{tr.rationale}</div>
                <div style={{ display: "flex", gap: 6 }}>
                  <button onClick={() => window.JD.mutate("approveTrade", tr.symbol).then(() => financeQ.reload())} style={bgg}>Approve</button>
                  <button onClick={() => window.JD.mutate("rejectTrade", tr.symbol).then(() => financeQ.reload())} style={br}>Reject</button>
                </div>
              </div>
            ))}
            {(fin.positions || []).length === 0 ? <Empty label="No positions" /> : (fin.positions || []).map(([t, q, v, d, c]) => (
              <div key={t} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "0.5px solid " + C.border, fontSize: 15 }}>
                <span style={{ color: C.cream, fontWeight: 500 }}>{t}</span><span style={{ color: c }}>{v}</span>
              </div>
            ))}
          </div>
        </div>

        {/* News + Store snapshot */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div style={card()}>
            <div style={ct}>NewsGuyRy · Social Activity</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 6, marginBottom: 10 }}>
              {(platformActivity.length ? platformActivity : [["TikTok", false], ["Instagram", false], ["Facebook", false], ["LinkedIn", false], ["YouTube", false], ["Newsletter", false]]).map(([p, done]) => (
                <div key={p} style={{ padding: "7px 8px", background: C.card2, borderRadius: 8, border: "0.5px solid " + (done ? "rgba(62,207,142,0.25)" : C.border), textAlign: "center" }}>
                  <div style={{ fontSize: 13, color: C.muted, marginBottom: 3 }}>{p}</div>
                  <div style={{ fontSize: 17 }}>{done ? "✓" : "○"}</div>
                </div>
              ))}
            </div>
            <div style={{ fontSize: 14, color: "rgba(222,214,185,0.72)" }}>—</div>
          </div>
          <div style={card()}>
            <div style={ct}>Store · Etsy/Printify</div>
            <StoreSnapshot />
            <div style={{ fontSize: 13, color: C.muted, letterSpacing: "0.1em", marginBottom: 6, textTransform: "uppercase" }}>Talk to Store Boss</div>
            <div style={{ maxHeight: 60, overflow: "auto", marginBottom: 6 }}>
              {storeMsgs.length === 0 && <div style={{ fontSize: 13, color: C.muted, fontStyle: "italic" }}>No messages yet</div>}
              {storeMsgs.map((m, i) => (
                <div key={i} style={{ fontSize: 14, color: m.role === "user" ? C.cream : "rgba(222,214,185,0.72)", marginBottom: 2 }}>
                  <span style={{ color: m.role === "user" ? C.gold : "rgba(139,127,212,0.8)", marginRight: 4 }}>{m.role === "user" ? "You:" : "Boss:"}</span>{m.msg}
                </div>
              ))}
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              <input value={storeMsg} onChange={e => setStoreMsg(e.target.value)} onKeyDown={e => e.key === "Enter" && sendStoreBoss()} placeholder="Instruct store boss..." style={{ ...inp, flex: 1 }} />
              <button onClick={sendStoreBoss} style={bg}>Send</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Tiny store-snapshot subcomponent so the parent stays readable
  function StoreSnapshot() {
    const { data } = window.useJarvisData("store");
    const s = data || {};
    return (
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 10 }}>
        {[["Revenue", s.revenueMTD], ["Expenses", s.expenses], ["Orders", s.orders], ["Listings", s.listings]].map(([l, v]) => (
          <div key={l} style={{ background: C.card2, borderRadius: 8, padding: "8px 10px", border: "0.5px solid " + C.border }}>
            <div style={{ fontSize: 13, color: C.muted, textTransform: "uppercase", letterSpacing: "0.1em" }}>{l}</div>
            <div style={{ fontSize: 26, color: v ? C.cream : C.muted, marginTop: 2 }}>{v || "—"}</div>
          </div>
        ))}
      </div>
    );
  }

  window.JD_TABS = window.JD_TABS || {};
  window.JD_TABS.Dashboard = Dashboard;
})();
