/* ============================================================
   App shell — icon rail + lane-folder sidebar + surface routing.
   ============================================================ */

const SURFACES = [
  { id: "assistant", label: "Assistant", icon: "sparkles" },
  { id: "inbox",     label: "Inbox",     icon: "inbox" },
  { id: "contacts",  label: "Contacts",  icon: "contacts" },
  { id: "campaigns", label: "Campaigns", icon: "sequence" },
  { id: "scouting",  label: "Scouting",  icon: "radar" },
  { id: "stats",     label: "Stats",     icon: "gauge" },
  { id: "agents",    label: "Agents",    icon: "bot" },
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "inboxLayout": "unibox",
  "accent": "#6CACE4",
  "density": "regular"
}/*EDITMODE-END*/;

function laneCount(laneId) {
  const ts = window.WTC.targets;
  if (laneId === "all") return ts.filter((t) => !["won", "lost"].includes(t.stage)).length;
  return ts.filter((t) => t.lane === laneId && !["won", "lost"].includes(t.stage)).length;
}

// ---- Composer modal ----
function ComposerModal({ targetId, contactId, onClose }) {
  const W = window.WTC;
  const target = W.targets.find((t) => t.id === targetId);
  if (!target) return null;
  const contact = target.contacts.find((c) => c.id === contactId) || target.contacts[0];
  const [sent, setSent] = React.useState(false);
  const thread = W.threads.find((th) => th.targetId === target.id) || null;
  const [showThread, setShowThread] = React.useState(true);
  const replySubject = thread ? "Re: " + thread.subject.replace(/^Re:\s*/i, "") : `We The Creators × ${target.brand}`;
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal compose-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <Avatar mono={target.mono} size={36} square />
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 15.5, fontWeight: 680 }}>Compose to {target.brand}</span>
                <LaneChip lane={target.lane} small />
              </div>
              <div style={{ fontSize: 12, color: "var(--text-2)", marginTop: 2 }}>
                {contact.name} · {contact.title} · <StageDot stage={target.stage} /> <span style={{ marginLeft: 4 }} className="num">{target.cadence.label}</span>
              </div>
            </div>
          </div>
          <button className="btn btn--ghost btn--icon" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        {target.contacts.length > 1 && (
          <div className="contact-pills">
            <span style={{ fontSize: 11.5, color: "var(--text-3)" }}>Recipients:</span>
            {target.contacts.map((c) => (
              <span key={c.id} className={"contact-pill" + (c.id === contact.id ? " active" : "")}>
                <Avatar name={c.name} initials={c.initials} color={c.color} size={18} />
                {c.name}
                <span className={"side-tag side-tag--" + c.side} style={{ marginLeft: 2 }}>{c.side === "brand" ? "Brand" : "Agency"}</span>
              </span>
            ))}
          </div>
        )}
        <div className="modal-body">
          {thread && (
            <div className="compose-thread">
              <button className="compose-thread-toggle" onClick={() => setShowThread((s) => !s)}>
                <Icon name="mail" size={13} />
                <span style={{ flex: 1, textAlign: "left" }}>Conversation · {thread.messages.length} message{thread.messages.length > 1 ? "s" : ""}</span>
                <span style={{ fontSize: 11.5, color: "var(--text-3)" }}>{thread.subject}</span>
                <Icon name="chevronDown" size={14} style={{ transform: showThread ? "rotate(180deg)" : "none", transition: "transform var(--t)" }} />
              </button>
              {showThread && (
                <div className="compose-thread-body">
                  {thread.messages.map((m) => {
                    const mine = m.from === "me";
                    return (
                      <div key={m.id} className="ct-msg" data-mine={mine || undefined}>
                        <div className="ct-msg-head">
                          {mine ? <Avatar name={W.ME.name} initials={W.ME.initials} size={20} /> : <Avatar name={thread.contact.name} initials={thread.contact.initials} color={thread.contact.color} size={20} />}
                          <span style={{ fontWeight: 650, fontSize: 12 }}>{mine ? "Preston" : thread.contact.name}</span>
                          <span style={{ flex: 1 }}></span>
                          <span style={{ fontSize: 11, color: "var(--text-3)" }}>{m.time}</span>
                        </div>
                        <div className="ct-msg-body">{m.body}</div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}
          <Composer target={target} contact={contact}
            thread={thread ? thread.messages : null}
            subject={replySubject}
            onSent={() => setSent(true)} />
        </div>
        {sent && <div className="toast toast--ok" style={{ position: "static", margin: "0 22px 18px" }}><Icon name="check" size={15} /> Marked sent · cadence advanced to step {Math.min(target.cadence.step + 1, target.cadence.total)}</div>}
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [surface, setSurface] = React.useState("assistant");
  const [lane, setLane] = React.useState("all");
  const [triage, setTriage] = React.useState("needs_attention");
  const [inboxFilter, setInboxFilter] = React.useState("all");
  const [selId, setSelId] = React.useState(null);
  const [search, setSearch] = React.useState("");
  const [compose, setCompose] = React.useState(null);  // {targetId, contactId}
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const [notifOpen, setNotifOpen] = React.useState(false);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [laneSheet, setLaneSheet] = React.useState(false);
  React.useEffect(() => {
    const h = (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setSearchOpen(true); } };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);
  const [detailId, setDetailId] = React.useState(null);  // target detail drawer
  const [threadState, setThreadState] = React.useState(() => window.__threadState || {}); // id -> {triage, starred}
  React.useEffect(() => { window.__threadState = threadState; }, [threadState]);

  const W = window.WTC;

  // apply accent tweak
  React.useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
  }, [t.accent]);

  // dismiss the preloader once mounted
  React.useEffect(() => {
    const p = document.getElementById("preloader");
    if (!p) return;
    const t1 = setTimeout(() => { p.classList.add("hide"); const t2 = setTimeout(() => p.remove(), 650); }, 400);
    return () => clearTimeout(t1);
  }, []);

  // derive threads with local overrides
  const allThreads = W.threads.map((th) => ({ ...th, ...(threadState[th.id] || {}) }));
  const inboxThreads = allThreads
    .filter((th) => (lane === "all" || th.lane === lane) && (triage === "drafts" ? th.hasDraft : th.triage === triage))
    .filter((th) => inboxFilter === "all" || th.inboxId === inboxFilter)
    .filter((th) => !search || (th.brand + th.subject + th.contact.name).toLowerCase().includes(search.toLowerCase()));

  const onTriage = (id, newTriage) => {
    setThreadState((s) => ({ ...s, [id]: { ...s[id], triage: newTriage } }));
    setSelId(null);
  };
  const onSnooze = (id) => { setThreadState((s) => ({ ...s, [id]: { ...s[id], triage: "not_now" } })); setSelId(null); };
  const onStar = (id) => setThreadState((s) => ({ ...s, [id]: { ...s[id], starred: !allThreads.find((x) => x.id === id).starred } }));

  const openCompose = (targetId, contactId, onCloseApprove) => setCompose({ targetId, contactId, onCloseApprove });
  const closeCompose = () => { if (compose && compose.onCloseApprove) compose.onCloseApprove(); setCompose(null); };
  const approveTarget = (target) => setCompose({ targetId: target.id, contactId: target.contacts[0].id });
  const targetById = (id) => W.targets.find((x) => x.id === id);

  const [timeframe, setTimeframe] = React.useState("30 days");

  // reset selection when switching lanes/triage
  React.useEffect(() => { setSelId(null); }, [lane, triage, surface]);

  const densityClass = "density-" + t.density;

  return (
    <div className={"app " + densityClass} data-skin="targets">
      {/* mobile top bar */}
      <div className="mobile-top">
        <button className="mtop-btn" onClick={() => setLaneSheet(true)} title="Lanes"><Icon name="filter" size={19} /></button>
        <span className="mtop-title">{(SURFACES.find((x) => x.id === surface) || {}).label || "Targets"}</span>
        <button className="mtop-btn" onClick={() => setSearchOpen(true)}><Icon name="search" size={19} /></button>
        <button className="mtop-btn rail-bell" onClick={() => setNotifOpen(true)}><Icon name="bell" size={19} /><span className="rail-bell-dot"></span></button>
      </div>
      {/* icon rail */}
      <nav className="rail">
        <div className="rail-logo" title="We The Creators — Targets"><Icon name="mountain" size={20} /></div>
        <div className="rail-items">
          {SURFACES.map((s) => (
            <button key={s.id} className="rail-btn" data-active={surface === s.id || undefined}
              onClick={() => setSurface(s.id)} title={s.label}>
              <Icon name={s.icon} size={20} />
              <span className="rail-tip">{s.label}</span>
            </button>
          ))}
        </div>
        <div className="rail-bottom">
          <button className="rail-btn rail-bell" title="Notifications" onClick={() => setNotifOpen(true)}>
            <Icon name="bell" size={19} />
            <span className="rail-bell-dot"></span>
          </button>
          <button className="rail-btn" title="Settings" data-active={settingsOpen || undefined} onClick={() => setSettingsOpen(true)}><Icon name="settings" size={19} /></button>
          <div className="rail-avatar" title={W.ME.name} onClick={() => setSettingsOpen(true)} style={{ cursor: "pointer" }}>
            <Avatar name={W.ME.name} initials={W.ME.initials} size={30} />
          </div>
        </div>
      </nav>

      {/* lane-folder sidebar */}
      <aside className="sidebar">
        <div className="sidebar-head">
          <a className="wtc-backlink" href="https://app.wethecreators.io" title="Back to the We The Creators CRM">
            <Icon name="chevronLeft" size={13} /> We The Creators CRM
          </a>
          <span style={{ fontSize: 16, fontWeight: 720, letterSpacing: "-0.01em" }}>Targets</span>
          <span className="sidebar-sub">Outbound BD engine</span>
        </div>
        <button className="sidebar-search" onClick={() => setSearchOpen(true)}>
          <Icon name="search" size={15} /><span style={{ flex: 1, textAlign: "left" }}>Search…</span><span className="search-kbd">⌘K</span>
        </button>

        <div className="side-group">
          <div className="side-group-label">Lanes</div>
          {W.LANES.map((l) => (
            <button key={l.id} className="folder" data-active={lane === l.id || undefined} onClick={() => setLane(l.id)}>
              {l.chip
                ? <span className="chip-dot" style={{ background: "var(--lane-" + (l.chip === "event" ? "event" : l.chip === "travel" ? "travel" : l.chip === "brand" ? "brand" : "agency") + ")" }}></span>
                : <span className="chip-dot" style={{ background: "var(--text-3)" }}></span>}
              <span style={{ flex: 1, textAlign: "left" }}>{l.label}</span>
              <span className="num folder-count">{laneCount(l.id)}</span>
            </button>
          ))}
        </div>

        <div className="side-group">
          <div className="side-group-label">This {timeframe.toLowerCase()}</div>
          <div className="side-stat">
            <span style={{ color: "var(--text-2)" }}>Win rate</span>
            <span className="num" style={{ color: "var(--green)", fontWeight: 700, fontSize: 15 }}>{W.kpis.winPct}%</span>
          </div>
          <div className="side-stat">
            <span style={{ color: "var(--text-2)" }}>Due today</span>
            <span className="num" style={{ color: "var(--accent)", fontWeight: 700, fontSize: 15 }}>{W.kpis.dueToday}</span>
          </div>
          <div className="side-stat">
            <span style={{ color: "var(--text-2)" }}>Replies waiting</span>
            <span className="num" style={{ color: "var(--amber)", fontWeight: 700, fontSize: 15 }}>{allThreads.filter((x) => x.triage === "needs_attention").length}</span>
          </div>
        </div>

        <div className="sidebar-foot">
          <button className="btn btn--primary" style={{ width: "100%" }} onClick={() => setSurface("assistant")}>
            <Icon name="sparkles" size={15} /> Ask Claude
          </button>
        </div>
      </aside>

      {/* main */}
      <main className="main">
        {surface === "assistant" && <Assistant lane={lane} onApprove={approveTarget} onDraft={(id, cid, cb) => openCompose(id, cid, cb)} />}
        {surface === "agents" && <Agents go={setSurface} />}
        {surface === "today" && null}
        {surface === "inbox" && (
          <Inbox threads={inboxThreads} lane={lane} triage={triage} setTriage={setTriage}
            layout={t.inboxLayout} selId={selId} setSelId={setSelId}
            onTriage={onTriage} onSnooze={onSnooze} onStar={onStar} targetById={targetById}
            search={search} setSearch={setSearch}
            inboxFilter={inboxFilter} setInboxFilter={setInboxFilter} onOpenTarget={setDetailId} />
        )}
        {surface === "contacts" && <Contacts lane={lane} onDraft={(id, cid) => openCompose(id, cid)} />}
        {surface === "campaigns" && <Campaigns lane={lane} />}
        {surface === "scouting" && <Scouting />}
        {surface === "stats" && <Deliverability onApprove={approveTarget} />}
      </main>

      {compose && <ComposerModal targetId={compose.targetId} contactId={compose.contactId} onClose={closeCompose} />}
      {detailId && <TargetDetail targetId={detailId} onClose={() => setDetailId(null)} onCompose={(id, cid) => { setDetailId(null); openCompose(id, cid); }} />}
      {settingsOpen && <Settings onClose={() => setSettingsOpen(false)} />}
      {notifOpen && <NotificationCenter onClose={() => setNotifOpen(false)} onGoInbox={() => setSurface("inbox")} onGoToday={() => setSurface("assistant")} />}
      {searchOpen && <GlobalSearch onClose={() => setSearchOpen(false)} onTarget={(id) => setDetailId(id)} onGo={(id) => setSurface(id)} />}

      {/* mobile bottom nav */}
      <nav className="mobile-nav">
        {SURFACES.slice(0, 5).map((s) => (
          <button key={s.id} className="mnav-btn" data-active={surface === s.id || undefined} onClick={() => setSurface(s.id)}>
            <Icon name={s.icon} size={20} /><span>{s.label}</span>
          </button>
        ))}
        <button className="mnav-btn" onClick={() => setLaneSheet(true)}><Icon name="more" size={20} /><span>More</span></button>
      </nav>

      {/* mobile lane + more sheet */}
      {laneSheet && (
        <div className="sheet-scrim" onClick={() => setLaneSheet(false)}>
          <div className="sheet" onClick={(e) => e.stopPropagation()}>
            <div className="sheet-handle"></div>
            <div className="sheet-label">Lanes</div>
            <div className="sheet-lanes">
              {W.LANES.map((l) => (
                <button key={l.id} className="folder" data-active={lane === l.id || undefined} onClick={() => { setLane(l.id); setLaneSheet(false); }}>
                  <span className="chip-dot" style={{ background: l.chip ? `var(--lane-${l.chip})` : "var(--text-3)" }}></span>
                  <span style={{ flex: 1, textAlign: "left" }}>{l.label}</span>
                  <span className="num folder-count">{laneCount(l.id)}</span>
                </button>
              ))}
            </div>
            <div className="sheet-label">More</div>
            <div className="sheet-more">
              {SURFACES.slice(5).map((s) => (
                <button key={s.id} className="sheet-more-btn" data-active={surface === s.id || undefined} onClick={() => { setSurface(s.id); setLaneSheet(false); }}>
                  <Icon name={s.icon} size={18} /> {s.label}
                </button>
              ))}
              <button className="sheet-more-btn" onClick={() => { setSettingsOpen(true); setLaneSheet(false); }}><Icon name="settings" size={18} /> Settings</button>
              <a className="sheet-more-btn" href="https://app.wethecreators.io"><Icon name="chevronLeft" size={18} /> WTC CRM</a>
            </div>
          </div>
        </div>
      )}

      {/* Tweaks */}
      <TweaksPanel>
        <TweakSection label="Inbox" />
        <TweakRadio label="Layout" value={t.inboxLayout}
          options={["unibox", "split", "table"]}
          onChange={(v) => setTweak("inboxLayout", v)} />
        <TweakSection label="Appearance" />
        <TweakColor label="Accent" value={t.accent}
          options={["#6CACE4", "#7FB98C", "#C9A06B", "#B69BE8"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakRadio label="Density" value={t.density}
          options={["compact", "regular"]}
          onChange={(v) => setTweak("density", v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
