// Lead detail — right-side drawer with all fields, status history, comment thread
const { useState: useDS, useEffect: useDE, useRef: useDR } = React;

function stripHtml(s) {
  return (s || "").replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
}

function LeadDetail({ lead, onClose, onNoteAdded }) {
  const [closing,         setClosing]         = useDS(false);
  const [draft,           setDraft]           = useDS("");
  const [liveActivity,    setLiveActivity]    = useDS([]);
  const [activityLoading, setActivityLoading] = useDS(false);
  const [posting,         setPosting]         = useDS(false);
  const threadRef = useDR(null);

  function close() { setClosing(true); setTimeout(onClose, 220); }

  useDE(() => {
    function onKey(e) { if (e.key === "Escape") close(); }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  // Fetch activity (system logs + notes) whenever the lead changes
  useDE(() => {
    if (!lead.lead_id) return;
    setLiveActivity([]);
    setActivityLoading(true);
    const id = lead.lead_id;

    let storedEmail = null;
    try { storedEmail = JSON.parse(localStorage.getItem("roa_user") || "{}").email; } catch (_) {}

    Promise.all([
      window.api.getSystemLogs(id),
      window.api.getNotes(id),
    ]).then(([logItems, noteItems]) => {
      const logs = (logItems || []).map((l) => {
        const isStatusChange = l.action === "status changed";
        return {
          kind:        "log",
          action:      l.action || "",
          from:        isStatusChange ? (l.existing_record?.status || "") : null,
          to:          isStatusChange ? (l.new_record?.status || "") : null,
          description: isStatusChange ? null : stripHtml(l.description || l.action || ""),
          time:        l.created,
        };
      });

      const notes = (noteItems || [])
        .filter((n) => n.category !== "call")
        .map((n) => ({
          kind:   "comment",
          by:     n.created_by?.email === storedEmail ? "Mainstay" : "ROA",
          author: n.created_by?.full_name || "Unknown",
          text:   n.note,
          time:   n.created,
        }));

      // Newest first
      const merged = [...logs, ...notes].sort((a, b) => new Date(b.time) - new Date(a.time));
      setLiveActivity(merged);
    }).catch(() => {}).finally(() => setActivityLoading(false));
  }, [lead.lead_id]);

  if (!lead) return null;

  const addr         = [lead.street, [lead.city, lead.state].filter(Boolean).join(", "), lead.zip].filter(Boolean).join(" · ");
  const activity     = liveActivity;
  const commentCount = lead.note_count || liveActivity.filter((a) => a.kind === "comment").length;

  async function post() {
    if (!draft.trim() || posting) return;
    const text = draft.trim();
    setDraft("");
    setPosting(true);
    try {
      const r = await window.api.createNote(lead.lead_id, text);
      if (r?.status === "success") {
        let storedName = "Mainstay";
        try { storedName = JSON.parse(localStorage.getItem("roa_user") || "{}").full_name || "Mainstay"; } catch (_) {}
        const entry = { kind: "comment", by: "Mainstay", author: storedName, text, time: new Date().toISOString() };
        setLiveActivity((prev) => [entry, ...prev]);
        if (onNoteAdded) onNoteAdded(lead.id);
      }
    } catch (_) {} finally {
      setPosting(false);
    }
  }

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200, display: "flex", justifyContent: "flex-end" }}>
      <div onClick={close} style={{ position: "absolute", inset: 0, background: "#10162e66",
        animation: closing ? "none" : "overlayIn .2s ease both", opacity: closing ? 0 : 1, transition: "opacity .2s ease" }}></div>

      <div className="thin-scroll" style={{ position: "relative", width: "min(620px, 94vw)", height: "100%",
        background: "var(--bg-app)", overflowY: "auto", boxShadow: "-20px 0 60px #10162e22",
        animation: closing ? "none" : "drawerIn .26s cubic-bezier(.2,.8,.25,1) both",
        transform: closing ? "translateX(100%)" : "none", transition: "transform .22s ease" }}>

        {/* header */}
        <div style={{ position: "sticky", top: 0, zIndex: 5, background: "#ffffffec", backdropFilter: "blur(10px)",
          borderBottom: "1px solid var(--border)", padding: "18px 24px" }}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, rowGap: 7, marginBottom: 7, flexWrap: "wrap" }}>
                <span className="mono" style={{ fontSize: 12, color: "var(--muted)", background: "#F1F2F4", padding: "2px 8px", borderRadius: 6 }}>{lead.id}</span>
                <StatusBadge status={lead.status} />
                {(lead.types || []).map((t) => <TypeChip key={t} t={t} />)}
              </div>
              <h2 style={{ fontSize: 22, fontWeight: 800, margin: 0, color: "var(--navy)", letterSpacing: "-.01em" }}>{lead.name}</h2>
            </div>
            <button onClick={close} className="btn btn-icon" style={{ background: "#fff", border: "1px solid var(--border)", color: "var(--muted)", width: 38, height: 38 }}>
              <Icon name="x" size={18} />
            </button>
          </div>
        </div>

        <div style={{ padding: "22px 24px 40px" }}>
          {/* assigned agent banner */}
          <div className="card" style={{ padding: 16, marginBottom: 16, boxShadow: "var(--card-shadow-2)",
            display: "flex", alignItems: "center", gap: 14 }}>
            <Avatar agent={lead.agent} size={46} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, color: "var(--muted)", fontWeight: 600, marginBottom: 2 }}>Assigned agent</div>
              {lead.agent ? (
                <>
                  <div style={{ fontWeight: 700, fontSize: 15.5 }}>{lead.agent.name}</div>
                  {lead.agent.office && <div style={{ fontSize: 12.5, color: "var(--muted)" }}>{lead.agent.office}</div>}
                </>
              ) : (
                <div style={{ fontWeight: 600, fontSize: 14.5, color: "var(--muted)", fontStyle: "italic" }}>Awaiting assignment from the pipeline</div>
              )}
            </div>
            <span style={{ fontSize: 11, fontWeight: 700, color: "var(--muted)", background: "#F1F2F4", padding: "5px 10px", borderRadius: 99,
              display: "inline-flex", alignItems: "center", gap: 5 }}>
              <Icon name="lock" size={12} /> From FUB
            </span>
          </div>

          {/* contact */}
          <Block title="Contact">
            <Row icon="user"   label="Client"   value={lead.name} />
            <Row icon="phone"  label="Phone"    value={lead.phone} />
            <Row icon="mail"   label="Email"    value={lead.email || "—"} muted={!lead.email} />
            <Row icon="mapPin" label="Property" value={addr || "—"} muted={!addr} last />
          </Block>

          {/* activity + comments */}
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 9 }}>
              <Icon name="message" size={16} style={{ color: "var(--navy)" }} />
              <div style={{ fontWeight: 700, fontSize: 15, color: "var(--navy)" }}>Activity &amp; comments</div>
              <span style={{ marginLeft: "auto", fontSize: 12, color: "var(--muted)", fontWeight: 600 }}>
                {commentCount} {commentCount === 1 ? "comment" : "comments"}
              </span>
            </div>

            <div ref={threadRef} className="thin-scroll" style={{ maxHeight: 340, overflowY: "auto", padding: 18 }}>
              {activityLoading ? (
                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  {Array.from({ length: 3 }).map((_, i) => (
                    <div key={i} style={{ display: "flex", gap: 13 }}>
                      <div className="sk" style={{ width: 11, height: 11, borderRadius: 99, flexShrink: 0, marginTop: 4 }}></div>
                      <div style={{ flex: 1 }}>
                        <div className="sk" style={{ width: "70%", height: 13, marginBottom: 6 }}></div>
                        <div className="sk" style={{ width: "40%", height: 11 }}></div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div style={{ position: "relative" }}>
                  {activity.length === 0
                    ? <div style={{ fontSize: 13.5, color: "var(--muted)", textAlign: "center", padding: "20px 0" }}>No activity yet.</div>
                    : activity.map((a, i) => <ActivityItem key={i} a={a} last={i === activity.length - 1} />)}
                </div>
              )}
            </div>

            {/* composer */}
            <div style={{ padding: 14, borderTop: "1px solid var(--border)", background: "#FBFCFD" }}>
              <div style={{ display: "flex", gap: 10, alignItems: "flex-end" }}>
                <span style={{ width: 32, height: 32, borderRadius: 99, background: "var(--navy)", color: "#fff",
                  display: "grid", placeItems: "center", fontWeight: 700, fontSize: 11, flexShrink: 0 }}>MS</span>
                <textarea className="textarea" value={draft} onChange={(e) => setDraft(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) post(); }}
                  placeholder="Add a comment for the agent or ROA ops..." rows={2}
                  style={{ minHeight: 44, flex: 1 }} />
              </div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10, paddingLeft: 42 }}>
                <span style={{ fontSize: 11.5, color: "var(--muted)" }}>Shared with the assigned agent · <span className="kbd">⌘</span> <span className="kbd">↵</span> to send</span>
                <button className="btn btn-navy btn-sm" disabled={!draft.trim() || posting} onClick={post}>
                  <Icon name="message" size={15} /> {posting ? "Posting..." : "Post comment"}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Block({ title, children }) {
  return (
    <div className="card" style={{ padding: 18, marginBottom: 16 }}>
      <div style={{ fontWeight: 700, fontSize: 12, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 12 }}>{title}</div>
      {children}
    </div>
  );
}

