// ─────────────────────────────────────────────────────────────────────
// REPORTS — home of financial reporting for the collection.
//
// The Monthly Expense Report is the primary entry point: the operational
// monthly task of packaging every expense (with its original receipts)
// for the collector family's accountant. The library below it is the
// roadmap — reports the archive will eventually write on demand.
// ─────────────────────────────────────────────────────────────────────

const { useState: useRpt } = React;

// Top bar — mirrors OpsTopBar (operations hub chrome).
function RptBar({ eyebrow, title, onClose }) {
  return (
    <div style={{
      padding: '10px 18px 12px', background: P.ink, flex: '0 0 auto',
      display: 'flex', alignItems: 'center', gap: 12, borderBottom: `1px solid ${P.graphite}`,
    }}>
      <button onClick={onClose} aria-label="Back" style={{
        background: P.gold, border: 'none', borderRadius: 999, width: 34, height: 34,
        flexShrink: 0, color: P.ink, cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
          strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
          <path d="M19 12H5M5 12l6-6M5 12l6 6" />
        </svg>
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: T.display, fontWeight: 600, fontSize: 15,
          letterSpacing: '0.02em', color: P.paper, lineHeight: 1.1,
        }}>{title}</div>
        <div style={{
          fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.16em', color: P.gold, marginTop: 3,
        }}>{eyebrow}</div>
      </div>
      <CAMonogram size={20} color={P.paper} stroke={1.6} />
    </div>
  );
}

// Small mono kv used across the reports surfaces.
function RptMono({ children, size = 9, color, tracking = '0.14em', style = {} }) {
  return (
    <span style={{
      fontFamily: T.mono, fontSize: size, letterSpacing: tracking,
      textTransform: 'uppercase', color: color || P.mute, ...style,
    }}>{children}</span>
  );
}

// Status chip for a report — DRAFT (gold) or SENT (quiet outline).
function ReportStatusChip({ sent }) {
  return sent ? (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 8px',
      border: `1px solid ${P.slate}`, color: P.mute,
      fontFamily: T.mono, fontSize: 8, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase',
    }}>
      <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke={P.gold}
        strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
      Sent
    </span>
  ) : (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 8px',
      border: `1px solid ${P.slate}`, color: P.gold,
      fontFamily: T.mono, fontSize: 8, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase',
    }}>
      <span style={{ width: 4, height: 4, background: P.gold, borderRadius: 3 }} />
      Draft
    </span>
  );
}

