/* Deliverability — whether what we send arrives.
   Commit model: INSTANT. Rechecking DNS is harmless and confirms itself; there
   is nothing else to commit here.
   Data state: one branch — populated.
   NOT time-scoped, and the screen says so in words: these are every send attempt
   Marketing Desk has recorded — journey steps since each journey was published,
   broadcasts since each one sent. A period control would imply the journey step
   counts are dated, and they are not.
   Primary display: a matrix. Three DNS checks across three domains is a grid
   question, and it declares its own horizontal scroll rather than reflowing into
   something that is no longer a matrix. The table under it is what makes the
   failure figure checkable: every row links to the record it came from. */
(() => {
  const {
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Button, Badge,
  } = window.OriginDesignSystem_7c998b;

  function CheckCell({ value }) {
    const found = DOMAIN_CHECKS.find((c) => c.id === value);
    return (
      <span className="md-status">
        <Icon name={value === "pass" ? "check" : value === "failing" ? "x" : "minus"} size={14} />
        <StatusBadge values={DOMAIN_CHECKS} value={found ? found.id : value} />
      </span>
    );
  }

  function DeliverabilityScreen({ data, now, onNavigate, onRecheck, onAddDomain }) {
    const attempts = sendAttempts(data);
    const failures = deliveryFailures(data);
    const sources = failureSources(data);
    const authenticated = authenticatedDomains(data.domains);
    const worst = sources[0];

    return (
      <>
        <PageHeader
          path="/deliverability"
          title="Deliverability"
          actions={
            <>
              <Button variant="outline" size="sm" onClick={onRecheck}><Icon name="refresh-cw" />Recheck DNS</Button>
              <Button size="sm" onClick={onAddDomain}><Icon name="plus" />Add domain</Button>
            </>
          }
        />

        <div className="md-scope">
          <p className="md-scope__note">
            No period: these are every send attempt Marketing Desk has recorded — journey steps since each journey was published, broadcasts since each one sent.
          </p>
        </div>

        <Figures items={[
          {
            label: "Send attempts",
            value: formatCount(attempts.total),
            qualifier: formatCount(attempts.journeys) + " from journey steps · " + formatCount(attempts.broadcasts) + " from broadcasts",
          },
          {
            label: "Failed to deliver",
            value: formatCount(failures.total),
            qualifier: formatCount(failures.journeys) + " on journey steps · " + formatCount(failures.broadcasts) + " on partial broadcasts",
          },
          {
            label: "Failure rate",
            value: formatPercent(rate(failures.total, attempts.total)),
            qualifier: worst
              ? "Worst source: “" + worst.label + "” at " + formatPercent(rate(worst.failed, worst.attempted))
              : "Nothing has failed to deliver",
          },
          {
            label: "Authenticated domains",
            value: formatCount(authenticated.length),
            qualifier: authenticated.length === data.domains.length
              ? "All " + data.domains.length + " pass SPF, DKIM and DMARC"
              : data.domains.filter((d) => !domainIsAuthenticated(d)).map((d) => d.domain).join(" · ") + " " + (data.domains.length - authenticated.length === 1 ? "does not" : "do not") + " pass all three",
          },
        ]} />

        <section className="md-band md-band--flush">
          <div className="md-band__head">
            <div>
              <h2 className="md-band__title">Domain authentication</h2>
              <p className="md-band__note">A domain is authenticated when all three checks pass. Anything else and receiving servers are free to treat the mail as unverified.</p>
            </div>
          </div>
          <div className="md-tablewrap">
            <div className="md-matrix">
              <span className="md-matrix__head">Domain</span>
              <span className="md-matrix__head">SPF</span>
              <span className="md-matrix__head">DKIM</span>
              <span className="md-matrix__head">DMARC</span>
              <span className="md-matrix__head">Last checked</span>
              {data.domains.map((domain) => (
                <React.Fragment key={domain.id}>
                  <span>
                    <span className="md-matrix__domain">{domain.domain}</span>
                    <span className="md-footnote">{domain.purpose}</span>
                  </span>
                  <span><CheckCell value={domain.spf} /></span>
                  <span><CheckCell value={domain.dkim} /></span>
                  <span><CheckCell value={domain.dmarc} /></span>
                  <span className="md-muted" title={formatAbsolute(domain.checkedAt)}>{formatWhen(domain.checkedAt, now)}</span>
                </React.Fragment>
              ))}
            </div>
          </div>
          <div className="md-tablefoot">
            <span className="md-footnote">{authenticated.length} of {data.domains.length} domains {authenticated.length === 1 ? "passes" : "pass"} all three checks.</span>
            <span className="md-footnote">{data.broadcasts.filter((b) => b.domainId && !domainIsAuthenticated(domainById(data.domains, b.domainId))).length} broadcasts are set to send from a domain that does not.</span>
          </div>
        </section>

        <section className="md-band md-band--flush">
          <div className="md-band__head">
            <div>
              <h2 className="md-band__title">Where the failures are</h2>
              <p className="md-band__note">The {formatCount(failures.total)} failures above, by the thing that produced them, worst rate first. A send still in flight is not in here — what it has not handed off yet is pending, not failed. A journey step at {formatPercent(FAILURE_THRESHOLD)} or more is flagged on the journey itself.</p>
            </div>
          </div>
          <div className="md-tablewrap">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>What sent it</TableHead>
                  <TableHead className="md-drop-md">Where</TableHead>
                  <TableHead className="md-num">Attempted</TableHead>
                  <TableHead className="md-num">Failed</TableHead>
                  <TableHead className="md-num">Rate</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {sources.map((row) => {
                  const failureRate = rate(row.failed, row.attempted);
                  return (
                    <TableRow key={row.key}>
                      <TableCell>
                        <button type="button" className="md-link" onClick={() => onNavigate(row.route)}>{row.label}</button>
                      </TableCell>
                      <TableCell className="md-muted md-drop-md">{row.where}</TableCell>
                      <TableCell className="md-num md-amount">{formatCount(row.attempted)}</TableCell>
                      <TableCell className="md-num md-amount">{formatCount(row.failed)}</TableCell>
                      <TableCell className="md-num">
                        <span className={isOverFailureThreshold(row.failed, row.attempted) ? "md-clock--danger md-amount" : "md-amount"}>{formatPercent(failureRate)}</span>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
          <div className="md-tablefoot">
            <span className="md-footnote">{sources.length} sources account for all {formatCount(failures.total)} failures.</span>
            <span className="md-footnote">{sources.filter((r) => isOverFailureThreshold(r.failed, r.attempted)).length} of them are at or above the {formatPercent(FAILURE_THRESHOLD)} threshold.</span>
          </div>
        </section>
      </>
    );
  }

  Object.assign(window, { DeliverabilityScreen });
})();
