/* Stratum Leads — Operations Console. Inbox: ticket queue + ticket detail.
   Single purpose: triage and work support tickets. Customer context here is
   a compact summary strip only — the full account (wallet ledger, lead
   access, activity) lives on its own page, opened via "Open account". */

/* Design-system components — each Babel script has its own scope, so every
   ops-*.jsx file must destructure what it needs from the namespace. */
const { NavItem, IconButton, WalletPill, Tabs, LeadCard, Button, Field, Card, Metric, StatusChip, TierBadge, ContactQuality, ProgressBar, StrataAmount, Checkbox, Switch, Avatar, AvatarStack, SegmentedControl, GateCard, EmptyState, Toast } = window.StratumLeadsDesignSystem_6367ed;

const { I, fmtStrata, getCustomer, TICKET_STATUS_TONE, PRIORITY_TONE, HEALTH_TONE, HEALTH_LABEL, CATEGORY_LABEL, Spinner, IconReply, IconNotePen, IconCheckCircle, IconRotateCcw } = window.OpsShared;

const STATUS_TABS = ["All", "New", "Open", "Pending", "Escalated", "Closed"];
const CATEGORY_OPTIONS = ["billing", "wallet", "auction", "lead_access", "account", "technical"];

/* ---- Ticket queue row ---- */
function TicketRow({ t, active, onClick }) {
  const cust = getCustomer(t.customerId);
  return (
    <button onClick={onClick} style={{ display: "grid", gridTemplateColumns: "1fr auto", alignItems: "start", gap: 8, width: "100%", textAlign: "left", padding: "12px 14px", border: "none", borderBottom: "1px solid var(--border-subtle)", borderLeft: active ? "3px solid var(--accent)" : "3px solid transparent", background: active ? "var(--accent-soft)" : "var(--surface)", cursor: "pointer" }}>
      <span style={{ minWidth: 0 }}>
        <strong style={{ display: "block", fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.subject}</strong>
        <span style={{ display: "block", fontSize: 12, color: "var(--text-muted)", margin: "2px 0 6px" }}>{t.id} · {cust?.name}</span>
        <span style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          <StatusChip tone={PRIORITY_TONE[t.priority]}>{t.priority}</StatusChip>
          <StatusChip tone="neutral">{CATEGORY_LABEL[t.category]}</StatusChip>
        </span>
      </span>
      <span style={{ display: "grid", justifyItems: "end", gap: 6 }}>
        <StatusChip tone={TICKET_STATUS_TONE[t.status]}>{t.status}</StatusChip>
        <SlaBadge minutes={t.slaMinutesLeft} />
      </span>
    </button>);

}

/* ---- Compact customer context (summary only — full 360 lives on Customers page) ---- */
function TicketCustomerStrip({ customer, onOpenCustomer }) {
  if (!customer) return null;
  return (
    <button onClick={() => onOpenCustomer(customer.id)} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto auto", alignItems: "center", gap: 14, width: "100%", textAlign: "left", padding: "12px 14px", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface-subtle)", cursor: "pointer" }}>
      <Avatar name={customer.name} initials={customer.initials} size={34} style={{ fontWeight: 800, fontSize: 12 }} />
      <span style={{ minWidth: 0 }}>
        <strong style={{ display: "block", fontSize: 13.5 }}>{customer.name}</strong>
        <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{customer.id} · {customer.plan.name}</span>
      </span>
      <span style={{ fontSize: 12, color: "var(--text-muted)" }}><StrataAmount amount={customer.wallet.available} size="sm" /></span>
      <StatusChip tone={HEALTH_TONE[customer.health]}>{HEALTH_LABEL[customer.health]}</StatusChip>
      <span style={{ fontSize: 12, fontWeight: 700, color: "var(--accent)", display: "flex", alignItems: "center", gap: 4 }}>Open account{I("arrow-right", { width: 13 })}</span>
    </button>);

}

/* ---- Message bubble ---- */
function MessageBubble({ m }) {
  const mine = m.type === "agent";
  const internal = !!m.internal;
  return (
    <div style={{ display: "flex", justifyContent: mine ? "flex-end" : "flex-start" }}>
      <div style={{ maxWidth: "78%", padding: "10px 14px", borderRadius: "var(--radius-md)", background: internal ? "var(--warning-soft)" : mine ? "var(--accent-soft)" : "var(--surface-sunken)", border: internal ? "1px solid var(--accent-soft-border)" : "1px solid transparent" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
          <strong style={{ fontSize: 12 }}>{m.author}</strong>
          {internal && <StatusChip tone="warning">Internal note</StatusChip>}
          <span style={{ fontSize: 11, color: "var(--text-muted)" }}>{m.time}</span>
        </div>
        <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.5 }}>{m.body}</p>
      </div>
    </div>);

}

