// Printable Reports — what users see when they hit "Print PDF" or "Export".
// US Letter portrait (816 × 1056 at 96dpi). Editorial, paper-like.
// Three reports: Budget Summary, Seating Plan, Day-of Timeline.

// ─── Page shell ──────────────────────────────────────────────

const PAGE_W = 816, PAGE_H = 1056;
const PAGE_PAD = 64;

function ReportPage({ children, eyebrow, title, footerNote }) {
  const wedding = useWedding();
  const dayName = wedding.dayName;
  const monthDay = wedding.date.toLocaleDateString('en-US', { month: 'long', day: 'numeric' });
  const year = wedding.date.getFullYear();
  const cityLine = wedding.city.split(',')[0];
  return (
    <div style={{
      width: PAGE_W, height: PAGE_H,
      background: '#fdfaf2',       // slightly warmer than pure white, like nice stock
      boxShadow: '0 1px 0 rgba(40,28,12,0.04), 0 24px 60px -28px rgba(40,28,12,0.22)',
      position: 'relative',
      fontFamily: FONT_UI,
      color: W.ink,
      overflow: 'hidden',
    }}>
      {/* Letterhead */}
      <div style={{
        position: 'absolute', top: PAGE_PAD, left: PAGE_PAD, right: PAGE_PAD,
        display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{
            fontFamily: FONT_UI, fontSize: 9, fontWeight: 600,
            letterSpacing: 2.2, textTransform: 'uppercase', color: W.muted,
          }}>The Wedding of</div>
          <div style={{
            fontFamily: FONT_DISPLAY, fontSize: 30, fontWeight: 500,
            color: W.ink, letterSpacing: -0.3, lineHeight: 1, marginTop: 6,
          }}>
            {wedding.brides} <span style={{ fontStyle: 'italic' }}>&amp;</span> {wedding.groom}
          </div>
          <div style={{
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 13.5,
            color: W.ink2, marginTop: 6,
          }}>{dayName}, {monthDay} · {year} · {cityLine}</div>
        </div>

        <div style={{ textAlign: 'right' }}>
          <div style={{
            fontFamily: FONT_UI, fontSize: 9, fontWeight: 600,
            letterSpacing: 2.2, textTransform: 'uppercase', color: W.muted,
          }}>{eyebrow}</div>
          <div style={{
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 22,
            color: W.ink, marginTop: 6, letterSpacing: -0.1,
          }}>{title}</div>
        </div>
      </div>

      {/* Top hairline */}
      <div style={{
        position: 'absolute', top: PAGE_PAD + 96,
        left: PAGE_PAD, right: PAGE_PAD,
        height: 0.5, background: W.line,
      }}/>

      {/* Body */}
      <div style={{
        position: 'absolute',
        top: PAGE_PAD + 116, left: PAGE_PAD, right: PAGE_PAD,
        bottom: PAGE_PAD + 44,
        overflow: 'hidden',
      }}>{children}</div>

      {/* Footer */}
      <div style={{
        position: 'absolute', bottom: PAGE_PAD - 18,
        left: PAGE_PAD, right: PAGE_PAD,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontFamily: FONT_UI, fontSize: 9.5, color: W.muted,
        letterSpacing: 1.6, textTransform: 'uppercase',
      }}>
        <div>WeddingOS · Generated {REPORT_DATE}</div>
        <div>{footerNote || ''}</div>
      </div>
    </div>
  );
}

const REPORT_DATE = 'May 25 2026';

// ─── 1. Budget Summary ───────────────────────────────────────

function BudgetReport() {
  const b = useBudget();
  const pctSpent = b.total ? b.spent / b.total : 0;
  return (
    <ReportPage eyebrow="Report 01" title="Budget Summary" footerNote="Page 1 of 1">
      {/* Hero numbers row */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
        gap: 0, marginBottom: 32,
      }}>
        <BudgetStat label="Total budget"    value={fmt$(b.total)}/>
        <BudgetStat label="Committed"       value={fmt$(b.spent)}      tone="ink"/>
        <BudgetStat label="Paid to date"    value={fmt$(b.paidToDate)} tone="ink"/>
        <BudgetStat label="Remaining"       value={fmt$(b.remaining)}  tone={b.remaining < 0 ? 'red' : 'clay'} last/>
      </div>

      {/* Contributors bar */}
      <div style={{ marginBottom: 30 }}>
        <ReportLabel>Funding</ReportLabel>
        <div style={{
          height: 22, borderRadius: 4, overflow: 'hidden',
          display: 'flex', marginTop: 10,
          border: `0.5px solid ${W.line}`,
        }}>
          {BUDGET.contributors.map((c) => (
            <div key={c.name} style={{
              flex: c.amount, background: c.color, height: '100%',
            }}/>
          ))}
        </div>
        <div style={{
          display: 'flex', gap: 24, marginTop: 12, flexWrap: 'wrap',
        }}>
          {BUDGET.contributors.map((c) => (
            <div key={c.name} style={{
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <span style={{
                width: 9, height: 9, borderRadius: 2, background: c.color,
              }}/>
              <span style={{ fontSize: 11.5, color: W.ink2 }}>
                <span style={{ color: W.ink, fontWeight: 500 }}>{c.name}</span>
                {' · '}{fmt$(c.amount)}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Categories table */}
      <ReportLabel>Categories</ReportLabel>
      <table style={{
        width: '100%', borderCollapse: 'collapse', marginTop: 10,
        fontSize: 12, color: W.ink,
      }}>
        <thead>
          <tr style={{ borderBottom: `0.5px solid ${W.line}` }}>
            <th style={budgetTh('left')}>Category</th>
            <th style={budgetTh('right')}>Planned</th>
            <th style={budgetTh('right')}>Spent</th>
            <th style={budgetTh('right')}>Remaining</th>
            <th style={budgetTh('right')}>Status</th>
          </tr>
        </thead>
        <tbody>
          {b.categories.map((c) => {
            const remaining = c.planned - c.spent;
            const over = remaining < 0;
            return (
              <tr key={c.name} style={{
                borderBottom: `0.5px solid ${W.lineSoft}`,
              }}>
                <td style={{ padding: '11px 0', fontSize: 13 }}>
                  <span style={{ fontFamily: FONT_DISPLAY, fontSize: 15.5, color: W.ink }}>
                    {c.name}
                  </span>
                  {c.note && (
                    <span style={{ color: W.red, fontSize: 11, marginLeft: 8, fontStyle: 'italic' }}>
                      · {c.note}
                    </span>
                  )}
                </td>
                <td style={budgetTd('right')}>{fmt$(c.planned)}</td>
                <td style={budgetTd('right')}>{fmt$(c.spent)}</td>
                <td style={{ ...budgetTd('right'), color: over ? W.red : W.ink2 }}>
                  {over ? '−' : ''}{fmt$(Math.abs(remaining))}
                </td>
                <td style={budgetTd('right')}>
                  <ReportStatus status={c.status}/>
                </td>
              </tr>
            );
          })}
          <tr style={{ borderTop: `1.5px solid ${W.ink}` }}>
            <td style={{ padding: '14px 0', fontFamily: FONT_DISPLAY, fontSize: 17, color: W.ink }}>
              Total
            </td>
            <td style={{ ...budgetTd('right'), fontWeight: 600 }}>{fmt$(b.total)}</td>
            <td style={{ ...budgetTd('right'), fontWeight: 600 }}>{fmt$(b.spent)}</td>
            <td style={{ ...budgetTd('right'), fontWeight: 600, color: b.remaining < 0 ? W.red : W.clay }}>
              {fmt$(b.remaining)}
            </td>
            <td style={budgetTd('right')}>
              <span style={{
                fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
                letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
              }}>{Math.round(pctSpent * 100)}% spent</span>
            </td>
          </tr>
        </tbody>
      </table>

      {/* Footer note */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 12.5,
        color: W.muted, lineHeight: 1.5,
      }}>
        {b.statusCounts.over > 0
          ? `${b.categories.filter(c => c.status === 'over').map(c => c.name).join(', ')} ${b.statusCounts.over === 1 ? 'is' : 'are'} currently over plan — total ${fmt$(b.overspend)} above. Consider trimming or reallocating.`
          : b.spent > 0
            ? `On track. ${fmt$(b.remaining)} remaining of your ${fmt$(b.total)} plan.`
            : `Your plan is set. Start tracking spend as deposits go out.`}
      </div>
    </ReportPage>
  );
}

function BudgetStat({ label, value, tone = 'ink', last }) {
  return (
    <div style={{
      borderRight: last ? 'none' : `0.5px solid ${W.line}`,
      paddingRight: 14, paddingLeft: 0,
    }}>
      <div style={{
        fontFamily: FONT_UI, fontSize: 9.5, fontWeight: 600,
        letterSpacing: 1.6, textTransform: 'uppercase', color: W.muted,
      }}>{label}</div>
      <div style={{
        fontFamily: FONT_DISPLAY, fontSize: 28,
        color: tone === 'red' ? W.red : tone === 'clay' ? W.clay : W.ink,
        letterSpacing: -0.4, marginTop: 6, lineHeight: 1,
      }}>{value}</div>
    </div>
  );
}

function ReportLabel({ children }) {
  return (
    <div style={{
      fontFamily: FONT_UI, fontSize: 9.5, fontWeight: 600,
      letterSpacing: 1.8, textTransform: 'uppercase', color: W.muted,
    }}>{children}</div>
  );
}

function ReportStatus({ status }) {
  const map = {
    paid:    { label: 'Paid',     color: W.green },
    partial: { label: 'Partial',  color: W.clay },
    over:    { label: 'Over',     color: W.red },
    open:    { label: 'Open',     color: W.muted },
  };
  const s = map[status] || map.open;
  return (
    <span style={{
      fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
      letterSpacing: 1.4, textTransform: 'uppercase', color: s.color,
    }}>{s.label}</span>
  );
}

const budgetTh = (align) => ({
  padding: '8px 0', textAlign: align,
  fontFamily: FONT_UI, fontSize: 9, fontWeight: 600,
  letterSpacing: 1.6, textTransform: 'uppercase', color: W.muted,
});
const budgetTd = (align) => ({
  padding: '11px 0', textAlign: align,
  fontFamily: FONT_MONO, fontSize: 12.5, color: W.ink,
});

// ─── 2. Seating Plan ─────────────────────────────────────────

function SeatingReport() {
  const t = useTables();
  const tables = t.all;
  const seated = t.filledSeats;
  return (
    <ReportPage eyebrow="Report 02" title="Seating Plan" footerNote="Page 1 of 1">
      {/* Top stats */}
      <div style={{
        display: 'flex', gap: 36, marginBottom: 26,
      }}>
        <BudgetStat label="Tables"    value={tables.length}/>
        <BudgetStat label="Seated"    value={seated}/>
        <BudgetStat label="Unassigned" value={t.unassigned}/>
        <BudgetStat label="Service"   value="Plated" last/>
      </div>

      {/* Floor plan note */}
      <ReportLabel>Hollow Tree Barn · Reception Layout</ReportLabel>

      {/* Mini visual: stage + dance floor + tables in grid */}
      <div style={{
        marginTop: 12, padding: 18,
        border: `0.5px solid ${W.line}`, borderRadius: 6,
        background: '#fbf6ea',
        position: 'relative',
        height: 200,
      }}>
        {/* Stage */}
        <div style={{
          position: 'absolute', left: 18, right: 18, top: 18,
          height: 22, border: `0.5px solid ${W.clay}`, borderRadius: 3,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: FONT_UI, fontSize: 9, letterSpacing: 1.8,
          color: W.clay, textTransform: 'uppercase', background: '#f3e7d4',
        }}>Head Table · Stage</div>

        {/* Dance floor */}
        <div style={{
          position: 'absolute', left: '50%', top: 56, transform: 'translateX(-50%)',
          width: 100, height: 70, borderRadius: 4,
          border: `0.5px dashed ${W.muted}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: FONT_UI, fontSize: 9, letterSpacing: 1.6,
          color: W.muted, textTransform: 'uppercase',
        }}>Dance floor</div>

        {/* Table dots around floor */}
        {[
          { id: 2, left: 60,   top: 60 },
          { id: 3, left: 60,   top: 110 },
          { id: 4, left: 60,   top: 160 },
          { id: 5, left: 145,  top: 160 },
          { id: 6, left: 245,  top: 160 },
          { id: 7, left: 345,  top: 160 },
          { id: 8, left: 425,  top: 160 },
          { id: 9, left: 425,  top: 110 },
          { id: 10, left: 425, top: 60 },
          { id: 11, left: 245, top: 75 },
        ].map((t) => (
          <div key={t.id} style={{
            position: 'absolute', left: t.left, top: t.top,
            width: 24, height: 24, borderRadius: 999,
            border: `1px solid ${W.clay}`,
            background: '#fdfaf2',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: FONT_DISPLAY, fontSize: 11, fontWeight: 500, color: W.ink,
          }}>{t.id}</div>
        ))}

        {/* Entry */}
        <div style={{
          position: 'absolute', left: '50%', bottom: 6, transform: 'translateX(-50%)',
          fontFamily: FONT_UI, fontSize: 8.5, letterSpacing: 1.6,
          color: W.muted, textTransform: 'uppercase',
        }}>⤓ Entry</div>
      </div>

      {/* Tables list — two columns */}
      <div style={{ marginTop: 22, marginBottom: 10 }}>
        <ReportLabel>Tables &amp; Guests</ReportLabel>
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 32, rowGap: 14,
      }}>
        {tables.map((t) => (
          <div key={t.id} style={{
            borderTop: `0.5px solid ${W.line}`, paddingTop: 10,
          }}>
            <div style={{
              display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
              marginBottom: 4,
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{
                  fontFamily: FONT_DISPLAY, fontSize: 16, fontWeight: 500, color: W.ink,
                }}>
                  <span style={{ color: TABLE_KIND_COLORS[t.kind] || W.clay }}>{t.number}</span>
                  {' · '}{t.name}
                </span>
              </div>
              <span style={{
                fontFamily: FONT_MONO, fontSize: 10, color: W.muted,
              }}>{t.seats.filter(Boolean).length}/{t.capacity}</span>
            </div>
            <div style={{
              fontFamily: FONT_UI, fontSize: 11.5, color: W.ink2, lineHeight: 1.55,
            }}>
              {t.seats.filter(Boolean).join(' · ') || (
                <span style={{ color: W.muted, fontStyle: 'italic' }}>No assignments yet</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </ReportPage>
  );
}

// ─── 3. Day-of Timeline ──────────────────────────────────────

function DayOfReport() {
  return (
    <ReportPage eyebrow="Report 03" title="Wedding Day Timeline" footerNote="Page 1 of 1">
      {/* Sunrise / ceremony / sunset */}
      <div style={{
        display: 'flex', gap: 36, marginBottom: 24,
      }}>
        <BudgetStat label="Sunrise"   value="7:01"/>
        <BudgetStat label="Ceremony"  value="4:00" tone="clay"/>
        <BudgetStat label="Sunset"    value="6:48"/>
        <BudgetStat label="Forecast"  value="62° clear" last/>
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 36,
      }}>
        {/* Timeline */}
        <div>
          <ReportLabel>Schedule</ReportLabel>
          <div style={{ marginTop: 14, position: 'relative' }}>
            <div style={{
              position: 'absolute', left: 76, top: 6, bottom: 6,
              width: 0.5, background: W.line,
            }}/>
            {DAYOF_TIMELINE.map((e, i) => (
              <ReportTimelineRow key={i} event={e}/>
            ))}
          </div>
        </div>

        {/* Right column */}
        <div>
          <ReportLabel>Emergency contacts</ReportLabel>
          <div style={{ marginTop: 12 }}>
            {[
              { role: 'Day-of planner', name: 'Nina Brock',  phone: '(415) 555-0142' },
              { role: 'Maid of honor',  name: 'Amelia Park', phone: '(310) 555-0188' },
              { role: 'Venue manager',  name: 'Lia Marsh',   phone: '(707) 555-0119' },
              { role: 'Officiant',      name: 'Father Joel', phone: '(707) 555-0193' },
              { role: 'Photographer',   name: 'Noa Hart',    phone: '(415) 555-0166' },
            ].map((c) => (
              <div key={c.name} style={{
                padding: '10px 0', borderBottom: `0.5px solid ${W.lineSoft}`,
              }}>
                <div style={{
                  fontFamily: FONT_UI, fontSize: 9, fontWeight: 600,
                  letterSpacing: 1.6, textTransform: 'uppercase', color: W.muted,
                }}>{c.role}</div>
                <div style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                  marginTop: 3,
                }}>
                  <span style={{ fontFamily: FONT_DISPLAY, fontSize: 14.5, color: W.ink }}>
                    {c.name}
                  </span>
                  <span style={{ fontFamily: FONT_MONO, fontSize: 10.5, color: W.ink2 }}>
                    {c.phone}
                  </span>
                </div>
              </div>
            ))}
          </div>

          {/* Rain plan */}
          <div style={{
            marginTop: 22, padding: 14,
            border: `0.5px solid ${W.line}`, borderRadius: 4,
            background: '#fbf6ea',
          }}>
            <ReportLabel>If it rains</ReportLabel>
            <div style={{
              fontFamily: FONT_DISPLAY, fontSize: 14, color: W.ink, marginTop: 6,
              lineHeight: 1.35,
            }}>Ceremony moves to the covered terrace.</div>
            <div style={{
              fontFamily: FONT_UI, fontSize: 10.5, color: W.ink2, marginTop: 6, lineHeight: 1.5,
            }}>
              Lia (venue) confirms by 11 AM. Florist will re-stage the arbor under
              the eastern overhang. Same start time.
            </div>
          </div>
        </div>
      </div>
    </ReportPage>
  );
}

function ReportTimelineRow({ event }) {
  const color = KIND_COLORS[event.kind] || W.clay;
  const isHero = event.hero;
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '64px 1fr', gap: 14,
      padding: '7px 0', alignItems: 'flex-start', position: 'relative',
    }}>
      <div style={{
        textAlign: 'right',
        fontFamily: FONT_DISPLAY, fontSize: isHero ? 14.5 : 13,
        color: isHero ? W.ink : W.ink2, paddingTop: 2,
      }}>{event.time}</div>

      <div style={{
        position: 'absolute', left: 76, top: 10,
        width: isHero ? 10 : 7, height: isHero ? 10 : 7, borderRadius: 999,
        background: isHero ? color : '#fdfaf2',
        border: `1.5px solid ${color}`,
        transform: 'translateX(-50%)',
      }}/>

      <div style={{ paddingLeft: 18 }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: isHero ? 13 : 12, fontWeight: 500,
          color: W.ink, lineHeight: 1.3,
        }}>{event.title}</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10.5, color: W.muted, marginTop: 2,
        }}>{event.where}</div>
        {event.note && (
          <div style={{
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 11.5,
            color: W.ink2, marginTop: 4, lineHeight: 1.4,
          }}>{event.note}</div>
        )}
      </div>
    </div>
  );
}

// Render any list of React elements into a `.wos-print-portal` div,
// call window.print(), then clean up. The print stylesheet hides everything
// outside the portal, so output is scoped exactly to what's mounted.
function printReactNodes(nodes) {
  const portal = document.createElement('div');
  portal.className = 'wos-print-portal';
  document.body.appendChild(portal);

  const root = ReactDOM.createRoot
    ? ReactDOM.createRoot(portal)
    : null;

  const cleanup = () => {
    try {
      if (root) root.unmount();
      else if (ReactDOM.unmountComponentAtNode) ReactDOM.unmountComponentAtNode(portal);
    } catch {}
    portal.remove();
    window.removeEventListener('afterprint', cleanup);
  };
  window.addEventListener('afterprint', cleanup);

  const tree = (
    <StoreProvider>
      {nodes}
    </StoreProvider>
  );
  if (root) root.render(tree);
  else ReactDOM.render(tree, portal);

  // Give React a tick to paint, then print.
  setTimeout(() => {
    window.print();
    // Some browsers don't fire afterprint reliably; safety cleanup.
    setTimeout(cleanup, 1500);
  }, 80);
}

// Print all 3 reports. Used from Settings, Desktop Reports, mobile Day-of.
function printAllReports() {
  printReactNodes(
    <React.Fragment>
      <BudgetReport/>
      <SeatingReport/>
      <DayOfReport/>
    </React.Fragment>
  );
}

// Print a single report by id: 'budget' | 'seating' | 'dayof'
function printReport(id) {
  const comp = id === 'budget'  ? <BudgetReport/>
            : id === 'seating' ? <SeatingReport/>
            : id === 'dayof'   ? <DayOfReport/>
            : null;
  if (!comp) { printAllReports(); return; }
  printReactNodes(comp);
}

Object.assign(window, {
  BudgetReport, SeatingReport, DayOfReport, PAGE_W, PAGE_H,
  printReactNodes, printAllReports, printReport,
});
