/* ============================================================
   TargetDetail — the connective tissue. Opens when you click a
   target anywhere. Unifies: header + stage, contacts, flow
   position, a cross-channel activity timeline, and the post-meeting
   handoff (→ WTC platform as a new prospect).
   ============================================================ */

// Build a cross-channel activity timeline for a target from threads + cadence.
function targetTimeline(t) {
  const W = window.WTC;
  const ths = W.threads.filter((th) => th.targetId === t.id);
  const ev = [];
  ths.forEach((th) => {
    th.messages.forEach((m) => {
      ev.push({
        kind: m.from === "me" ? "sent" : "reply",
        channel: "email",
        who: m.from === "me" ? "You" : th.contact.name.split(" ")[0],
        text: m.body, time: m.time,
      });
    });
  });
  // synthesize a couple of non-email touches so the cross-channel story reads
  if (t.contacts.some((c) => c.side === "agency") || t.lane === "agency") ev.push({ kind: "linkedin", channel: "linkedin", who: "You", text: "Sent a LinkedIn connection request.", time: "Earlier" });
  if (t.lane === "travel") ev.push({ kind: "ig", channel: "instagram", who: "You", text: "Followed the property on Instagram to warm up.", time: "Earlier" });
  ev.push({ kind: "enrolled", channel: "system", who: "Claude", text: `Enrolled in the ${W.LANE_META[t.lane].label} follow-up flow.`, time: "Flow start" });
  return ev;
}
const TL_META = {
  sent: { icon: "send", color: "var(--accent)", label: "Email sent" },
  reply: { icon: "reply", color: "var(--green)", label: "Reply received" },
  linkedin: { icon: "linkedin", color: "#8FB8E8", label: "LinkedIn" },
  ig: { icon: "instagram", color: "var(--lane-agency)", label: "Instagram" },
  enrolled: { icon: "sequence", color: "var(--text-2)", label: "Flow" },
  note: { icon: "draft", color: "var(--text-2)", label: "Note" },
  meeting: { icon: "calendar", color: "var(--amber)", label: "Meeting" },
};

