// The one ticket row used everywhere. Collapsed it's a summary line; clicking
// expands a normalized detail panel — status timeline + the same field grid for
// every ticket, whatever its origin (local, freshly filed, or read from Jira).
//
// `mode`: "customer" (plain-language severity, no reporter/account) or
// "admin" (SEV codes, account + reporter, Jira link). The STRUCTURE is
// identical in both — only the vocabulary and the extra admin columns differ.
const { useState: useStateTC } = React;

function fmtAgo(ts) {
  if (!ts) return "";
  const s = Math.floor((Date.now() - ts) / 1000);
  if (s < 60) return "just now";
  if (s < 3600) return Math.floor(s / 60) + "m ago";
  if (s < 86400) return Math.floor(s / 3600) + "h ago";
  return Math.floor(s / 86400) + "d ago";
}
function fmtWhen(ts) {
  if (!ts) return "—";
  try {
    return new Date(ts).toLocaleString(undefined, {
      month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
    });
  } catch (e) { return "—"; }
}

// Every ticket shows the same rows; missing values render as "Not provided"
// rather than disappearing, so the structure never shifts between tickets.
const DETAIL_ROWS = [
  { key: "reproSteps", label: "What led to it" },
  { key: "expected", label: "Expected" },
  { key: "actual", label: "What happened" },
  { key: "environment", label: "Environment" },
  { key: "errorText", label: "Error / console" },
  { key: "blastRadius", label: "Who's affected" },
];

function StatusTimeline({ ticket }) {
  const events = window.NS.buildHistory(ticket);
  return (
    <ol className="tl">
      {events.map((e) => (
        <li key={e.key} className={"tl-item" + (e.done ? " is-done" : " is-pending")}>
          <span className="tl-dot" aria-hidden="true" />
          <div className="tl-body">
            <div className="tl-head">
              <span className="tl-label">{e.label}</span>
              <span className="tl-when">{e.at ? fmtWhen(e.at) : "pending"}</span>
            </div>
            <div className="tl-detail">{e.detail}</div>
          </div>
        </li>
      ))}
    </ol>
  );
}

function TicketCard({ ticket, mode }) {
  const [open, setOpen] = useStateTC(false);
  const t = window.NS.normalizeTicket(ticket);
  const s = window.NS.sev(t.severity);
  const fs = window.NS.friendlyStatus(t.statusCategory, t.status);
  const admin = mode === "admin";

  return (
    <div className={"ticket-card" + (open ? " is-open" : "")}>
      <button
        type="button"
        className="ticket-row ticket-row-btn"
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
      >
        <span className={"sev-chip sev-" + s.rank} title={s.rubric}>
          <span className="sev-dot" />{admin ? s.code : s.label}
        </span>
        <span className="ticket-main">
          <span className="ticket-title">{t.title}</span>
          <span className="ticket-meta">
            <span className="ticket-key">{t.key}</span>
            {admin && t.account && <span>· {t.account}</span>}
            {admin && t.reporter && <span>· {t.reporter}</span>}
            {t.component && <span>· {t.component}</span>}
            <span>· updated {fmtAgo(t.updatedAt)}</span>
            {!t.live && <span title="Simulated — no Jira credentials set">· demo</span>}
            {t.kbVerdict && t.kbVerdict !== "new-bug" && t.kbVerdict !== "unclear" && (
              <span className="kb-badge" title={t.kbCitation || ""}>📖 {window.NS.kbVerdictLabel(t.kbVerdict)}</span>
            )}
          </span>
        </span>
        <span className="ticket-right">
          <span className={"status-pill " + fs.cls}><span className="sev-dot" />{fs.label}</span>
          <span className="ticket-eta">
            {fs.key !== "resolved" ? `next update ${window.NS.nextUpdateLabel(t.severity)}` : fs.blurb}
          </span>
        </span>
        <span className={"ticket-chev" + (open ? " is-open" : "")} aria-hidden="true">⌄</span>
      </button>

      {open && (
        <div className="ticket-detail">
          <div className="ticket-detail-grid">
            <section className="td-col">
              <div className="eyebrow td-h">Status &amp; history</div>
              <StatusTimeline ticket={t} />
            </section>

            <section className="td-col">
              <div className="eyebrow td-h">Details</div>
              <dl className="td-dl">
                {DETAIL_ROWS.map((r) => (
                  <div className="td-row" key={r.key}>
                    <dt>{r.label}</dt>
                    <dd className={t[r.key] ? "" : "is-empty"}>{t[r.key] || "Not provided"}</dd>
                  </div>
                ))}
                <div className="td-row">
                  <dt>Impact</dt>
                  <dd>
                    {admin ? `${s.code} · ${s.label} · Jira ${s.jiraPriority}` : `${s.label} impact`}
                    {t.severityRationale ? ` — ${t.severityRationale}` : ""}
                  </dd>
                </div>
                {t.kbCitation && (
                  <div className="td-row">
                    <dt>Knowledge base</dt>
                    <dd>{window.NS.kbVerdictLabel(t.kbVerdict)} — {t.kbCitation}</dd>
                  </div>
                )}
              </dl>

              <div className="td-actions">
                {t.url
                  ? <a className="btn btn-ghost btn-sm" href={t.url} target="_blank" rel="noreferrer">View in Jira ↗</a>
                  : <span className="ticket-eta" title="No Jira credentials set">No Jira link (demo)</span>}
              </div>
            </section>
          </div>
        </div>
      )}
    </div>
  );
}

window.TicketCard = TicketCard;
window.fmtAgo = fmtAgo;
