/* Reports — what sending did, read as shapes.

   Commit model: INSTANT (nothing commits; this screen only reads).
   Data state: one branch — populated.
   Scope: the period control sits above every figure and moves all of them, the
   chart and the two decompositions together. The per-audience and per-owner
   tables underneath are the same window decomposed, never a different one.

   Every figure names its array: the series is deliverySeries (journey log plus
   each broadcast on the day it went out), the audience rows are the sent
   broadcasts inside the window grouped by their audience, the owner rows the
   same grouped by owner. Nothing here is authored. */
(() => {
  const {
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Select, Button, Badge,
  } = window.OriginDesignSystem_7c998b;

  function ReportsScreen({ data, now, period, onPeriodChange, onNavigate }) {
    const days = Number(period);
    const series = deliverySeries(data, days, now);
    const totals = deliveryTotals(series);
    const sent = sentBroadcasts(data.broadcasts, days, now);

    const byAudience = data.audiences.map((audience) => {
      const rows = sent.filter((b) => b.audienceId === audience.id);
      return {
        audience,
        sends: sumBy(rows, "sends"),
        delivered: sumBy(rows, "delivered"),
        opened: sumBy(rows, "opened"),
        clicked: sumBy(rows, "clicked"),
        count: rows.length,
      };
    }).filter((row) => row.count).sort((a, b) => b.delivered - a.delivered);

    const byOwner = data.members.map((member) => {
      const rows = sent.filter((b) => b.ownerId === member.id);
      return { member, count: rows.length, delivered: sumBy(rows, "delivered"), opened: sumBy(rows, "opened") };
    }).filter((row) => row.count).sort((a, b) => b.delivered - a.delivered);

    const journeyShare = rate(totals.journey.delivered, totals.delivered);
    const openRate = rate(totals.opened, totals.delivered);
    const clickRate = rate(totals.clicked, totals.delivered);
    const unsubRate = rate(totals.unsubs, totals.delivered);
    const bestDay = series.slice().sort((a, b) => b.delivered - a.delivered)[0];

    return (
      <>
        <PageHeader path="/reports" title="Reports" actions={
          <ExportMenu scope={"Last " + days + " days"} onExport={() => {}} />
        } />

        <div className="md-scope">
          <span className="md-scope__control">
            <span className="md-scope__label">Period</span>
            <span className="md-scope__select">
              <Select size="sm" items={PERIODS} value={period} aria-label="Period for every figure on this screen" onValueChange={onPeriodChange} />
            </span>
          </span>
          <p className="md-scope__note">Everything below covers the last {days} days: {formatCount(totals.delivered)} delivered from journeys and broadcasts together.</p>
        </div>

        <Tiles>
          <Tile span="7" tone="hero" title="Delivered, and what came back"
            note={"The shape of the last " + days + " days. Day-by-day numbers live on the Overview chart; this is the trend."}>
            <StatRow>
              <StatTile label="Delivered" value={formatCount(totals.delivered)}
                spark={<Spark points={series.map((d) => d.delivered)} />}
                qualifier={formatCount(totals.journey.delivered) + " from journeys · " + formatCount(totals.broadcast.delivered) + " from broadcasts"} />
              <StatTile label="Opens" value={formatCount(totals.opened)}
                spark={<Spark points={series.map((d) => d.opened)} tone="success" />}
                qualifier={formatPercent(openRate) + " of what was delivered"} />
              <StatTile label="Clicks" value={formatCount(totals.clicked)}
                spark={<Spark points={series.map((d) => d.clicked)} tone="warning" />}
                qualifier={formatPercent(clickRate) + " of the same delivered total"} />
            </StatRow>
            <PillMeter label={"Where the " + formatCount(totals.delivered) + " came from"}
              parts={[
                { key: "journeys", percent: journeyShare * 100 },
                { key: "broadcasts", percent: (1 - journeyShare) * 100, tone: "soft" },
              ]}
              foot={formatPercent(journeyShare) + " of everything delivered came from journeys running continuously; the rest is " + sent.length + " one-off sends."} />
          </Tile>

          <Tile span="5" title="Engagement against delivery" note="Both rates read the same delivered total, so they are comparable.">
            <div style={{ display: "flex", flexWrap: "wrap", gap: "var(--space-5)", justifyContent: "space-around" }}>
              <Gauge percent={openRate * 100} value={formatPercent(openRate)} label="opened" tone={openRate > 0.3 ? "success" : "warning"}
                note={formatCount(totals.opened) + " opens across " + formatCount(totals.delivered) + " delivered."} />
              <Gauge percent={clickRate * 100 * 4} value={formatPercent(clickRate)} label="clicked" tone="default"
                note={"Drawn against a 25% ceiling — " + formatCount(totals.clicked) + " clicks."} />
            </div>
            <KeyValues rows={[
              { label: "Unsubscribes", value: formatCount(totals.unsubs) + " · " + formatPercent(unsubRate) },
              { label: "Busiest day", value: new Date(bestDay.at).toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" }) + " · " + formatCount(bestDay.delivered) },
              { label: "One-off sends in window", value: String(sent.length) },
            ]} />
          </Tile>

          <Tile span="5" title="Which audiences carried it" note="Sent broadcasts in the window, grouped by the audience they went to. The slices sum to the broadcast delivered total.">
            <div className="md-donutrow">
              <Donut slices={byAudience.map((row) => ({ key: row.audience.id, value: row.delivered }))}
                centreValue={formatCount(totals.broadcast.delivered)} centreLabel="delivered by broadcasts" />
              <DonutKey slices={byAudience.map((row) => ({ key: row.audience.id, label: row.audience.name, display: formatCount(row.delivered) }))} />
            </div>
          </Tile>

          <Tile span="7" flush title="Audience by audience" note="Open rate is that audience's opens over its own delivered — never over the workspace total.">
            <div className="md-tablewrap">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Audience</TableHead>
                    <TableHead>Sends</TableHead>
                    <TableHead>Delivered</TableHead>
                    <TableHead>Opened</TableHead>
                    <TableHead>Clicked</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {byAudience.map((row) => (
                    <TableRow key={row.audience.id}>
                      <TableCell>
                        <button type="button" className="md-link" onClick={() => onNavigate("/audiences/" + row.audience.id)}>{row.audience.name}</button>
                        <span className="md-footnote"> · {row.count} {row.count === 1 ? "send" : "sends"}</span>
                      </TableCell>
                      <TableCell>{formatCount(row.sends)}</TableCell>
                      <TableCell>{formatCount(row.delivered)}</TableCell>
                      <TableCell>{formatPercent(rate(row.opened, row.delivered))}</TableCell>
                      <TableCell>{formatPercent(rate(row.clicked, row.delivered))}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Tile>

          <Tile span="6" title="Who sent it" note="The same sent broadcasts, grouped by the person the record names as owner.">
            <div className="md-queue">
              {byOwner.map((row) => (
                <div className="md-queue__row" key={row.member.id}>
                  <div className="md-person">
                    <Face person={row.member} size={30} />
                    <div className="md-person__text">
                      <button type="button" className="md-link md-person__name" onClick={() => onNavigate("/people/" + row.member.id)}>{row.member.name}</button>
                      <span className="md-person__role">{row.count} {row.count === 1 ? "send" : "sends"} · {formatPercent(rate(row.opened, row.delivered))} opened</span>
                    </div>
                  </div>
                  <div className="md-queue__side">
                    <span style={{ minWidth: "8rem" }}>
                      <PillMeter parts={[{ key: "d", percent: (row.delivered / byOwner[0].delivered) * 100 }]} />
                    </span>
                    <span className="md-footnote">{formatCount(row.delivered)}</span>
                  </div>
                </div>
              ))}
            </div>
            <div className="md-tile__foot">
              <span>Journey sends are not attributed to a person here — a live journey keeps sending long after whoever built it moved on.</span>
            </div>
          </Tile>

          <Tile span="6" title="Where engagement is weakest" note="The same sent broadcasts, ordered by their own open rate — lowest first. This is the figure that decides whether a segment is being over-sent to.">
            <div className="md-queue">
              {byAudience.slice().sort((a, b) => rate(a.opened, a.delivered) - rate(b.opened, b.delivered)).slice(0, 4).map((row) => (
                <div className="md-queue__row" key={row.audience.id}>
                  <div className="md-queue__main">
                    <button type="button" className="md-link" onClick={() => onNavigate("/audiences/" + row.audience.id)}>{row.audience.name}</button>
                    <span className="md-footnote">{formatCount(row.delivered)} delivered in this window across {row.count} {row.count === 1 ? "send" : "sends"}</span>
                  </div>
                  <div className="md-queue__side">
                    <Chip>{formatPercent(rate(row.clicked, row.delivered))} clicked</Chip>
                    <Chip tone={rate(row.opened, row.delivered) < 0.2 ? "warning" : undefined}>{formatPercent(rate(row.opened, row.delivered))} opened</Chip>
                  </div>
                </div>
              ))}
            </div>
            <div className="md-tile__foot">
              <span>Workspace unsubscribes over the window: {formatCount(totals.unsubs)} — {formatPercent(unsubRate)} of everything delivered.</span>
              <Button variant="ghost" size="sm" onClick={() => onNavigate("/deliverability")}>Deliverability<Icon name="arrow-right" size={14} /></Button>
            </div>
          </Tile>
        </Tiles>
      </>
    );
  }

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