function Row({ icon, label, value, muted, last }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 0",
      borderBottom: last ? "none" : "1px solid #F1F2F4" }}>
      <Icon name={icon} size={16} style={{ color: "var(--muted)", flexShrink: 0 }} />
      <div style={{ fontSize: 13, color: "var(--muted)", fontWeight: 600, width: 140, flexShrink: 0 }}>{label}</div>
      <div style={{ fontSize: 13.5, fontWeight: 600, color: muted ? "#A2A8B2" : "var(--foreground)",
        fontStyle: muted ? "italic" : "normal", textAlign: "right", flex: 1 }}>{value}</div>
    </div>
  );
}

function ActivityItem({ a, last }) {
  const isLog     = a.kind === "log";
  const isComment = a.kind === "comment";
  const isROA     = a.by === "ROA";
  const dotColor  = isLog ? "#C4C9D1" : isComment ? (isROA ? "var(--blue)" : "var(--navy)") : "var(--emerald)";

  return (
    <div style={{ display: "flex", gap: 13, position: "relative", paddingBottom: last ? 0 : 18 }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flexShrink: 0 }}>
        <span style={{ width: 11, height: 11, borderRadius: 99, background: dotColor, marginTop: 4,
          boxShadow: isLog ? "none" : "0 0 0 3px " + (isComment ? (isROA ? "var(--st-blue-bg)" : "var(--accent-soft)") : "var(--st-high-bg)") }}></span>
        {!last && <span style={{ flex: 1, width: 2, background: "#EAEDF2", marginTop: 4, minHeight: 14 }}></span>}
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        {isComment ? (
          <div style={{ background: isROA ? "#fff" : "var(--accent-soft)",
            border: "1px solid " + (isROA ? "var(--border)" : "#D6E0F2"), borderRadius: 11, padding: "11px 13px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5 }}>
              <span style={{ fontWeight: 700, fontSize: 13 }}>{a.author}</span>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: isROA ? "var(--blue)" : "var(--navy)",
                background: isROA ? "var(--st-blue-bg)" : "#fff", padding: "1px 7px", borderRadius: 99 }}>{a.by}</span>
              <span style={{ marginLeft: "auto", fontSize: 11.5, color: "var(--muted)" }}>{relTime(a.time)}</span>
            </div>
            <div style={{ fontSize: 13.5, color: "var(--desc)", lineHeight: 1.5, fontWeight: 500 }}>{a.text}</div>
          </div>
        ) : isLog ? (
          <div style={{ paddingTop: 1 }}>
            {a.from != null ? (
              <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap", fontSize: 13.5 }}>
                <span style={{ color: "var(--muted)", fontWeight: 600 }}>Lead status changed</span>
                <span style={{ fontWeight: 700, color: "var(--foreground)" }}>{a.from || "—"}</span>
                <span style={{ color: "var(--muted)" }}>→</span>
                <span style={{ fontWeight: 700, color: "var(--navy)" }}>{a.to || "—"}</span>
              </div>
            ) : (
              <div style={{ fontSize: 13.5, color: "var(--desc)", lineHeight: 1.5 }}>{a.description}</div>
            )}
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{fmtDateTime(a.time)}</div>
          </div>
        ) : (
          <div style={{ paddingTop: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>
              Status set to <span style={{ color: "var(--navy)" }}>{a.status}</span>
              {a.agent && <span style={{ color: "var(--desc)", fontWeight: 500 }}> · {a.agent.name}</span>}
            </div>
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{a.by} · {fmtDateTime(a.time)}</div>
          </div>
        )}
      </div>
    </div>
  );
}

window.LeadDetail = LeadDetail;