/* ---- Ticket detail ---- */
function TicketDetail({ ticket, cannedResponses, onReply, onSetStatus, onOpenAdjustWallet, onOpenCustomer, onResetPassword }) {
  const [mode, setMode] = React.useState("reply");
  const [body, setBody] = React.useState("");
  const [cannedId, setCannedId] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const threadRef = React.useRef(null);
  React.useEffect(refresh, [ticket?.id, ticket?.messages?.length]);
  React.useEffect(() => setSending(false), [ticket?.id]);
  React.useEffect(() => {
    if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight;
  }, [ticket?.messages?.length, ticket?.id]);

  if (!ticket) {
    return <Card style={{ height: "100%" }}><EmptyState icon="inbox" title="Select a ticket" message="Choose a ticket from the queue to view the conversation." /></Card>;
  }
  const customer = getCustomer(ticket.customerId);
  const relevantCanned = cannedResponses.filter((c) => c.category === ticket.category);

  const send = () => {
    if (!body.trim() || sending) return;
    setSending(true);
    setTimeout(() => {
      onReply(ticket.id, { body: body.trim(), internal: mode === "note" });
      setBody("");setCannedId("");setSending(false);
    }, 650);
  };
  const insertCanned = (id) => {
    setCannedId(id);
    const c = cannedResponses.find((c) => c.id === id);
    if (c) setBody(c.body);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)", overflow: "hidden" }}>
      <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <span style={{ fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{ticket.id}</span>
          <h2 style={{ margin: "2px 0 0", fontSize: 17, fontWeight: 800 }}>{ticket.subject}</h2>
        </div>
        <div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
          <StatusChip tone={PRIORITY_TONE[ticket.priority]}>{ticket.priority}</StatusChip>
          <StatusChip tone={TICKET_STATUS_TONE[ticket.status]}>{ticket.status}</StatusChip>
        </div>
      </div>

      <div style={{ padding: "14px 18px", display: "grid", gap: 12, borderBottom: "1px solid var(--border)" }}>
        <TicketCustomerStrip customer={customer} onOpenCustomer={onOpenCustomer} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Button size="sm" variant="secondary" icon={I("wallet", { width: 14 })} onClick={() => onOpenAdjustWallet({ customerId: ticket.customerId, ticketId: ticket.id })}>Adjust Wallet</Button>
          <Button size="sm" variant="secondary" icon={I("mail", { width: 14 })} onClick={() => onResetPassword(ticket.customerId)}>Send Password Reset</Button>
          {ticket.status !== "Closed" ?
          <Button size="sm" variant="secondary" icon={<IconCheckCircle size={14} />} onClick={() => onSetStatus(ticket.id, "Closed")}>Mark Resolved</Button> :

          <Button size="sm" variant="secondary" icon={<IconRotateCcw size={14} />} onClick={() => onSetStatus(ticket.id, "Open")}>Reopen</Button>
          }
          {ticket.status !== "Escalated" && ticket.status !== "Closed" &&
          <Button size="sm" variant="secondary" icon={I("arrow-up-circle", { width: 14 })} onClick={() => onSetStatus(ticket.id, "Escalated")}>Escalate</Button>
          }
        </div>
      </div>

      <div ref={threadRef} style={{ flex: 1, overflowY: "auto", padding: 18, display: "grid", gap: 12, alignContent: "start" }}>
        {ticket.messages.map((m, i) => <MessageBubble key={i} m={m} />)}
      </div>

      <div style={{ borderTop: "1px solid var(--border)", padding: 16, display: "grid", gap: 10, background: "var(--surface-subtle)" }}>
        <SegmentedControl variant="pill" size="sm" value={mode} onChange={setMode} options={[{ value: "reply", label: "Reply" }, { value: "note", label: "Internal Note" }]} style={{ width: "fit-content" }} />
        {mode === "reply" && relevantCanned.length > 0 &&
        <Field as="select" value={cannedId} onChange={(e) => insertCanned(e.target.value)}>
            <option value="">Insert a canned response...</option>
            {relevantCanned.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </Field>
        }
        <Field as="textarea" rows={3} placeholder={mode === "note" ? "Add an internal note (not visible to the customer)..." : "Type a reply..."} value={body} onChange={(e) => setBody(e.target.value)} />
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <Button variant="primary" disabled={sending || !body.trim()} icon={sending ? <Spinner size={14} /> : mode === "note" ? <IconNotePen size={15} /> : <IconReply size={15} />} onClick={send}>{sending ? "Sending…" : mode === "note" ? "Add Note" : "Send Reply"}</Button>
        </div>
      </div>
    </div>);

}

/* ---- New ticket drawer ---- */
function NewTicketDrawer({ customers, onClose, onCreate }) {
  const [customerId, setCustomerId] = React.useState(customers[0]?.id || "");
  const [category, setCategory] = React.useState("account");
  const [priority, setPriority] = React.useState("Medium");
  const [subject, setSubject] = React.useState("");
  const [msg, setMsg] = React.useState("");

  return (
    <SideDrawer title="New Ticket" subtitle="Draft a ticket on behalf of a customer." icon={I("ticket-plus")} onClose={onClose} footer={
    <React.Fragment>
        <Button variant="secondary" onClick={onClose}>Cancel</Button>
        <Button variant="primary" icon={I("ticket-plus", { width: 15 })} disabled={!subject.trim() || !msg.trim()} onClick={() => onCreate({ customerId, category, priority, subject: subject.trim(), body: msg.trim() })}>Create Ticket</Button>
      </React.Fragment>
    }>
      <Field label="Customer" as="select" value={customerId} onChange={(e) => setCustomerId(e.target.value)}>
        {customers.map((c) => <option key={c.id} value={c.id}>{c.name} · {c.id}</option>)}
      </Field>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Field label="Category" as="select" value={category} onChange={(e) => setCategory(e.target.value)}>
          {CATEGORY_OPTIONS.map((c) => <option key={c} value={c}>{CATEGORY_LABEL[c]}</option>)}
        </Field>
        <Field label="Priority" as="select" value={priority} onChange={(e) => setPriority(e.target.value)}>
          {["Low", "Medium", "High", "Urgent"].map((p) => <option key={p} value={p}>{p}</option>)}
        </Field>
      </div>
      <Field label="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Short summary of the issue" />
      <Field label="First message" as="textarea" rows={4} value={msg} onChange={(e) => setMsg(e.target.value)} placeholder="Describe the issue on the customer's behalf..." />
    </SideDrawer>);

}

/* ---- Page shell: filterable queue + detail ---- */
function TicketsPage({ tickets, customers, cannedResponses, selectedTicketId, onSelectTicket, onReply, onSetStatus, onOpenAdjustWallet, onOpenCustomer, onResetPassword }) {
  const [status, setStatus] = React.useState("All");
  const [query, setQuery] = React.useState("");
  React.useEffect(refresh);

  const filtered = tickets.filter((t) => {
    if (status !== "All" && t.status !== status) return false;
    if (query.trim() === "") return true;
    const q = query.trim().toLowerCase();
    const cust = getCustomer(t.customerId);
    return t.subject.toLowerCase().includes(q) || t.id.toLowerCase().includes(q) || (cust && cust.name.toLowerCase().includes(q));
  });
  const selected = tickets.find((t) => t.id === selectedTicketId) || null;
  const countFor = (s) => s === "All" ? tickets.length : tickets.filter((t) => t.status === s).length;

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)", height: "calc(100vh - 4px)", display: "flex", flexDirection: "column" }}>
      <PageHeader eyebrow="Customer Operations" title="Inbox" description="Triage and work support tickets. Adjust wallet, escalate, or reply — every action is logged." />

      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <SegmentedControl variant="pill" size="sm" value={status} onChange={setStatus} options={STATUS_TABS.map((s) => ({ value: s, label: s, count: countFor(s) }))} style={{ flexWrap: "wrap" }} />
        <div style={{ width: 240 }}><Field icon={I("search")} placeholder="Search tickets..." value={query} onChange={(e) => setQuery(e.target.value)} /></div>
      </div>

      <div style={{ flex: 1, minHeight: 0, display: "grid", gridTemplateColumns: "380px 1fr", gap: 18 }}>
        <div style={{ overflowY: "auto", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", background: "var(--surface)" }}>
          {filtered.length === 0 ?
          <EmptyState icon="inbox" title="No tickets" message="No tickets match this filter." /> :

          filtered.map((t) => <TicketRow key={t.id} t={t} active={t.id === selectedTicketId} onClick={() => onSelectTicket(t.id)} />)
          }
        </div>
        <TicketDetail ticket={selected} cannedResponses={cannedResponses} onReply={onReply} onSetStatus={onSetStatus} onOpenAdjustWallet={onOpenAdjustWallet} onOpenCustomer={onOpenCustomer} onResetPassword={onResetPassword} />
      </div>

    </div>);

}

Object.assign(window, { OpsTickets: { TicketsPage, NewTicketDrawer } });
