// Recursive MLS — Screen: Support (Realtor-facing ticketing).
// See your open tickets with the MLS and their status; submit a new request via a form
// that recommends knowledgebase articles/videos as you describe the problem.
function Support({ go }) {
  const KB = window.RC_KB;
  const [mode, setMode] = useState("list"); // list | new
  const [topic, setTopic] = useState("");
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const [linkType, setLinkType] = useState("listing");
  const [linked, setLinked] = useState(null);
  const [open, setOpen] = useState(null);

  const linkOptions = {
    listing: [{ id: "L1", label: "1408 Westover Rd", sub: "Draft · $1,875,000", icon: "home" }, { id: "L2", label: "845 Catalonia Ave", sub: "Active · $1,525,000", icon: "home" }, { id: "L3", label: "210 Palermo Ave", sub: "Pending · $980,000", icon: "home" }],
    showing: [{ id: "S1", label: "3050 Bird Ave", sub: "Tomorrow · 2:00 PM", icon: "calendar-clock" }, { id: "S2", label: "845 Catalonia Ave", sub: "Sat · 1:00 PM", icon: "calendar-clock" }],
    offer: [{ id: "O1", label: "Offer · 845 Catalonia Ave", sub: "Submitted · $1,500,000", icon: "file-signature" }],
  };

  const mine = KB.myTickets.map((id) => KB.ticketById(id)).filter(Boolean);
  const openCount = mine.filter((t) => t.status !== "solved").length;

  // live suggestions: map topic + typed text to sections, then articles
  const text = (topic + " " + subject + " " + body).toLowerCase();
  const topicSection = { listings: "listings", cma: "cma", showings: "showings", marketing: "marketing", rules: "rules", data: "data", search: "search" }[topic];
  let suggestions = KB.articles
    .map((a) => {
      let score = 0;
      if (a.section === topicSection) score += 3;
      const hay = (a.title + " " + a.desc).toLowerCase();
      text.split(/\s+/).filter((w) => w.length > 3).forEach((w) => { if (hay.includes(w)) score += 1; });
      return { a, score };
    })
    .filter((x) => x.score > 0).sort((a, b) => b.score - a.score).slice(0, 4).map((x) => x.a);
  if (suggestions.length === 0 && topicSection) suggestions = KB.articles.filter((a) => a.section === topicSection).slice(0, 3);

  const StatusPill = ({ s }) => { const m = KB.ticketStatus[s]; return <Pill tone={m.tone}>{m.label}</Pill>; };
  const chan = (c) => { const m = KB.channelMeta[c]; return <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, color: "#8a8e88" }}><Icon name={m.icon} size={13} color="#a8aca6" /> {m.label}</span>; };
  const typeIcon = (t) => KB.typeMeta[t].icon;

  const SuggestCard = ({ a, compact }) => (
    <div onClick={() => setOpen(a)} className="rc-row" style={{ display: "flex", gap: 11, alignItems: "center", padding: "10px 11px", border: "1px solid #e7e5df", borderRadius: 8, cursor: "pointer", background: "#fff" }}>
      <span style={{ width: 34, height: 34, borderRadius: 7, flex: "none", background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={typeIcon(a.type)} size={16} color="#006747" /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f", lineHeight: 1.3 }}>{a.title}</div>
        <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 2 }}>{KB.typeMeta[a.type].label} · {a.type === "video" ? a.duration : a.type === "pdf" ? a.pages + " pages" : a.readingTime}</div>
      </div>
      <Icon name="chevron-right" size={15} color="#c4c2b8" />
    </div>
  );

  return (
    <div style={{ height: "100%", overflowY: "auto", background: "#f4f3ef" }}>
      <div style={{ maxWidth: 1100, margin: "0 auto", padding: "26px 28px 64px" }}>

        {/* header */}
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 18, flexWrap: "wrap", marginBottom: 22 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1.5px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 6 }}>Support</div>
            <h1 style={{ margin: 0, fontSize: 27, fontWeight: 600, letterSpacing: "-0.6px" }}>Help &amp; support</h1>
            <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>Your requests to <strong style={{ color: "#4a504a", fontWeight: 600 }}>{KB.mls}</strong> support, and where each one stands.</p>
          </div>
          {mode === "list"
            ? <button onClick={() => setMode("new")} style={btnPrimaryS}><Icon name="plus" size={16} color="#fff" /> New request</button>
            : <button onClick={() => setMode("list")} style={btnGhostS}><Icon name="arrow-left" size={15} color="#006747" /> Back to my tickets</button>}
        </div>

        {mode === "list" ? (
          <React.Fragment>
            {/* quick stats */}
            <div style={{ display: "flex", gap: 14, marginBottom: 18 }}>
              {[["Open", openCount, "#006747"], ["Pending your reply", mine.filter((t) => t.status === "pending").length, "#9a6a12"], ["Solved", mine.filter((t) => t.status === "solved").length, "#8a8e88"]].map(([k, v, c]) => (
                <div key={k} style={{ flex: 1, background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "14px 16px" }}>
                  <div style={{ fontFamily: "'Space Mono',monospace", fontSize: 22, fontWeight: 700, color: c }}>{v}</div>
                  <div style={{ fontSize: 11.5, color: "#a8aca6", textTransform: "uppercase", letterSpacing: ".5px", marginTop: 2 }}>{k}</div>
                </div>
              ))}
              <div onClick={() => go && go("knowledge")} className="rc-row" style={{ flex: 2, background: "#006747", borderRadius: 3, padding: "14px 18px", display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }}>
                <span style={{ width: 38, height: 38, borderRadius: 8, background: "rgba(255,255,255,.14)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="graduation-cap" size={19} color="#fff" /></span>
                <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, fontWeight: 600, color: "#fff" }}>Search the knowledgebase first</div><div style={{ fontSize: 12, color: "rgba(255,255,255,.75)", marginTop: 1 }}>Most answers are a video or guide away.</div></div>
                <Icon name="arrow-right" size={18} color="rgba(255,255,255,.8)" />
              </div>
            </div>

            {/* tickets table */}
            <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", overflow: "hidden" }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 140px 130px 120px", gap: 12, padding: "11px 18px", borderBottom: "1px solid #f0efe9", fontSize: 10.5, fontWeight: 600, letterSpacing: ".5px", textTransform: "uppercase", color: "#a8aca6" }}>
                <span>Request</span><span>Channel</span><span>Updated</span><span>Status</span>
              </div>
              {mine.map((t) => (
                <div key={t.id} onClick={() => setOpen({ ticket: t })} className="rc-row" style={{ display: "grid", gridTemplateColumns: "1fr 140px 130px 120px", gap: 12, padding: "14px 18px", borderBottom: "1px solid #f4f3ee", cursor: "pointer", alignItems: "center" }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ fontFamily: "'Space Mono',monospace", fontSize: 11.5, color: "#a8aca6" }}>{t.id}</span>
                      <span style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.subject}</span>
                    </div>
                    <div style={{ display: "flex", gap: 6, marginTop: 5 }}>{t.tags.map((tg) => <span key={tg} style={{ fontSize: 10.5, color: "#6b706a", background: "#f0efe9", borderRadius: 4, padding: "2px 7px" }}>{tg}</span>)}</div>
                  </div>
                  <div>{chan(t.channel)}</div>
                  <div style={{ fontSize: 12.5, color: "#8a8e88" }}>{t.updated}</div>
                  <div><StatusPill s={t.status} /></div>
                </div>
              ))}
            </div>
          </React.Fragment>
        ) : (
          /* NEW REQUEST — form + live suggestions */
          <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 22, alignItems: "start" }}>
            <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 22 }}>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>Submit a request</div>
              <p style={{ margin: "0 0 18px", fontSize: 12.5, color: "#8a8e88", lineHeight: 1.5 }}>Tell us what's happening. We'll suggest help articles instantly — and route it to {KB.mls} support if you still need a hand.</p>

              <label style={lbl}>Topic</label>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginBottom: 16 }}>
                {[["listings", "Listings"], ["cma", "CMA & Pricing"], ["showings", "Showings"], ["marketing", "Marketing"], ["search", "Find homes"], ["rules", "Rules & regs"], ["data", "Data & tools"]].map(([v, label]) => (
                  <button key={v} onClick={() => setTopic(v)} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, border: "1px solid", borderColor: topic === v ? "#006747" : "#e2e0d8", background: topic === v ? "#eef4f1" : "#fff", color: topic === v ? "#006747" : "#6b706a", borderRadius: 999, padding: "7px 13px", cursor: "pointer" }}>{label}</button>
                ))}
              </div>

              <label style={lbl}>Subject</label>
              <input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Briefly, what do you need help with?" style={inp} />

              <label style={{ ...lbl, marginTop: 16 }}>Details</label>
              <textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Describe what happened, the listing or screen involved, and what you expected…" rows={6} style={{ ...inp, resize: "vertical", lineHeight: 1.5 }} />

              <label style={{ ...lbl, marginTop: 16 }}>Connect a record <span style={{ color: "#a8aca6", fontWeight: 500, textTransform: "none", letterSpacing: 0 }}>(optional)</span></label>
              <p style={{ margin: "0 0 9px", fontSize: 11.5, color: "#a8aca6", lineHeight: 1.45 }}>Link the listing, showing, or offer you're having trouble with so support sees it instantly.</p>
              <div style={{ display: "flex", gap: 7, marginBottom: 10 }}>
                {[["listing", "Listing", "home"], ["showing", "Showing", "calendar-clock"], ["offer", "Offer", "file-signature"]].map(([v, label, ic]) => (
                  <button key={v} onClick={() => { setLinkType(v); setLinked(null); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, border: "1px solid", borderColor: linkType === v ? "#006747" : "#e2e0d8", background: linkType === v ? "#eef4f1" : "#fff", color: linkType === v ? "#006747" : "#6b706a", borderRadius: 999, padding: "6px 12px", cursor: "pointer" }}><Icon name={ic} size={13} color={linkType === v ? "#006747" : "#8a8e88"} /> {label}</button>
                ))}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                {linkOptions[linkType].map((o) => {
                  const on = linked && linked.id === o.id;
                  return (
                    <div key={o.id} onClick={() => setLinked(on ? null : o)} style={{ display: "flex", alignItems: "center", gap: 10, border: "1px solid", borderColor: on ? "#9fcab5" : "#e7e5df", background: on ? "#eef4f1" : "#fff", borderRadius: 8, padding: "9px 11px", cursor: "pointer" }}>
                      <span style={{ width: 30, height: 30, borderRadius: 6, background: on ? "#dcebe3" : "#f0efe9", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={o.icon} size={15} color="#006747" /></span>
                      <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f" }}>{o.label}</div><div style={{ fontSize: 11, color: "#a8aca6" }}>{o.sub}</div></div>
                      <span style={{ width: 18, height: 18, borderRadius: "50%", border: on ? "none" : "1.5px solid #cdcdc4", background: on ? "#006747" : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>{on && <Icon name="check" size={12} color="#fff" />}</span>
                    </div>
                  );
                })}
              </div>

              <label style={{ ...lbl, marginTop: 16 }}>Attach (optional)</label>
              <div style={{ border: "1.5px dashed #d9d7cd", borderRadius: 8, padding: "16px", display: "flex", alignItems: "center", gap: 10, color: "#8a8e88", fontSize: 12.5 }}>
                <Icon name="paperclip" size={16} color="#a8aca6" /> Drop a screenshot or file, or click to browse
              </div>

              <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 20 }}>
                <button style={btnPrimaryS}><Icon name="send" size={15} color="#fff" /> Submit request</button>
                <span style={{ fontSize: 11.5, color: "#a8aca6" }}>Typical first reply: under 2 business hours</span>
              </div>
            </div>

            {/* live suggestions */}
            <div style={{ position: "sticky", top: 0 }}>
              <div style={{ background: "#eef4f1", border: "1px solid #d6e7de", borderRadius: 10, padding: 16 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                  <Icon name="sparkles" size={16} color="#006747" />
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: "#006747" }}>Suggested for you</span>
                </div>
                <p style={{ margin: "0 0 12px", fontSize: 11.5, color: "#4a6157", lineHeight: 1.45 }}>{suggestions.length ? "These might solve it before you even submit." : "Pick a topic or start typing — we'll surface help instantly."}</p>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {suggestions.map((a) => <SuggestCard key={a.id} a={a} />)}
                </div>
                {suggestions.length > 0 && (
                  <button onClick={() => go && go("knowledge")} style={{ width: "100%", marginTop: 12, fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "#006747", background: "#fff", border: "1px solid #cfe0d6", borderRadius: 7, padding: "9px", cursor: "pointer" }}>Browse all knowledgebase ›</button>
                )}
              </div>
            </div>
          </div>
        )}
      </div>

      {open && open.ticket && <TicketViewer ticket={open.ticket} onClose={() => setOpen(null)} />}
      {open && open.id && <KBViewer a={open} onClose={() => setOpen(null)} go={go} />}
    </div>
  );
}

