// House detail page — hero, KPIs, monthly matrices, cleaning log, recent txns.
function HousePage({ store, houseId, onOpenTxn, onAddTxn }) {
  const { transactions, cleanings, houses, year, setYear } = store;
  const house = houses.find(h => h.id === houseId);
  if (!house) return null;

  const houseTxns = transactions.filter(t => t.houseId === houseId);
  const yearTxns = filterByYear(houseTxns, year);
  const income = yearTxns.filter(t => t.type === 'income').reduce((s, t) => s + t.amount, 0);
  const expense = yearTxns.filter(t => t.type === 'expense').reduce((s, t) => s + t.amount, 0);
  const net = income - expense;

  const houseCleanings = cleanings.filter(c => c.houseId === houseId)
    .filter(c => year === 'all' || Number(c.date.slice(0, 4)) === year);

  const currentYear = year === 'all' ? 2026 : year;
  const monthLabels = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

  // Build monthly-by-category matrix
  function buildMatrix(type, categories) {
    return categories.map(cat => {
      const cells = Array(12).fill(0);
      yearTxns.filter(t => t.type === type && t.category === cat)
        .forEach(t => { cells[Number(t.date.slice(5, 7)) - 1] += t.amount; });
      return { category: cat, cells, total: cells.reduce((a, b) => a + b, 0) };
    });
  }
  const incomeMatrix = buildMatrix('income', CATEGORIES.income).filter(r => r.total > 0);
  const expenseMatrix = buildMatrix('expense', CATEGORIES.expense).filter(r => r.total > 0);

  const incomeTotals = Array(12).fill(0);
  incomeMatrix.forEach(r => r.cells.forEach((v, i) => incomeTotals[i] += v));
  const expenseTotals = Array(12).fill(0);
  expenseMatrix.forEach(r => r.cells.forEach((v, i) => expenseTotals[i] += v));
  const netByMonth = incomeTotals.map((v, i) => v - expenseTotals[i]);

  // Approximate occupancy
  const nights = yearTxns.filter(t => t.type === 'income' && t.category !== 'Direct booking').length * 3.5;
  const daysInYear = year === 'all' ? 365 : (currentYear === 2026 ? 114 : 365);
  const occupancy = Math.min(100, Math.round((nights / daysInYear) * 100));

  return (
    <>
      <Topbar title={house.name}>
        <YearFilter value={year} onChange={setYear}/>
        <button className="btn">{Icon.download} Export</button>
        <button className="btn accent" onClick={() => onAddTxn({ houseId })}>{Icon.plus} New transaction</button>
      </Topbar>

      <div className="content" style={{ display: 'grid', gap: 20 }}>
        {/* Hero */}
        <div className="card" style={{ overflow: 'hidden', padding: 0 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '360px 1fr', alignItems: 'stretch' }}>
            <div style={{ padding: 18 }}>
              <HousePhoto house={house} size="lg"/>
            </div>
            <div style={{ padding: '24px 28px 24px 0', display: 'flex', flexDirection: 'column', gap: 14, justifyContent: 'center' }}>
              <div>
                <div className="row" style={{ gap: 10 }}>
                  <span className="dot" style={{ background: house.accentColor, width: 10, height: 10 }}/>
                  <span className="xs muted" style={{ letterSpacing: 0.4, textTransform: 'uppercase' }}>Property</span>
                </div>
                <h2 className="serif" style={{ fontSize: 36, margin: '4px 0 6px', fontWeight: 400, letterSpacing: '-0.02em' }}>{house.name}</h2>
                <div className="row muted small" style={{ gap: 6 }}>
                  {React.cloneElement(Icon.mapPin, { style: { width: 14, height: 14 } })}
                  <span>{house.address}</span>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 24, marginTop: 6 }}>
                <div>
                  <div className="xs muted">Cleaning rate</div>
                  <div className="tabular" style={{ fontWeight: 500, fontSize: 15, marginTop: 2 }}>${house.cleaningRate} <span className="xs muted" style={{ fontWeight: 400 }}>per turnover</span></div>
                </div>
                <div>
                  <div className="xs muted">Avg nightly</div>
                  <div className="tabular" style={{ fontWeight: 500, fontSize: 15, marginTop: 2 }}>${house.nightlyRate}</div>
                </div>
                <div>
                  <div className="xs muted">Occupancy {year === 'all' ? '' : currentYear}</div>
                  <div className="tabular" style={{ fontWeight: 500, fontSize: 15, marginTop: 2 }}>{occupancy}%</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* KPIs */}
        <div className="grid cols-4">
          <KpiCard label="Revenue" value={fmt$(income)} delta={null} sublabel={`${yearTxns.filter(t => t.type === 'income').length} bookings`}/>
          <KpiCard label="Expenses" value={fmt$(expense)} delta={null} sublabel="all categories"/>
          <KpiCard label="Net profit" value={fmt$(net)} delta={null} sublabel={income ? `${(net/income*100).toFixed(1)}% margin` : null}/>
          <KpiCard label="Cleanings" value={String(houseCleanings.length)} delta={null} sublabel={`${fmt$(houseCleanings.length * house.cleaningRate, { compact: true })} in fees`}/>
        </div>

        {/* Monthly income table */}
        <MonthlyMatrix
          title="Income by month"
          subtitle={`${currentYear} · ${CATEGORIES.income.length} sources`}
          color={house.accentColor}
          labels={monthLabels}
          rows={incomeMatrix}
          totals={incomeTotals}
          grandTotal={income}
        />

        {/* Monthly expense table */}
        <MonthlyMatrix
          title="Expenses by month"
          subtitle={`${currentYear} · ${expenseMatrix.length} categories`}
          color="var(--expense)"
          labels={monthLabels}
          rows={expenseMatrix}
          totals={expenseTotals}
          grandTotal={expense}
          netRow={netByMonth}
        />

        {/* Cleaning log + recent transactions */}
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 20 }}>
          <div className="card" style={{ display: 'flex', flexDirection: 'column' }}>
            <div className="card-header">
              <h3>Cleaning log</h3>
              <span className="xs muted">{houseCleanings.length} cleanings</span>
            </div>
            <div style={{ overflow: 'auto', maxHeight: 380 }}>
              <table className="table">
                <tbody>
                  {houseCleanings.slice(0, 12).map(c => (
                    <tr key={c.id}>
                      <td style={{ width: 70, color: 'var(--text-secondary)', fontSize: 12 }} className="tabular">{fmtDate(c.date)}</td>
                      <td>
                        <div style={{ fontWeight: 450, fontSize: 13 }}>{c.cleaner}</div>
                        <div className="xs muted">${c.cleaningRateSnapshot} fee{c.laundryAmount ? ` · $${c.laundryAmount} laundry` : ''}</div>
                      </td>
                      <td style={{ width: 28 }}>{c.laundryReceiptUrl && <ReceiptThumb small/>}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div className="card">
            <div className="card-header">
              <h3>Recent transactions</h3>
              <span className="xs muted">{yearTxns.length} total</span>
            </div>
            <div style={{ overflow: 'auto', maxHeight: 380 }}>
              <table className="table">
                <tbody>
                  {yearTxns.slice(0, 12).map(t => (
                    <tr key={t.id} onClick={() => onOpenTxn(t)}>
                      <td style={{ width: 70, color: 'var(--text-secondary)', fontSize: 12 }} className="tabular">{fmtDate(t.date)}</td>
                      <td>
                        <div style={{ fontWeight: 450, fontSize: 13 }}>{t.description}</div>
                        <div className="xs muted">{t.category}</div>
                      </td>
                      <td className="num tabular" style={{ width: 90, fontWeight: 500, color: t.type === 'income' ? 'var(--income)' : 'var(--text)' }}>
                        {t.type === 'income' ? '+' : '-'}{fmt$(t.amount)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { HousePage });
