/* ============================================================
   Notifications — the email tool. Sends Preston (1) a daily
   update digest and (2) an instant alert when a target replies
   interested / wants to do work. Shows rendered email previews.
   ============================================================ */
function notifData() {
  const W = window.WTC, k = W.kpis;
  // interested = warm inbound replies that want to engage
  const interested = W.threads.filter((t) => ["interested", "needs_attention"].includes(t.triage)).map((t) => {
    const m = [...t.messages].reverse().find((x) => x.from === "them");
    return { id: t.id, brand: t.brand, mono: t.mono, lane: t.lane, contact: t.contact, quote: m ? m.body : "", time: t.lastTouch === "today" ? "Today" : t.lastTouch, targetId: t.targetId };
  });
  const q = W.todayQueue;
  return {
    interested,
    digest: {
      date: "Tuesday, June 2",
      dueToday: k.dueToday, replies: interested.length,
      overdue: q.filter((t) => t.priority === "overdue").length,
      cold: q.filter((t) => t.priority === "cold").length,
      winPct: k.winPct, active: k.active, sentWeek: k.spark.reduce((a, b) => a + b, 0),
      top: q.slice(0, 4),
      wins: k.wins.slice(0, 2),
    },
  };
}

// ---- rendered email previews ----
function EmailFrame({ subject, children }) {
  return (
    <div className="email-frame">
      <div className="email-bar">
        <div className="email-from"><div className="email-logo"><Icon name="mountain" size={15} /></div>
          <div><div style={{ fontSize: 12.5, fontWeight: 650 }}>We The Creators · Targets</div><div style={{ fontSize: 11, color: "var(--text-3)" }}>targets@wethecreators.co → preston@wethecreators.co</div></div></div>
      </div>
      <div className="email-subject">{subject}</div>
      <div className="email-body">{children}</div>
      <div className="email-foot">You're getting this from your Targets workspace · <span style={{ color: "var(--accent)" }}>Manage notifications</span></div>
    </div>
  );
}

function DigestEmail({ d, onOpen }) {
  return (
    <EmailFrame subject={`Your daily update — ${d.replies} replies, ${d.dueToday} to send`}>
      <p style={{ margin: "0 0 14px", fontSize: 14 }}>Morning, Preston — here's where things stand for <b>{d.date}</b>.</p>
      <div className="dg-stats">
        {[["Replies waiting", d.replies, "var(--green)"], ["Ready to send", d.dueToday, "var(--accent)"], ["Overdue", d.overdue, "var(--red)"], ["Going cold", d.cold, "var(--amber)"]].map(([l, v, c]) => (
          <div key={l} className="dg-stat"><span className="num" style={{ fontSize: 22, fontWeight: 700, color: c }}>{v}</span><span style={{ fontSize: 11, color: "var(--text-3)" }}>{l}</span></div>
        ))}
      </div>
      <div className="dg-section-label">Who to reach first</div>
      {d.top.map((t) => (
        <div key={t.id} className="dg-row">
          <Avatar mono={t.mono} size={26} square />
          <div style={{ minWidth: 0, flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600 }}>{t.brand}</div><div style={{ fontSize: 11.5, color: "var(--text-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.whyNow}</div></div>
        </div>
      ))}
      <div className="dg-section-label" style={{ marginTop: 14 }}>This week</div>
      <p style={{ margin: 0, fontSize: 13, color: "var(--text-2)" }}>{d.winPct}% win rate · {d.active} active targets · {d.sentWeek} touches sent. Recent wins: {d.wins.map((w) => w.brand).join(", ")}.</p>
      <button className="btn btn--primary" style={{ marginTop: 18 }} onClick={onOpen}><Icon name="arrowUpRight" size={14} /> Open today's queue</button>
    </EmailFrame>
  );
}

function InterestedEmail({ r, onOpen }) {
  return (
    <EmailFrame subject={`🔥 ${r.brand} is interested — wants to talk`}>
      <p style={{ margin: "0 0 14px", fontSize: 14 }}><b>{r.contact.name}</b> at <b>{r.brand}</b> replied and they're warm. Claude flagged this as ready to move.</p>
      <div className="int-quote"><Icon name="reply" size={13} style={{ color: "var(--green)" }} />"{r.quote}"</div>
      <div style={{ display: "flex", alignItems: "center", gap: 9, margin: "14px 0" }}>
        <Avatar name={r.contact.name} initials={r.contact.initials} color={r.contact.color} size={32} />
        <div><div style={{ fontSize: 13, fontWeight: 600 }}>{r.contact.name}</div><div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{r.contact.title} · {r.brand}</div></div>
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        <button className="btn btn--primary btn--sm" onClick={onOpen}><Icon name="sparkles" size={13} /> Draft reply</button>
        <button className="btn btn--sm" onClick={onOpen}><Icon name="calendar" size={13} /> Book a call</button>
      </div>
    </EmailFrame>
  );
}

function NotificationCenter({ onClose, onGoInbox, onGoToday }) {
  const D = React.useMemo(notifData, []);
  const items = [
    { type: "digest", title: "Daily update", sub: `${D.digest.replies} replies · ${D.digest.dueToday} to send`, time: "8:00 AM", icon: "today", unread: true },
    ...D.interested.map((r) => ({ type: "interested", r, title: `${r.brand} is interested`, sub: r.contact.name + " wants to talk", time: r.time, icon: "flame", unread: true })),
  ];
  const [sel, setSel] = React.useState(items[0]);
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal notif-modal" onClick={(e) => e.stopPropagation()}>
        <div className="notif-list">
          <div className="notif-list-head"><Icon name="bell" size={15} style={{ color: "var(--accent)" }} /><span style={{ fontSize: 14, fontWeight: 700 }}>Notifications</span><span className="num notif-badge">{items.length}</span></div>
          <div className="notif-scroll">
            {items.map((it, i) => (
              <button key={i} className="notif-item" data-active={sel === it || undefined} onClick={() => setSel(it)}>
                <span className="notif-ico" style={{ color: it.type === "interested" ? "var(--amber)" : "var(--accent)" }}><Icon name={it.icon} size={15} /></span>
                <div style={{ minWidth: 0, flex: 1 }}><div style={{ fontSize: 12.5, fontWeight: 650, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.title}</div><div style={{ fontSize: 11, color: "var(--text-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.sub}</div></div>
                <span style={{ fontSize: 10.5, color: "var(--text-3)", flex: "none" }}>{it.time}</span>
              </button>
            ))}
          </div>
          <div className="notif-foot"><Icon name="mail" size={13} /> Sent to your inbox in real time</div>
        </div>
        <div className="notif-preview">
          <button className="btn btn--ghost btn--icon settings-x" onClick={onClose}><Icon name="x" size={18} /></button>
          {sel.type === "digest"
            ? <DigestEmail d={D.digest} onOpen={() => { onClose(); onGoToday(); }} />
            : <InterestedEmail r={sel.r} onOpen={() => { onClose(); onGoInbox(); }} />}
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { NotificationCenter, notifData });