function ReportsHome({ onBack, onOpenMonthly }) {
  const store = useReportStore();
  const [reminderSheet, setReminderSheet] = useRpt(false);

  // Current draft = every expense not yet included in a sent report.
  const current = reportById('draft');
  const { included } = reportExpenses('draft');
  const roll = reportRollup(included);
  const rangeLabel = fmtRange(current.start, current.end);
  const reminder = REPORT_REMINDER_OPTIONS.find(o => o.id === store.reminder);

  // Sent history — newest first, each shown by its reporting period.
  const sentReports = allSentReports()
    .map(r => ({ ...r, roll: reportRollup(reportExpenses(r.id).included), rangeLabel: fmtRange(r.start, r.end) }))
    .reverse();

  return (
    <React.Fragment>
      <RptBar title="Send Expense Report" eyebrow="Financials" onClose={onBack} />
      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }}
        data-screen-label="rpt-home">

        {/* Intro */}
        <div style={{ padding: '18px 22px 14px' }}>
          <div style={{
            fontFamily: T.display, fontWeight: 700, fontSize: 32,
            lineHeight: 0.92, letterSpacing: '-0.02em', color: P.paper,
          }}>THE ARCHIVE,<br />REPORTED</div>
          <div style={{
            fontFamily: T.body, fontSize: 12.5, color: P.mute,
            marginTop: 10, lineHeight: 1.5, maxWidth: 310,
          }}>
            Reports organize records that already exist in the archive —
            packaged for accountants, owners, insurers, and buyers.
          </div>
        </div>

        {/* ── The current draft — every unreported expense ── */}
        <div style={{ padding: '4px 0 8px' }}><RowRule>NOT YET REPORTED</RowRule></div>
        <div style={{ padding: '12px 22px 6px' }}>
          <div style={{ background: P.graphite, borderLeft: `2px solid ${P.gold}` }}>
            <div style={{ padding: '16px 16px 14px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
                <div style={{ minWidth: 0 }}>
                  <RptMono size={8.5} color={P.gold} tracking="0.18em">Expense Report</RptMono>
                  <div style={{
                    fontFamily: T.display, fontSize: 21, fontWeight: 700, color: P.paper,
                    letterSpacing: '-0.015em', lineHeight: 1.05, marginTop: 7,
                  }}>{current.empty ? 'ALL CAUGHT UP' : rangeLabel.toUpperCase()}</div>
                  <RptMono size={8} color={P.mute} style={{ display: 'block', marginTop: 6 }}>
                    {current.empty
                      ? 'Every expense has been reported'
                      : `Reporting period · to ${ACCOUNTANT.name}`}
                  </RptMono>
                </div>
                <ReportStatusChip sent={false} />
              </div>
            </div>
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', borderTop: `1px solid ${P.slate}`,
            }}>
              {[
                { k: 'Expenses', v: String(roll.count) },
                { k: 'Total', v: rMoney(roll.total) },
                { k: 'Originals', v: `${roll.docs} of ${roll.count}` },
              ].map((c, i) => (
                <div key={c.k} style={{
                  padding: '10px 12px 12px',
                  borderLeft: i > 0 ? `1px solid ${P.slate}` : 'none',
                }}>
                  <RptMono size={7.5}>{c.k}</RptMono>
                  <div style={{
                    fontFamily: T.display, fontSize: 15, fontWeight: 600, color: P.paper, marginTop: 3,
                  }}>{c.v}</div>
                </div>
              ))}
            </div>
            {/* Primary CTA — the most prominent action on the screen */}
            <div style={{ padding: 12, borderTop: `1px solid ${P.slate}` }}>
              <button onClick={() => onOpenMonthly('draft')} disabled={current.empty} style={{
                width: '100%', height: 50, cursor: current.empty ? 'default' : 'pointer',
                background: current.empty ? 'transparent' : P.gold,
                border: `1px solid ${current.empty ? P.slate : P.gold}`, color: current.empty ? P.mute : P.ink,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: '0.2em', textTransform: 'uppercase',
              }}>
                {current.empty ? 'Nothing to Report' : 'Review & Send'}
              </button>
            </div>
          </div>
        </div>

        {/* Reminder schedule */}
        <div style={{ padding: '6px 22px 18px' }}>
          <button onClick={() => setReminderSheet(true)} style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 12,
            background: 'transparent', border: `1px solid ${P.graphite}`,
            padding: '12px 14px', cursor: 'pointer', textAlign: 'left',
          }}>
            <Icon name="BellRing" size={16} color={P.gold} strokeWidth={1.5} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: T.body, fontSize: 12, color: P.paper }}>
                Expense Report Reminder
              </div>
              <RptMono size={8} style={{ display: 'block', marginTop: 3 }}>
                {reminder.id === 'off' ? 'Off' : `${reminder.label} · ${reminder.sub}`}
              </RptMono>
            </div>
            <RptMono size={8} color={P.gold}>Change</RptMono>
          </button>
        </div>

        {/* ── Sent history ── */}
        <div style={{ padding: '0 0 8px' }}><RowRule>SENT</RowRule></div>
        <div style={{ padding: '12px 22px 18px', display: 'grid', gap: 6 }}>
          {sentReports.map(p => (
            <button key={p.id} onClick={() => onOpenMonthly(p.id)} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12,
              background: P.graphite, border: 'none', padding: '13px 14px',
              cursor: 'pointer', textAlign: 'left',
            }}>
              <span style={{
                width: 34, height: 34, flexShrink: 0, border: `1px solid ${P.slate}`, background: P.ink,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name="FileSpreadsheet" size={16} color={P.gold} strokeWidth={1.5} />
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 600, color: P.paper }}>
                  {p.rangeLabel}
                </div>
                <RptMono size={8} style={{ display: 'block', marginTop: 3 }}>
                  {p.roll.count} expenses · {rMoney(p.roll.total)} · sent {p.sentOn}
                </RptMono>
              </div>
              <Icon name="arrow" size={14} color={P.gold} strokeWidth={1.5} />
            </button>
          ))}
        </div>

        <div style={{ padding: '14px 22px 28px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 5, height: 5, background: P.gold, flexShrink: 0 }} />
          <RptMono size={8.5} tracking="0.14em" style={{ lineHeight: 1.6 }}>
            Actions create records. Records create the <span style={{ color: P.gold }}>archive</span>.
          </RptMono>
        </div>
      </div>

      {/* Reminder frequency sheet */}
      {reminderSheet && (
        <ActionSheet
          eyebrow="EXPENSE REPORTS"
          title="Expense Report Reminder"
          onClose={() => setReminderSheet(false)}
          items={REPORT_REMINDER_OPTIONS.map(o => ({
            label: o.id === ReportStore.state.reminder ? `${o.label} ●` : o.label,
            icon: o.id === 'off' ? 'BellOff' : 'BellRing',
            action: () => ReportStore.set({ reminder: o.id }),
          }))}
        />
      )}
    </React.Fragment>
  );
}

Object.assign(window, { ReportsHome, RptBar, RptMono, ReportStatusChip });
