// Shared table chrome for Backstage data pages.

function Th({ children, align, sortable, active, onClick, style }) {
  return (
    <th onClick={onClick} style={{
      textAlign: align || "left",
      padding: "14px 16px",
      fontFamily: "var(--font-body)",
      fontWeight: 600,
      fontSize: 10,
      letterSpacing: "0.16em",
      textTransform: "uppercase",
      color: active ? "var(--rdb-gold)" : "var(--ink-6)",
      cursor: sortable ? "pointer" : "default",
      userSelect: "none",
      whiteSpace: "nowrap",
      ...style,
    }}>
      {children}
      {sortable && active && <span style={{ marginLeft: 6, fontFamily: "var(--font-mono)" }}>↓</span>}
    </th>
  );
}

function Td({ children, align, style }) {
  return (
    <td style={{
      textAlign: align || "left",
      padding: "16px 16px",
      verticalAlign: "middle",
      fontFamily: "var(--font-body)",
      fontSize: 13,
      color: "var(--fg-1)",
      ...style,
    }}>{children}</td>
  );
}

// Page header: eyebrow + serif title + intro + right-aligned actions.
function PageHeader({ eyebrow, title, intro, actions, synced }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 24, marginBottom: 32 }}>
      <div style={{ minWidth: 0 }}>
        <div className="rdb-eyebrow" style={{ marginBottom: 14 }}>{eyebrow}</div>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 48, letterSpacing: "-0.02em", color: "var(--fg-1)", margin: 0, lineHeight: 1.02 }}>
          {title}
        </h1>
        <p style={{ fontFamily: "var(--font-body)", fontSize: 15, lineHeight: 1.55, color: "var(--fg-2)", margin: "14px 0 0", maxWidth: 560 }}>
          {intro}
        </p>
        {synced && (
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16 }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--success)", display: "inline-block" }} />
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-6)", letterSpacing: "0.02em" }}>{synced}</span>
          </div>
        )}
      </div>
      {actions && <div style={{ display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>{actions}</div>}
    </div>
  );
}

// Horizontal stat strip with hairline dividers.
function StatStrip({ stats }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${stats.length}, 1fr)`, gap: 0, marginBottom: 32, borderTop: "1px solid var(--ink-3)", borderBottom: "1px solid var(--ink-3)" }}>
      {stats.map((s, i) => (
        <div key={s.label} style={{ padding: "20px 24px", borderRight: i < stats.length - 1 ? "1px solid var(--ink-3)" : "none" }}>
          <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 10, letterSpacing: "0.32em", color: "var(--ink-6)", textTransform: "uppercase" }}>{s.label}</div>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 34, color: s.tone === "warning" ? "#E8A33D" : s.tone === "danger" ? "#C0392B" : "var(--fg-1)", marginTop: 8, letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>{s.value}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-6)", marginTop: 4 }}>{s.note}</div>
        </div>
      ))}
    </div>
  );
}

// Category chips + search + status select.
function FilterBar({ categories, selectedCat, onCat, search, onSearch, searchPlaceholder, statusFilter, onStatus, statusOptions }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
        {categories.map(c => (
          <span key={c} onClick={() => onCat(c)} style={{
            fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 10,
            letterSpacing: "0.16em", textTransform: "uppercase",
            padding: "7px 13px",
            border: c === selectedCat ? "1px solid var(--rdb-gold)" : "1px solid var(--ink-3)",
            background: c === selectedCat ? "var(--rdb-gold)" : "transparent",
            color: c === selectedCat ? "#0D0D0D" : "var(--fg-2)",
            cursor: "pointer", lineHeight: 1,
            transition: "all 160ms cubic-bezier(.22,1,.36,1)"
          }}>{c}</span>
        ))}
      </div>
      <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, borderBottom: "1px solid var(--ink-4)", paddingBottom: 6 }}>
          <Icon name="search" size={15} color="var(--ink-6)" />
          <input value={search} onChange={e => onSearch(e.target.value)} placeholder={searchPlaceholder} style={{ background: "transparent", border: "none", outline: "none", color: "var(--fg-1)", fontFamily: "var(--font-body)", fontSize: 13, width: 230 }} />
        </div>
        {statusOptions && (
          <select value={statusFilter} onChange={e => onStatus(e.target.value)} style={{
            background: "transparent", border: "1px solid var(--ink-3)", color: "var(--fg-1)",
            padding: "9px 12px", fontFamily: "var(--font-body)", fontSize: 12, letterSpacing: "0.04em",
            borderRadius: 2, cursor: "pointer", outline: "none"
          }}>
            {statusOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        )}
      </div>
    </div>
  );
}

// Table footer with result count + pager.
// onPrev/onNext make the pager live; when omitted the buttons stay inert (legacy
// callers). Buttons auto-disable at the first/last page.
function TableFooter({ shown, total, page, pages, onPrev, onNext }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 16px", borderTop: "1px solid var(--ink-3)", background: "var(--ink-1)" }}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-6)" }}>
        Showing <span style={{ color: "var(--fg-1)" }}>{shown}</span> of <span style={{ color: "var(--fg-1)" }}>{total}</span>
      </span>
      <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
        <Button variant="ghost" size="sm" onClick={onPrev} disabled={page <= 1}>← Prev</Button>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-2)", padding: "0 12px" }}>{page} / {pages}</span>
        <Button variant="ghost" size="sm" onClick={onNext} disabled={page >= pages}>Next →</Button>
      </div>
    </div>
  );
}

// Copy-to-clipboard email affordance — global treatment, approved.
function CopyEmail({ email }) {
  const [copied, setCopied] = React.useState(false);
  const [hover, setHover] = React.useState(false);
  function copy(e) {
    e.stopPropagation();
    try { navigator.clipboard.writeText(email); } catch (err) {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
  }
  return (
    <span
      onClick={copy}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      title="Copy email"
      style={{ display: "inline-flex", alignItems: "center", gap: 7, cursor: "pointer", userSelect: "none" }}
    >
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: copied ? "var(--rdb-gold)" : hover ? "var(--fg-1)" : "var(--fg-2)", whiteSpace: "nowrap", transition: "color 120ms" }}>{email}</span>
      <Icon name={copied ? "check" : "copy"} size={12} color={copied || hover ? "var(--rdb-gold)" : "var(--ink-5)"} />
      {copied && <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--rdb-gold)", textTransform: "uppercase", letterSpacing: "0.12em" }}>Copied</span>}
    </span>
  );
}

// Uniform external link — opens in a new tab, consistent icon + hover treatment.
function ExtLink({ href, children }) {
  const [hover, setHover] = React.useState(false);
  return (
    <a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      onClick={e => e.stopPropagation()}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-mono)", fontSize: 12, color: hover ? "var(--rdb-gold)" : "var(--fg-2)", textDecoration: "none", whiteSpace: "nowrap", transition: "color 120ms" }}
    >
      {children}
      <Icon name="external-link" size={12} color={hover ? "var(--rdb-gold)" : "var(--ink-6)"} />
    </a>
  );
}

Object.assign(window, { Th, Td, PageHeader, StatStrip, FilterBar, TableFooter, CopyEmail, ExtLink });