// Realtor's read view of one of their tickets
function TicketViewer({ ticket, onClose }) {
  const KB = window.RC_KB;
  return (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(20,28,22,.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 40, padding: 30 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 620, maxHeight: "100%", background: "#fff", borderRadius: 4, boxShadow: "0 18px 60px rgba(0,0,0,.3)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid #ececec" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontFamily: "'Space Mono',monospace", fontSize: 12, color: "#a8aca6" }}>{ticket.id}</span>
            <Pill tone={KB.ticketStatus[ticket.status].tone}>{KB.ticketStatus[ticket.status].label}</Pill>
            <div style={{ flex: 1 }} />
            <button onClick={onClose} style={{ border: 0, background: "none", cursor: "pointer", display: "flex" }}><Icon name="x" size={20} color="#8a8e88" /></button>
          </div>
          <div style={{ fontSize: 16, fontWeight: 600, marginTop: 8 }}>{ticket.subject}</div>
          {ticket.linked && (
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 10, background: "#f6f5f1", border: "1px solid #e7e5df", borderRadius: 8, padding: "8px 11px" }}>
              <span style={{ width: 26, height: 26, borderRadius: 6, background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={ticket.linked.icon} size={13} color="#006747" /></span>
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12, fontWeight: 600, color: "#1d241f" }}>{ticket.linked.label}</div><div style={{ fontSize: 10.5, color: "#a8aca6" }}>{ticket.linked.sub}</div></div>
            </div>
          )}
        </div>
        <div style={{ overflowY: "auto", padding: "18px 20px", display: "flex", flexDirection: "column", gap: 14 }}>
          {ticket.thread.map((m, i) => (
            <div key={i} style={{ display: "flex", gap: 11, flexDirection: m.from === "staff" ? "row-reverse" : "row" }}>
              <span style={{ width: 32, height: 32, borderRadius: "50%", flex: "none", background: m.from === "staff" ? "#006747" : "#e7e1d4", color: m.from === "staff" ? "#fff" : "#006747", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 12 }}>{m.from === "staff" ? "MS" : ticket.initials}</span>
              <div style={{ maxWidth: "78%" }}>
                <div style={{ fontSize: 13, color: "#1d241f", background: m.from === "staff" ? "#eef4f1" : "#f6f5f1", borderRadius: 10, padding: "11px 13px", lineHeight: 1.5, whiteSpace: "pre-wrap" }}>{m.body}</div>
                <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 4, textAlign: m.from === "staff" ? "right" : "left" }}>{m.from === "staff" ? "MLS support" : "You"} · {m.at}</div>
              </div>
            </div>
          ))}
        </div>
        {ticket.status !== "solved" && (
          <div style={{ borderTop: "1px solid #ececec", padding: "12px 16px", display: "flex", gap: 10, alignItems: "center" }}>
            <input placeholder="Add a reply…" style={{ flex: 1, border: "1px solid #e2e0d8", borderRadius: 8, padding: "10px 12px", fontFamily: "inherit", fontSize: 13, outline: 0 }} />
            <button style={btnPrimaryS}><Icon name="send" size={15} color="#fff" /> Send</button>
          </div>
        )}
      </div>
    </div>
  );
}

const lbl = { display: "block", fontSize: 10.5, fontWeight: 600, letterSpacing: ".5px", textTransform: "uppercase", color: "#a8aca6", marginBottom: 7 };
const inp = { width: "100%", boxSizing: "border-box", border: "1px solid #e2e0d8", borderRadius: 8, padding: "10px 12px", fontFamily: "inherit", fontSize: 13.5, color: "#1d241f", outline: 0 };
const btnPrimaryS = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#fff", background: "#006747", border: 0, borderRadius: 8, padding: "10px 16px", cursor: "pointer" };
const btnGhostS = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "#fff", border: "1px solid #d7ddd9", borderRadius: 8, padding: "9px 14px", cursor: "pointer" };

window.Support = Support;
