// Solo staff admin area — Email Log: a read-only audit trail of every
// outbound email the platform has sent (welcome emails, company/user
// approve-reject, ticket alerts + reseller notifications, password
// resets, staff invites, contact form) — see routes/admin-email-log.ts
// for the backend and lib/emailTemplate.ts's logEmail() for how rows
// land here. This is the customer's explicit ask to "track this
// somewhere in the admin portal" for delivery visibility.
//
// Reached via the sidebar nav in AdminShell (see admin-shell.jsx). Reuses
// MiniField/SectionLabel/EmptyNote/ModalError/adminInputStyle/adminSelectStyle
// from admin-assets-page.jsx (loaded earlier — see index.html), same
// pattern as admin-tickets-page.jsx.

const EMAIL_STATUS_LABELS = { pending: "Pending", sent: "Sent", failed: "Failed", skipped: "Skipped" };
const EMAIL_STATUS_COLORS = {
  pending: "rgba(140,140,140,0.95)",
  sent: "rgba(20,140,60,0.95)",
  failed: "rgba(190,40,30,0.95)",
  skipped: "rgba(180,110,0,0.95)",
};

const EMAIL_TYPE_LABELS = {
  contact_form: "Contact form",
  reseller_welcome: "Reseller welcome",
  company_approved: "Company approved",
  company_rejected: "Company rejected",
  user_approved: "User approved",
  user_rejected: "User rejected",
  ticket_created_staff_alert: "New ticket → staff alert",
  ticket_reply_to_reseller: "Ticket reply → reseller",
  ticket_status_change: "Ticket status change",
  password_reset_reseller: "Password reset (reseller)",
  password_reset_admin: "Password reset (staff)",
  staff_invite: "Staff invite",
};

function AdminEmailLogPage({ onNavigate }) {
  const [state, setState] = useState({ status: "loading", admin: null, emails: [], summary: null, emailTypes: [] });
  const [statusFilter, setStatusFilter] = useState("");
  const [typeFilter, setTypeFilter] = useState("");
  const [q, setQ] = useState("");

  const load = () => {
    const params = new URLSearchParams();
    if (statusFilter) params.set("status", statusFilter);
    if (typeFilter) params.set("emailType", typeFilter);
    if (q.trim()) params.set("q", q.trim());
    Promise.all([
      fetch("/api/admin/me", { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
      fetch(`/api/admin/email-log?${params.toString()}`, { credentials: "same-origin" }).then((r) => (r.ok ? r.json() : Promise.reject())),
    ])
      .then(([me, log]) => {
        setState({
          status: "ready", admin: me.admin,
          emails: log.emails || [], summary: log.summary || null, emailTypes: log.emailTypes || [],
        });
      })
      .catch(() => onNavigate("admin-login"));
  };

  useEffect(load, [statusFilter, typeFilter]); // eslint-disable-line react-hooks/exhaustive-deps

  if (state.status === "loading") {
    return <section style={{ background: "#fff", minHeight: "calc(100vh - 88px)" }} />;
  }

  const summary = state.summary || {};

  return (
    <AdminShell admin={state.admin} page="admin-email-log" onNavigate={onNavigate}
      subtitle="Staff only" title="Email log.">
      <div style={{ display: "flex", gap: 20, flexWrap: "wrap", marginBottom: 24 }}>
        <SummaryStat label="Total sent" value={summary.total || 0} />
        <SummaryStat label="Delivered" value={summary.sent || 0} color="rgba(20,140,60,0.95)" />
        <SummaryStat label="Failed" value={summary.failed || 0} color="rgba(190,40,30,0.95)" />
        <SummaryStat label="Skipped" value={summary.skipped || 0} color="rgba(180,110,0,0.95)" />
      </div>

      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 24 }}>
        <MiniField label="Recipient or subject">
          <input
            value={q} onChange={(e) => setQ(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter") load(); }}
            onBlur={load}
            placeholder="Search…" style={adminInputStyle}
          />
        </MiniField>
        <MiniField label="Status">
          <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} style={adminSelectStyle}>
            <option value="">All statuses</option>
            {Object.keys(EMAIL_STATUS_LABELS).map((s) => <option key={s} value={s}>{EMAIL_STATUS_LABELS[s]}</option>)}
          </select>
        </MiniField>
        <MiniField label="Email type">
          <select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)} style={adminSelectStyle}>
            <option value="">All types</option>
            {state.emailTypes.map((t) => <option key={t} value={t}>{EMAIL_TYPE_LABELS[t] || t}</option>)}
          </select>
        </MiniField>
      </div>

      <SectionLabel>Emails ({state.emails.length}{state.emails.length === 300 ? "+" : ""})</SectionLabel>
      {state.emails.length === 0 ? (
        <EmptyNote>No emails match this filter.</EmptyNote>
      ) : (
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)", fontSize: 13 }}>
            <thead>
              <tr style={{ textAlign: "left", borderBottom: "1px solid rgba(0,0,0,0.14)" }}>
                <Th>When</Th>
                <Th>Type</Th>
                <Th>To</Th>
                <Th>Subject</Th>
                <Th>Related</Th>
                <Th>Status</Th>
              </tr>
            </thead>
            <tbody>
              {state.emails.map((e) => <EmailRow key={e.id} email={e} />)}
            </tbody>
          </table>
        </div>
      )}
    </AdminShell>
  );
}

function SummaryStat({ label, value, color }) {
  return (
    <div style={{ minWidth: 120 }}>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, color: color || "#000" }}>{value}</div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "rgba(0,0,0,0.55)" }}>
        {label}
      </div>
    </div>
  );
}

function Th({ children }) {
  return (
    <th style={{
      padding: "10px 14px", fontFamily: "var(--font-body)", fontSize: 11,
      letterSpacing: "0.08em", textTransform: "uppercase", color: "rgba(0,0,0,0.55)", fontWeight: 600,
    }}>
      {children}
    </th>
  );
}

function Td({ children, wrap }) {
  return (
    <td style={{
      padding: "10px 14px", borderBottom: "1px solid rgba(0,0,0,0.08)", verticalAlign: "top",
      ...(wrap ? { wordBreak: "break-all" } : {}),
    }}>
      {children}
    </td>
  );
}

function EmailRow({ email }) {
  const related = email.ticket_number
    ? `Ticket ${email.ticket_number}`
    : email.company_name || (email.related_user_id ? `User #${email.related_user_id}` : "—");

  return (
    <tr data-testid={`email-log-row-${email.id}`}>
      <Td>
        <span style={{ whiteSpace: "nowrap", color: "rgba(0,0,0,0.7)" }}>
          {new Date(email.created_at.replace(" ", "T") + "Z").toLocaleString()}
        </span>
      </Td>
      <Td>{EMAIL_TYPE_LABELS[email.email_type] || email.email_type}</Td>
      <Td wrap>{email.to_email}</Td>
      <Td>{email.subject}</Td>
      <Td>{related}</Td>
      <Td>
        <span style={{
          color: EMAIL_STATUS_COLORS[email.status] || "rgba(0,0,0,0.55)",
          textTransform: "uppercase", letterSpacing: "0.08em", fontSize: 11, fontWeight: 600,
        }}>
          {EMAIL_STATUS_LABELS[email.status] || email.status}
        </span>
        {email.error && (
          <div style={{ fontSize: 11, color: "rgba(190,40,30,0.85)", marginTop: 4, maxWidth: 260 }}>
            {email.error}
          </div>
        )}
      </Td>
    </tr>
  );
}

Object.assign(window, { AdminEmailLogPage });
