/* eslint-disable */
// Loaded as a separate <script type="text/babel">. Exposes components on window
// so app.jsx (separate Babel scope) can pick them up at render time.
(function () {
  const { useEffect, useMemo, useRef } = React;

  // ── helpers (mirrors app.jsx, since each Babel script gets its own scope) ──
  function rptJoin(items, conj = "and") {
    if (!items || items.length === 0) return "";
    if (items.length === 1) return items[0];
    if (items.length === 2) return `${items[0]} ${conj} ${items[1]}`;
    return `${items.slice(0, -1).join(", ")}, ${conj} ${items[items.length - 1]}`;
  }

  const STATUS_LABEL = {
    active: "active", lapsing: "lapsing", prospect: "prospect",
    dormant: "dormant", churned: "churned", unknown: "unknown",
  };

  function orgPaymentLine(org) {
    for (const a of (org.accounts || [])) {
      const p = a.payment;
      if (!p || !p.amount) continue;
      if (p.cadence === "month")  return `${p.amount}/month`;
      if (p.cadence === "annual") return `${p.amount}/year`;
      if (p.cadence && p.cadence !== "n/a") return `${p.amount} (${p.cadence})`;
      return p.amount;
    }
    return null;
  }

  function orgNextDate(org) {
    for (const a of (org.accounts || [])) {
      if (a.payment?.next) return a.payment.next;
    }
    return null;
  }

  function orgPaymentMethod(org) {
    for (const a of (org.accounts || [])) {
      if (a.payment?.method) return a.payment.method;
    }
    return null;
  }

  function orgActions(org) {
    const out = [];
    for (const a of (org.accounts || [])) for (const t of (a.actions || [])) out.push(t);
    return out;
  }

  function orgEvents(org) {
    const out = [];
    for (const a of (org.accounts || [])) for (const e of (a.events || [])) out.push({ ...e, _acct: a.name });
    out.sort((x, y) => (x.date < y.date ? 1 : -1));
    return out;
  }

  function orgDocs(org) {
    const out = [];
    for (const a of (org.accounts || [])) for (const d of (a.docs || [])) out.push({ ...d, _acct: a.name });
    return out;
  }

  function monthlyTotalOrg(org) {
    let total = 0;
    for (const a of (org.accounts || [])) {
      const p = a.payment;
      if (!p?.amount) continue;
      const m = String(p.amount).match(/£([\d,]+\.?\d*)/);
      if (!m) continue;
      const v = parseFloat(m[1].replace(/,/g, ""));
      if (Number.isNaN(v)) continue;
      if (p.cadence === "month") total += v;
      else if (p.cadence === "annual") total += v / 12;
    }
    return total;
  }

  function orgBlurb(org) {
    const status = org.relationship_status || "unknown";
    const pay = orgPaymentLine(org);
    const next = orgNextDate(org);
    const n = (org.accounts || []).length;
    const noun = n === 1 ? "resource" : "resources";
    let lead = org.relationship_summary || `${n} ${noun} held with ${org.organisation_name}.`;
    let tail = "";
    if (status === "lapsing") {
      tail = next ? `Currently lapsing — ${next}.` : "Currently lapsing.";
    } else if (status === "dormant") {
      tail = "Marked dormant; no recent activity.";
    } else if (pay && next) {
      tail = `Charged ${pay}; next ${next}.`;
    } else if (pay) {
      tail = `Charged ${pay}.`;
    } else if (next) {
      tail = `Next event ${next}.`;
    }
    return tail ? `${lead} ${tail}` : lead;
  }

  function categoryNotes(orgs) {
    return rptJoin(orgs.map(o => o.organisation_name), "and");
  }

  // ── Report header ─────────────────────────────────────────────────────────
  function ReportHeader({ user, dateStr, timeStr, docRef, subtitle }) {
    const Wordmark = window.Wordmark;
    return (
      <header className="page__head">
        <div className="page__brand">
          {Wordmark && <Wordmark size={22} />}
          <span className="page__brand-sub">{subtitle || "Asset Handover Report"}</span>
        </div>
        <div className="page__meta">
          <div className="page__meta-prepared">
            <span className="page__meta-label">Prepared for</span>
            <span className="page__meta-name">{user?.name || "—"}</span>
          </div>
          {(user?.email || user?.address) && (
            <div className="page__meta-contact">
              {user?.email && <span className="page__meta-line">{user.email}</span>}
              {user?.address && <span className="page__meta-line">{user.address}</span>}
            </div>
          )}
          <div className="page__meta-rule" />
          <dl className="page__meta-rows">
            <div className="page__meta-row"><dt>Issued</dt><dd>{dateStr} · {timeStr}</dd></div>
            <div className="page__meta-row"><dt>Document ref</dt><dd className="mono">{docRef}</dd></div>
          </dl>
        </div>
      </header>
    );
  }

  // ── Per-org section inside the consolidated report ────────────────────────
  function RSumOrg({ org }) {
    const status = org.relationship_status || "unknown";
    const pay = orgPaymentLine(org);
    const next = orgNextDate(org);
    const method = orgPaymentMethod(org);
    const actions = orgActions(org);

    const facts = [];
    if (pay) facts.push(["Payment", pay]);
    if (next) facts.push(["Next", next]);
    if (method) facts.push(["Method", method]);

    return (
      <article className="rsum__org" id={`org-${org.resource_id || org.organisation_name}`}>
        <h3 className="rsum__org-h">
          <span className="rsum__org-name">{org.organisation_name}</span>
          <span className="rsum__org-status" data-status={status}>— {STATUS_LABEL[status] || status}</span>
        </h3>
        <p className="rsum__org-res-label">Resources:</p>
        <ul className="rsum__org-resources">
          {(org.accounts || []).map((a, i) => {
            const detailEntries = Object.entries(a.details || {});
            return (
              <li key={i}>
                <div className="rsum__org-res-row">
                  <span className="rsum__org-res-dot" />
                  <span className="rsum__org-res-name">{a.name && a.name !== org.organisation_name ? a.name : (a.resource_type || a.name || "Account")}</span>
                </div>
                {detailEntries.length > 0 && (
                  <dl className="rsum__res-details">
                    {detailEntries.map(([k, v]) => (
                      <React.Fragment key={k}><dt>{k}</dt><dd>{v}</dd></React.Fragment>
                    ))}
                  </dl>
                )}
              </li>
            );
          })}
        </ul>
        <p className="rsum__blurb">{orgBlurb(org)}</p>
        {(facts.length > 0 || actions.length > 0) && (
          <dl className="rsum__facts">
            {facts.map(([k, v]) => (
              <React.Fragment key={k}><dt>{k}</dt><dd>{v}</dd></React.Fragment>
            ))}
            {actions.length > 0 && (
              <>
                <dt className="rsum__facts-actions-l">Actions</dt>
                <dd className="rsum__facts-actions-v">
                  {actions.join("; ")}{actions[actions.length - 1]?.endsWith(".") ? "" : "."}
                </dd>
              </>
            )}
          </dl>
        )}
      </article>
    );
  }

  function RSumCategory({ category, label, family, orgs }) {
    return (
      <section className="rsum__cat" data-family={family} id={`cat-${category}`}>
        <h2 className="rsum__cat-h">{label}</h2>
        {orgs.map(o => <RSumOrg key={o.resource_id || o.organisation_name} org={o} />)}
      </section>
    );
  }

  // ── Consolidated report ───────────────────────────────────────────────────
  function SlimReportDoc({ report, user }) {
    const CATEGORY_LABELS = window.CATEGORY_LABELS || {};
    const CATEGORY_ORDER  = window.CATEGORY_ORDER || Object.keys(report.orgs_by_category || {});

    const date = new Date();
    const dateStr = date.toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" });
    const timeStr = date.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
    const docRef = "MH-" + date.getTime().toString(36).toUpperCase().slice(-8);

    const orgs = report.orgs || [];
    const populated = CATEGORY_ORDER
      .map(c => ({
        c,
        orgs: (report.orgs_by_category || {})[c] || [],
      }))
      .filter(r => r.orgs.length > 0);

    let totalResources = 0, totalActions = 0;
    for (const o of orgs) {
      for (const a of (o.accounts || [])) {
        totalResources += 1;
        totalActions += (a.actions || []).length;
      }
    }

    const priorityActions = useMemo(() => {
      const out = [];
      const lapsing = orgs.filter(o => (o.accounts || []).some(a => a.status === "lapsing"));
      if (lapsing.length > 0) {
        out.push(`Confirm or cancel lapsing accounts before they end — ${rptJoin(lapsing.map(l => l.organisation_name))}.`);
      }
      const subs = (report.orgs_by_category || {}).subscriptions || [];
      if (subs.length > 0) {
        out.push("Review active subscriptions ahead of the next renewal cycle.");
      }
      const withActions = orgs.filter(o => orgActions(o).length > 0);
      if (withActions.length > 0) {
        out.push(`Address ${totalActions} outstanding action${totalActions === 1 ? "" : "s"} flagged across ${withActions.length} organisation${withActions.length === 1 ? "" : "s"}.`);
      }
      return out;
    }, [orgs]);

    return (
      <div className="page-wrap">
        <article className="page page--md rsum" id="report-page">
          <ReportHeader user={user} dateStr={dateStr} timeStr={timeStr} docRef={docRef} />

          <section className="page__body rsum__body">
            <h1 className="rsum__h1">Your handover, <em>in one place</em>.</h1>
            <p className="rsum__lede">
              Across <strong>{orgs.length}</strong> organisation{orgs.length === 1 ? "" : "s"} we identified <strong>{totalResources}</strong> resource{totalResources === 1 ? "" : "s"} with material financial, digital or administrative ties.
              {" "}High-confidence relationships should be reviewed for transfer or cancellation;
              lower-confidence ones are documented as evidence and may indicate dormant accounts worth closing.
            </p>

            <h4 className="rsum__h4">Summary</h4>
            <table className="rsum__table">
              <thead>
                <tr><th>Category</th><th className="num">Resource count</th><th>Notes</th></tr>
              </thead>
              <tbody>
                {populated.map(({ c, orgs }) => {
                  const resN = orgs.reduce((n, o) => n + (o.accounts?.length || 0), 0);
                  const fam = (orgs[0] && orgs[0].family) || "unknown";
                  return (
                    <tr key={c} data-family={fam}>
                      <td>
                        <span className="rsum__table-dot" />
                        <a href={`#cat-${c}`}>{CATEGORY_LABELS[c] || c}</a>
                      </td>
                      <td className="num">{resN}</td>
                      <td className="notes">{categoryNotes(orgs)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>

            {priorityActions.length > 0 && (
              <>
                <h4 className="rsum__h4">Priority actions</h4>
                <ol className="rsum__priorities">
                  {priorityActions.map((a, i) => <li key={i}>{a}</li>)}
                </ol>
              </>
            )}

            {populated.map(({ c, orgs }) => (
              <RSumCategory
                key={c}
                category={c}
                label={CATEGORY_LABELS[c] || c}
                family={(orgs[0] && orgs[0].family) || "unknown"}
                orgs={orgs}
              />
            ))}

            <p className="rsum__foot-note">
              Compiled by MyHandover from inbox evidence on {dateStr}.
              Verify material details directly with the named institutions before acting.
            </p>
          </section>

          <footer className="page__foot">
            <div>myhandover · {dateStr}</div>
            <div className="mono">{docRef}</div>
          </footer>
        </article>
      </div>
    );
  }

  // ── Per-org report modal (design's OrgReport shape) ───────────────────────
  function actionPriority(text) {
    return window.actionPriority ? window.actionPriority(text) : "LOW";
  }
  function resourceSignals(a) {
    return (a.events?.length || 0) + (a.docs?.length || 0);
  }

  function OrgReportModal({ org, user, onClose }) {
    const closeRef = useRef(onClose);
    closeRef.current = onClose;

    useEffect(() => {
      function onKey(e) { if (e.key === "Escape") closeRef.current && closeRef.current(); }
      document.addEventListener("keydown", onKey);
      document.body.style.overflow = "hidden";
      return () => {
        document.removeEventListener("keydown", onKey);
        document.body.style.overflow = "";
      };
    }, []);

    const CATEGORY_LABELS = window.CATEGORY_LABELS || {};
    const date = new Date();
    const dateStr = date.toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" });
    const timeStr = date.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
    const docRef = "MH-" + (org.resource_id || org.organisation_name).toString().toUpperCase().slice(0, 4) + "-" + date.getTime().toString(36).toUpperCase().slice(-6);

    const status = org.relationship_status || "unknown";
    const actionsAll = orgActions(org);
    const prioRank = { HIGH: 3, MEDIUM: 2, LOW: 1 };
    const actionsPrioritised = actionsAll
      .map((t) => ({ text: t, prio: actionPriority(t) }))
      .sort((a, b) => prioRank[b.prio] - prioRank[a.prio]);

    const allEvents = orgEvents(org);
    const intel = allEvents.map(e => ({ date: e.date, kind: e.kind || "notification", label: e.label }));
    const monthly = monthlyTotalOrg(org);
    const docs = orgDocs(org);

    return (
      <div className="orpt__overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
        <div className="orpt__sheet" role="dialog" aria-modal="true" aria-label={`Report for ${org.organisation_name}`}>
          <div className="orpt__bar">
            <span className="orpt__bar-l mono">Per-organisation report · {org.organisation_name}</span>
            <div className="orpt__bar-r">
              <button className="btn-ghost" onClick={() => {
                document.body.classList.add("print-org");
                const cleanup = () => { document.body.classList.remove("print-org"); window.removeEventListener("afterprint", cleanup); };
                window.addEventListener("afterprint", cleanup);
                window.print();
              }}>Print</button>
              <button className="btn-ghost" onClick={onClose} aria-label="Close">Close ✕</button>
            </div>
          </div>

          <article className="page page--md rsum orpt__doc" id="org-report-page">
            <ReportHeader
              user={user} dateStr={dateStr} timeStr={timeStr} docRef={docRef}
              subtitle={`Per-organisation report · ${CATEGORY_LABELS[org.category] || ""}`}
            />

            <section className="page__body rsum__body">
              <p className="rsum__eyebrow">{CATEGORY_LABELS[org.category] || org.category}</p>
              <h3 className="rsum__org-h">
                <span className="rsum__org-name">{org.organisation_name}</span>
                <span className="rsum__org-status" data-status={status}>— {STATUS_LABEL[status] || status}</span>
              </h3>
              <p className="rsum__org-res-label">RESOURCES:</p>
              <ul className="rsum__org-resources">
                {(org.accounts || []).map((a, i) => {
                  const detailEntries = Object.entries(a.details || {});
                  return (
                    <li key={i}>
                      <div className="rsum__org-res-row">
                        <span className="rsum__org-res-dot" />
                        <span className="rsum__org-res-name">{a.name && a.name !== org.organisation_name ? a.name : (a.resource_type || a.name || "Account")}</span>
                      </div>
                      {detailEntries.length > 0 && (
                        <dl className="rsum__res-details">
                          {detailEntries.map(([k, v]) => (
                            <React.Fragment key={k}><dt>{k}</dt><dd>{v}</dd></React.Fragment>
                          ))}
                        </dl>
                      )}
                    </li>
                  );
                })}
              </ul>
              <p className="rsum__blurb">{orgBlurb(org)}</p>
              <dl className="rsum__facts">
                {orgPaymentLine(org) && (
                  <><dt>PAYMENT</dt><dd>{orgPaymentLine(org)}</dd></>
                )}
                {orgNextDate(org) && (
                  <><dt>NEXT</dt><dd>{orgNextDate(org)}</dd></>
                )}
                {orgPaymentMethod(org) && (
                  <><dt>METHOD</dt><dd>{orgPaymentMethod(org)}</dd></>
                )}
                {actionsAll.length > 0 && (
                  <>
                    <dt className="rsum__facts-actions-l">ACTIONS</dt>
                    <dd className="rsum__facts-actions-v">
                      {actionsAll.join("; ")}{actionsAll[actionsAll.length - 1]?.endsWith(".") ? "" : "."}
                    </dd>
                  </>
                )}
              </dl>

              {allEvents.length > 0 && (
                <>
                  <h4 className="rsum__h4">Key Events</h4>
                  <ul className="rsum__events rsum__events--keyed">
                    {allEvents.map((e, i) => (
                      <li key={i} data-kind={e.kind || "strong"}>
                        <span className="d mono">{e.date}</span>
                        <span className="e">{e.label}</span>
                        <span className="k">({e.kind || "strong"})</span>
                      </li>
                    ))}
                  </ul>
                </>
              )}

              {actionsPrioritised.length > 0 && (
                <>
                  <h4 className="rsum__h4">Actions Required</h4>
                  <ul className="rsum__actreq">
                    {actionsPrioritised.map((a, i) => (
                      <li key={i}>
                        <span className={`prio prio--${a.prio}`}>{a.prio}</span>
                        <span className="rsum__actreq-text">{a.text}</span>
                      </li>
                    ))}
                  </ul>
                </>
              )}

              {intel.length > 0 && (
                <>
                  <h4 className="rsum__h4">Email Intelligence</h4>
                  <p className="rsum__intel-note">
                    Chronological extract of inbox signals attributed to {org.organisation_name}.
                  </p>
                  <ul className="rsum__intel">
                    {intel.slice().reverse().map((e, i) => (
                      <li key={i}>
                        <span className="d mono">{e.date}</span>
                        <span className="k mono">{e.kind}</span>
                        <span className="e">— {e.label}</span>
                      </li>
                    ))}
                  </ul>
                </>
              )}

              <h4 className="rsum__h4">Confirmed Resources</h4>
              <ul className="rsum__confirmed">
                {(org.accounts || []).map((a, i) => (
                  <li key={i}>
                    <span className="rsum__conf-name">{a.name}</span>
                    <span className="rsum__rid-sep">·</span>
                    <span className="rsum__rid-status" data-status={a.status}>{STATUS_LABEL[a.status] || a.status}</span>
                    <span className="rsum__rid-sep">·</span>
                    <span className="rsum__conf-family">{org.family}</span>
                  </li>
                ))}
              </ul>

              {docs.length > 0 && (
                <>
                  <h4 className="rsum__h4">Documents on File</h4>
                  <ul className="rsum__docs">
                    {docs.map((d, i) => (
                      <li key={i}>
                        <span className="dn">{d.name}</span>
                        {d.date && <span className="dd mono">{d.date}</span>}
                      </li>
                    ))}
                  </ul>
                </>
              )}

              <p className="rsum__footline mono">
                Organisations: 1 · Confirmed resources: {(org.accounts || []).length} · Events: {allEvents.length} · Actions: {actionsAll.length}
              </p>

              <p className="rsum__foot-note">
                Compiled by MyHandover for {user?.email || "you"} on {dateStr}.
                Verify material details directly with {org.organisation_name} before acting.
              </p>
            </section>

            <footer className="page__foot">
              <div>myhandover · {org.organisation_name} · {dateStr}</div>
              <div className="mono">{docRef}</div>
            </footer>
          </article>
        </div>
      </div>
    );
  }

  window.SlimReportDoc = SlimReportDoc;
  window.OrgReportModal = OrgReportModal;
  window.Wordmark = window.Wordmark; // app.jsx assigns this; report.jsx loads after.
})();
