/* ============================================================
   Reframe Work Orders — Ticket detail modal (shared)
   role: "admin" | "employee" | "customer"
   ============================================================ */
function TicketModal({ openId, onClose, state, actions, role = "admin", currentEmployeeId = null }) {
  const [note, setNote] = useState("");
  const [assignOpen, setAssignOpen] = useState(false);
  const [lightbox, setLightbox] = useState(null);
  const mobile = useIsMobile();
  const ticket = state.tickets.find((t) => t.id === openId) || null;

  useEffect(() => { setNote(""); setAssignOpen(false); }, [openId]);
  if (!ticket) return null;

  const ids = ticket.assigneeIds || [];
  const techs = ids.map((id) => WOData.employee(state, id)).filter(Boolean);
  const canEditStatus = role === "admin" || (role === "employee" && ids.includes(currentEmployeeId));
  const canAssign = role === "admin";

  function addNote() {
    if (!note.trim()) return;
    // The server stamps the note with the signed-in user's name.
    actions.addNote(ticket.id, note.trim());
    setNote("");
  }

  return (
    <Modal open={!!openId} onClose={onClose} width={840}>
      <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 320px", minHeight: mobile ? 0 : 480, position: "relative" }}>
        <button onClick={onClose} style={{ position: "absolute", top: 14, right: 14, zIndex: 5, width: 34, height: 34, borderRadius: 8, border: "1px solid #E6E6E6", background: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}
          onMouseEnter={(e) => e.currentTarget.style.background = "#F2F2F2"} onMouseLeave={(e) => e.currentTarget.style.background = "#fff"}><Icon name="x" size={16} color="#515151" /></button>
        {/* Left: detail */}
        <div style={{ padding: mobile ? "22px 18px" : "26px 28px", paddingRight: mobile ? 56 : 28, borderRight: mobile ? "none" : "1px solid #F2F2F2", borderBottom: mobile ? "1px solid #F2F2F2" : "none", maxHeight: mobile ? "none" : "78vh", overflowY: "auto" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "#9AA3A5" }}>{ticket.id}</span>
            <PriorityChip priority={ticket.priority} compact />
            <CategoryTag category={ticket.category} />
          </div>
          <h2 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 25, lineHeight: 1.15, letterSpacing: "-0.025em", color: "#16331E", textWrap: "pretty" }}>{ticket.title}</h2>

          <div style={{ marginTop: 20, padding: 16, background: "#FAFBFB", border: "1px solid #F2F2F2", borderRadius: 12 }}>
            <SectionLabel icon="map-pin">Location & contact</SectionLabel>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 18px", marginTop: 10 }}>
              <Detail label="Camp area" value={ticket.customer.property} />
              <Detail label="Site" value={ticket.customer.unit || "—"} />
              <Detail label="Contact" value={ticket.customer.name + (ticket.customer.role ? " · " + ticket.customer.role : "")} />
              <Detail label="Troop / Pack" value={ticket.customer.troop || "—"} />
              <Detail label="Phone" value={ticket.customer.phone || "—"} />
              <div style={{ gridColumn: "1 / -1" }}><Detail label="Email" value={ticket.customer.email} /></div>
            </div>
          </div>

          <div style={{ marginTop: 22 }}>
            <SectionLabel icon="list-checks">Description</SectionLabel>
            <p style={{ margin: "10px 0 0", fontSize: 14.5, lineHeight: 1.6, color: "#2a3a3d" }}>{ticket.description}</p>
          </div>

          {ticket.photos.length > 0 && (
            <div style={{ marginTop: 22 }}>
              <SectionLabel icon="image">Photos · {ticket.photos.length}</SectionLabel>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 10 }}>
                {ticket.photos.map((p, i) => <PhotoThumb key={i} photo={p} size={84} onClick={() => p.kind === "img" && setLightbox(p)} />)}
              </div>
            </div>
          )}

          <div style={{ marginTop: 24 }}>
            <SectionLabel icon="clock">Activity</SectionLabel>
            <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 0 }}>
              {ticket.activity.slice().reverse().map((a, i, arr) => (
                <div key={i} style={{ display: "flex", gap: 12 }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                    <span style={{ width: 9, height: 9, borderRadius: "50%", background: i === 0 ? "#2F6B3A" : "#C5CDCF", marginTop: 4, flexShrink: 0 }}></span>
                    {i < arr.length - 1 && <span style={{ width: 1.5, flex: 1, background: "#E6E6E6", minHeight: 14 }}></span>}
                  </div>
                  <div style={{ paddingBottom: 14 }}>
                    <div style={{ fontSize: 13.5, color: "#16331E", lineHeight: 1.4 }}>{a.text}</div>
                    <div style={{ fontSize: 11.5, color: "#9AA3A5", marginTop: 1 }}>{fmtDate(a.ts)}</div>
                  </div>
                </div>
              ))}
            </div>
            {canEditStatus && (
              <div style={{ display: "flex", gap: 8, marginTop: 6 }}>
                <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="Add an update…" onKeyDown={(e) => e.key === "Enter" && addNote()}
                  style={{ flex: 1, height: 42, padding: "0 12px", borderRadius: 8, border: "1px solid #E6E6E6", fontSize: 14, fontFamily: "var(--font-sans)", color: "#16331E", outline: "none" }}
                  onFocus={(e) => e.target.style.borderColor = "#2F6B3A"} onBlur={(e) => e.target.style.borderColor = "#E6E6E6"} />
                <Button kind="subtle" size="sm" icon="send" onClick={addNote} style={{ height: 42 }}>Post</Button>
              </div>
            )}
          </div>
        </div>

        {/* Right: controls */}
        <div style={{ padding: mobile ? "20px 18px" : "26px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
          <div style={{ marginTop: mobile ? 0 : 24 }}>
            <SectionLabel>Status</SectionLabel>
            <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 10 }}>
              {WOData.STATUSES.map((s) => {
                const active = ticket.status === s.id;
                const c = STATUS_COLORS[s.id];
                const disabled = !canEditStatus;
                return (
                  <button key={s.id} disabled={disabled} onClick={() => actions.moveTicket(ticket.id, s.id)} style={{
                    display: "flex", alignItems: "center", gap: 9, padding: "10px 12px", borderRadius: 9, cursor: disabled ? "default" : "pointer", textAlign: "left",
                    border: "1px solid " + (active ? c.dot : "#E6E6E6"), background: active ? c.bg : "#fff", opacity: disabled && !active ? 0.55 : 1,
                    transition: "all 120ms",
                  }}>
                    <span style={{ width: 9, height: 9, borderRadius: "50%", background: c.dot }}></span>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: active ? c.fg : "#16331E", flex: 1 }}>{s.label}</span>
                    {active && <Icon name="check" size={15} color={c.fg} />}
                  </button>
                );
              })}
            </div>
          </div>

          <div style={{ position: "relative" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <SectionLabel>Assigned to{techs.length > 1 ? " · " + techs.length : ""}</SectionLabel>
              {canAssign && techs.length > 0 && <button onClick={() => setAssignOpen((o) => !o)} style={{ border: "none", background: "transparent", cursor: "pointer", color: "#2F6B3A", fontSize: 12.5, fontWeight: 600 }}>Edit</button>}
            </div>
            <div style={{ marginTop: 10 }}>
              {techs.length > 0 ? (
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {techs.map((tech) => (
                    <div key={tech.id} style={{ display: "flex", alignItems: "center", gap: 11, padding: 10, borderRadius: 10, border: "1px solid #E6E6E6", background: "#FAFBFB" }}>
                      <Avatar name={tech.name} color={tech.color} size={34} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 600, color: "#16331E" }}>{tech.name}</div>
                        <div style={{ fontSize: 12, color: "#515151" }}>{tech.trade}</div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                canAssign ? (
                  <button onClick={() => setAssignOpen((o) => !o)} style={{
                    width: "100%", display: "flex", alignItems: "center", justifyContent: "center", gap: 7, height: 46, borderRadius: 10,
                    border: "1px dashed #2F6B3A", background: "#E5F0E7", color: "#245730", cursor: "pointer", fontSize: 14, fontWeight: 600, fontFamily: "var(--font-display)",
                  }}><Icon name="plus" size={16} color="#245730" />Assign crew member</button>
                ) : <div style={{ fontSize: 13.5, color: "#9AA3A5", padding: "10px 0" }}>Not yet assigned.</div>
              )}
            </div>
            {assignOpen && <AssignPopover state={state} selected={ids} align="left" onClose={() => setAssignOpen(false)} onChange={(next) => actions.assign(ticket.id, next)} />}
          </div>

          {canAssign && (
            <div>
              <SectionLabel>Priority</SectionLabel>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginTop: 10 }}>
                {WOData.PRIORITIES.map((p) => {
                  const active = ticket.priority === p.id;
                  return (
                    <button key={p.id} onClick={() => actions.setPriority(ticket.id, p.id)} style={{
                      padding: "9px 10px", borderRadius: 8, cursor: "pointer", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 12.5,
                      border: "1px solid " + (active ? p.color : "#E6E6E6"), background: active ? p.color + "1A" : "#fff", color: active ? p.color : "#515151",
                    }}>{p.label}</button>
                  );
                })}
              </div>
            </div>
          )}

          <div style={{ marginTop: "auto", fontSize: 11.5, color: "#9AA3A5", lineHeight: 1.5 }}>
            Submitted {fmtDate(ticket.createdAt)}<br />Last updated {timeAgo(ticket.updatedAt)}
          </div>
        </div>
      </div>

      {lightbox && (
        <div onClick={() => setLightbox(null)} style={{ position: "fixed", inset: 0, background: "rgba(0,32,38,0.8)", zIndex: 200, display: "flex", alignItems: "center", justifyContent: "center", padding: 40 }}>
          <img src={lightbox.url} alt="" style={{ maxWidth: "90%", maxHeight: "90%", borderRadius: 12, boxShadow: "var(--shadow-lg)" }} />
        </div>
      )}
    </Modal>
  );
}

function SectionLabel({ icon, children }) {
  return <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: "#9AA3A5" }}>
    {icon && <Icon name={icon} size={13} color="#9AA3A5" />}{children}
  </div>;
}
function Detail({ label, value }) {
  return <div><div style={{ fontSize: 11.5, color: "#9AA3A5", marginBottom: 2 }}>{label}</div><div style={{ fontSize: 14, color: "#16331E", fontWeight: 500 }}>{value}</div></div>;
}

Object.assign(window, { TicketModal, SectionLabel, Detail });