function TargetDetail({ targetId, onClose, onCompose }) {
  const W = window.WTC;
  const t = W.targets.find((x) => x.id === targetId);
  const [handoff, setHandoff] = React.useState(false);
  const [booking, setBooking] = React.useState(false);
  const [stage, setStage] = React.useState(t ? t.stage : "new");
  const [toast, setToast] = React.useState(null);
  const flash = (m) => { setToast(m); setTimeout(() => setToast(null), 1900); };
  if (!t) return null;

  const SM = W.STAGE_META;
  const enr = W.enrollments[t.contacts[0].id];
  const flow = enr ? W.sequences.find((s) => s.id === enr.seqId) : W.sequences.find((s) => s.lane === t.lane);
  const flowStep = enr ? enr.step : 1;
  const tl = targetTimeline(t);
  const tlReplies = tl.filter((e) => e.kind === "reply").length;
  const tlSent = tl.filter((e) => e.kind === "sent").length;

  const STAGES = ["new", "contacted", "in_convo", "pitched", "won", "lost"];

  return (
    <div className="drawer-scrim" onClick={onClose}>
      <div className="contact-drawer target-detail" onClick={(e) => e.stopPropagation()} style={{ width: "min(560px, 96%)" }}>
        <button className="btn btn--ghost btn--icon drawer-x" onClick={onClose}><Icon name="x" size={18} /></button>

        {/* header */}
        <div className="cd-head" style={{ alignItems: "center" }}>
          <Avatar mono={t.mono} size={52} square />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 19, fontWeight: 720 }}>{t.brand}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 5, flexWrap: "wrap" }}>
              <LaneChip lane={t.lane} small />
              <span style={{ fontSize: 12, color: "var(--text-2)" }}>{t.event}</span>
              {t.value > 0 && <span className="num" style={{ fontSize: 12, color: "var(--green)", fontWeight: 600 }}>{fmtMoney(t.value)}</span>}
            </div>
          </div>
        </div>

        {/* stage pipeline */}
        <div className="td-stages">
          {STAGES.map((s) => (
            <button key={s} className="td-stage" data-on={stage === s || undefined} data-done={STAGES.indexOf(s) < STAGES.indexOf(stage) && stage !== "lost" || undefined}
              onClick={() => { setStage(s); flash("Moved to " + SM[s].label); }}>
              <span className="stagedot" style={{ background: SM[s].color }}></span>{SM[s].label}
            </button>
          ))}
        </div>

        {/* won → handoff banner */}
        {stage === "won" && (
          <div className="handoff-banner">
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <Icon name="trend" size={16} style={{ color: "var(--green)" }} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 650 }}>Won — ready to hand off</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>After the meeting, move them to the WTC platform as a new prospect.</div>
              </div>
            </div>
            <button className="btn btn--primary btn--sm" onClick={() => setHandoff(true)}><Icon name="arrowUpRight" size={14} /> Send to WTC platform</button>
          </div>
        )}

        {/* quick actions */}
        <div className="cd-actions">
          <button className="btn btn--primary" onClick={() => onCompose(t.id, t.contacts[0].id)}><Icon name="sparkles" size={15} /> Draft outreach</button>
          <button className="btn" onClick={() => flash("Logged a touch")}><Icon name="checkDouble" size={15} /> Log touch</button>
          <button className="btn" onClick={() => setBooking(true)}><Icon name="calendar" size={15} /> Book meeting</button>
        </div>

        {/* flow position */}
        {flow && (
          <div className="cd-section">
            <div className="cd-section-label">Follow-up flow</div>
            <div className="td-flow">
              <LaneChip lane={flow.lane} small />
              <span style={{ fontSize: 13, fontWeight: 600, flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{flow.name}</span>
              <span className="num" style={{ fontSize: 12, color: "var(--text-2)" }}>Step {flowStep} of {flow.steps.length}</span>
            </div>
            <div className="td-flow-track">
              {flow.steps.map((s, i) => <span key={i} className="td-flow-pip" data-on={i < flowStep || undefined} title={s.channel}></span>)}
            </div>
          </div>
        )}

        {/* contacts */}
        <div className="cd-section">
          <div className="cd-section-label">Contacts · {t.contacts.length}</div>
          {t.contacts.map((c) => (
            <div key={c.id} className="ev-row">
              <Avatar name={c.name} initials={c.initials} color={c.color} size={28} />
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{c.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{c.title}</div>
              </div>
              <span className={"side-tag side-tag--" + c.side}>{c.side === "brand" ? "Brand" : "Agency"}</span>
              <button className="icon-act" title="Draft" onClick={() => onCompose(t.id, c.id)}><Icon name="sparkles" size={14} /></button>
            </div>
          ))}
        </div>

        {/* activity timeline */}
        <div className="cd-section">
          <div className="cd-section-label">Activity · <span className="num">{tlSent}</span> sent · <span className="num">{tlReplies}</span> replies</div>
          <div className="timeline">
            {tl.map((e, i) => {
              const m = TL_META[e.kind] || TL_META.note;
              return (
                <div key={i} className="tl-row">
                  <div className="tl-rail"><span className="tl-dot" style={{ background: m.color }}><Icon name={m.icon} size={11} /></span>{i < tl.length - 1 && <span className="tl-line"></span>}</div>
                  <div className="tl-body">
                    <div className="tl-head"><span style={{ fontWeight: 600, fontSize: 12.5 }}>{m.label}</span><span style={{ fontSize: 11, color: "var(--text-3)" }}>{e.who} · {e.time}</span></div>
                    <div className="tl-text">{e.text}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {handoff && <HandoffModal t={t} onClose={() => setHandoff(false)} onDone={() => { setHandoff(false); flash(t.brand + " sent to WTC platform as a new prospect"); }} />}
        {booking && <BookingModal contact={t.contacts[0]} brand={t.brand} onClose={() => setBooking(false)} onBooked={() => { setBooking(false); flash("Meeting booked with " + t.contacts[0].name); }} />}
        {toast && <div className="toast toast--ok"><Icon name="check" size={15} /> {toast}</div>}
      </div>
    </div>
  );
}

function HandoffModal({ t, onClose, onDone }) {
  const [owner, setOwner] = React.useState("Preston Vance");
  const [type, setType] = React.useState(t.lane === "travel" ? "Travel partnership" : t.lane === "agency" ? "Agency retainer" : "Brand activation");
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" style={{ width: "min(460px, 100%)" }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Avatar mono={t.mono} size={32} square />
            <span style={{ fontSize: 15, fontWeight: 680 }}>Send {t.brand} to WTC platform</span>
          </div>
          <button className="btn btn--ghost btn--icon" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="modal-body" style={{ display: "flex", flexDirection: "column", gap: 15 }}>
          <div className="insp-note">They said yes in the meeting — this creates a <b>new prospect</b> on the WTC delivery platform and carries over the contacts, thread history, and value. Outreach stops here; the project picks up there.</div>
          <div className="brief-field"><label className="brief-label">Project type</label>
            <Segmented value={type} onChange={setType} options={["Brand activation", "Agency retainer", "Travel partnership"]} /></div>
          <div className="brief-field"><label className="brief-label">Owner</label>
            <input className="input" value={owner} onChange={(e) => setOwner(e.target.value)} /></div>
          <div className="brief-field"><label className="brief-label">Carries over</label>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
              {[t.contacts.length + " contacts", "Thread history", t.value > 0 ? fmtMoney(t.value) + " est." : "Value TBD", t.event].map((x) => (
                <span key={x} className="chip" style={{ background: "var(--elevated)", color: "var(--text-2)" }}>{x}</span>
              ))}
            </div>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, padding: "0 22px 20px" }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn btn--primary" onClick={onDone}><Icon name="arrowUpRight" size={14} /> Create prospect</button>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { TargetDetail });
