/* ============================================================================
   MOWDEW — Homeowner screens, part 2
   h_ledger (payment STATEMENT · distinct artifact: year control, filters,
   ledger-style entries) · h_summary (monthly recap)
   ========================================================================= */

/* ============================== PAYMENT LEDGER / STATEMENT ============= */
function HomeLedger({ go, openFab }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all'); // all | paid | due
  const [year, setYear] = React.useState(2026);

  const paidYTD = LEDGER.filter(r => r.status === 'paid').reduce((s, r) => s + r.cents, 0);
  const due = LEDGER.filter(r => r.status === 'unpaid').reduce((s, r) => s + r.cents, 0);
  const billed = paidYTD + due;
  const paidCount = LEDGER.filter(r => r.status === 'paid').length;
  const paidVisits = LEDGER.filter(r => r.status === 'paid').reduce((s, r) => s + r.visits, 0);
  const counts = { all: LEDGER.length, paid: paidCount, due: LEDGER.length - paidCount };
  const rows = LEDGER
    .filter(r => filter === 'all' || (filter === 'paid' ? r.status === 'paid' : r.status === 'unpaid'))
    .filter(r => r.month.toLowerCase().includes(q.toLowerCase()));

  const YearBtn = ({ dir, label }) => (
    <button onClick={() => setYear(y => y + dir)} aria-label={label}
      style={{ width: 30, height: 30, borderRadius: 8, border: 'none', background: 'transparent', color: 'var(--ink-500)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
      <Icon name={dir < 0 ? 'arrow-left' : 'arrow-right'} size={16} strokeWidth={2.4} />
    </button>
  );

  return (
    <Screen footer={<TabBar role="homeowner" active="h_ledger" go={go} onFab={openFab} />}>
      {/* statement header + year control */}
      <div style={{ padding: '8px 18px 8px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--ink-900)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}><Icon name="ledger" size={20} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.14em', color: 'var(--ink-500)' }}>PAYMENT STATEMENT</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 21, letterSpacing: '-0.02em' }}>Your ledger</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', background: '#fff', border: '1px solid var(--ink-200)', borderRadius: 11, padding: 2 }}>
          <YearBtn dir={-1} label="Previous year" />
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14.5, letterSpacing: '-0.01em', minWidth: 38, textAlign: 'center' }}>{year}</span>
          <YearBtn dir={1} label="Next year" />
        </div>
      </div>

      {/* statement summary band — distinct dark artifact */}
      <div style={{ padding: '0 18px' }}>
        <div style={{ background: 'var(--ink-900)', borderRadius: 'var(--radius-2xl)', padding: '16px 18px 15px', color: '#fff' }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.1em', color: 'rgba(255,255,255,.6)' }}>CLEARED · {year}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26, letterSpacing: '-0.03em', marginTop: 3 }}>{fmtMoney(paidYTD)}</div>
              <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,.6)', marginTop: 1 }}>{paidCount} months · {paidVisits} visits</div>
            </div>
            <div onClick={() => due && go('h_inbox')} style={{ flex: 1, paddingLeft: 16, borderLeft: '1px solid rgba(255,255,255,.16)', cursor: due ? 'pointer' : 'default' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.1em', color: due ? '#FF9E7D' : 'rgba(255,255,255,.6)' }}>STILL DUE</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26, letterSpacing: '-0.03em', marginTop: 3, color: due ? '#FFB59A' : '#fff' }}>{fmtMoney(due)}</div>
              <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,.6)', marginTop: 1 }}>{counts.due} invoice{counts.due === 1 ? '' : 's'} open</div>
            </div>
          </div>
          {/* collected vs billed */}
          <div style={{ marginTop: 13 }}>
            <div style={{ height: 6, borderRadius: 99, background: 'rgba(255,255,255,.16)', overflow: 'hidden' }}>
              <span style={{ display: 'block', height: '100%', width: `${Math.round((paidYTD / billed) * 100)}%`, background: 'var(--green-500)' }} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 7, fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.04em', color: 'rgba(255,255,255,.55)' }}>
              <span>{Math.round((paidYTD / billed) * 100)}% CLEARED</span><span>BILLED {fmtMoney(billed)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* controls: filter + search */}
      <div style={{ padding: '14px 18px 0', display: 'flex', gap: 7, background: 'transparent' }}>
        {[['all', 'All'], ['paid', 'Cleared'], ['due', 'Due']].map(([id, lb]) => {
          const on = filter === id;
          return (
            <button key={id} onClick={() => setFilter(id)} style={{ flex: 1, padding: '9px 6px', borderRadius: 11, border: '1px solid', borderColor: on ? 'transparent' : 'var(--ink-200)', cursor: 'pointer', fontSize: 13, fontWeight: 700, background: on ? 'var(--ink-900)' : '#fff', color: on ? '#fff' : 'var(--ink-700)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
              {lb}<span style={{ background: on ? 'rgba(255,255,255,.22)' : 'var(--ink-100)', color: on ? '#fff' : 'var(--ink-600,#6E6B60)', borderRadius: 99, minWidth: 17, height: 17, padding: '0 5px', fontSize: 10.5, fontWeight: 800, display: 'grid', placeItems: 'center' }}>{counts[id]}</span>
            </button>
          );
        })}
      </div>
      <div style={{ padding: '10px 18px 4px', position: 'relative' }}>
        <Icon name="search" size={18} style={{ position: 'absolute', left: 31, top: 21, color: 'var(--ink-300)' }} />
        <input value={q} onChange={e => setQ(e.target.value)} className="input" placeholder="Find a month — e.g. March" style={{ paddingLeft: 42 }} />
      </div>

      {/* ledger entries */}
      <div style={{ padding: '8px 18px 0', display: 'grid', gap: 9 }}>
        {rows.map(r => {
          const unpaid = r.status === 'unpaid';
          const [mo, yr] = r.month.split(' ');
          return (
            <div key={r.id} onClick={() => go(unpaid ? 'h_inbox' : 'h_summary', { id: r.id })} className="card" style={{ padding: '12px 13px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
              {/* date column */}
              <div style={{ width: 42, textAlign: 'center', flexShrink: 0 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15, letterSpacing: '-0.02em', lineHeight: 1, color: 'var(--ink-900)' }}>{mo.slice(0, 3)}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--ink-400,#A8A498)', marginTop: 2 }}>{yr}</div>
              </div>
              <span style={{ width: 1, alignSelf: 'stretch', background: 'var(--ink-100)' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ fontWeight: 700, fontSize: 14 }}>{r.visits} visits</span>
                  {unpaid ? <Chip tone="alert">Due</Chip> : <Chip tone="done" icon="check">Cleared</Chip>}
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-500)', display: 'flex', alignItems: 'center', gap: 5, marginTop: 3 }}>
                  {unpaid
                    ? <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{r.invoice}</span>
                    : <><RailChip rail={r.rail} size={15} /><span>Paid {r.paidOn} · {RAIL[r.rail].label}</span></>}
                </div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <Amount cents={r.cents} size={16} tone={unpaid ? 'due' : 'plain'} />
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.06em', color: unpaid ? 'var(--alert-700)' : 'var(--ink-400,#A8A498)', marginTop: 3 }}>{unpaid ? 'UNPAID' : 'CLEARED'}</div>
              </div>
            </div>
          );
        })}
        {rows.length === 0 && (
          <div style={{ textAlign: 'center', padding: '34px 0', color: 'var(--ink-400,#A8A498)' }}>
            <Sprout size={84} mood="zzz" />
            <div style={{ fontSize: 14, color: 'var(--ink-500)', marginTop: 6 }}>{q ? `No months match "${q}".` : 'Nothing here for this filter.'}</div>
          </div>
        )}
      </div>

      <div style={{ padding: '16px 18px 0', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, fontSize: 12, color: 'var(--ink-500)' }}>
        <Icon name="lock" size={14} style={{ color: 'var(--green-700)' }} />Cleared months lock — Mowdew won't let you pay one twice.
      </div>
    </Screen>
  );
}

/* ============================== MONTHLY SUMMARY ======================= */
function HomeSummary({ go, params }) {
  const r = LEDGER.find(x => x.id === params.id) || LEDGER[1];
  const visitDates = ['Apr 28', 'Apr 21', 'Apr 14', 'Apr 7'];
  return (
    <Screen padBottom={26} footer={
      <ActionBar>
        <button onClick={() => go('h_ledger')} className="btn btn-secondary" style={{ flex: 1 }}>Back to ledger</button>
        <button className="btn btn-primary" style={{ flex: 1 }}><Icon name="share" size={18} />Share recap</button>
      </ActionBar>}>
      <TopBar title={`${r.month} recap`} onBack={() => go('h_ledger')} />

      {/* hero recap card */}
      <div style={{ padding: '4px 18px 0' }}>
        <div style={{ background: 'var(--green-700)', borderRadius: 'var(--radius-3xl)', padding: '22px 22px 20px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', right: -16, top: -10, opacity: 0.9 }}><Sprout size={120} mood="wink" /></div>
          <Tag tone="green" onDark>Month, on the record</Tag>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 30, letterSpacing: '-0.025em', marginTop: 10, maxWidth: 220, lineHeight: 1.12 }}>
            {r.month.split(' ')[0]}: {r.visits} visits, {fmtMoney(r.cents).replace('.00', '')}, all paid.
          </div>
          <div style={{ display: 'flex', gap: 18, marginTop: 18 }}>
            {[['Visits', r.visits], ['Total', fmtMoney(r.cents).replace('.00', '')], ['Avg', fmtMoney(Math.round(r.cents / r.visits)).replace('.00', '')]].map(([k, v], i) => (
              <div key={i}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 22 }}>{v}</div>
                <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,.75)', fontWeight: 600 }}>{k}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* paid via */}
      <div style={{ padding: '14px 18px 0' }}>
        <div className="card" style={{ padding: '13px 14px', display: 'flex', alignItems: 'center', gap: 11 }}>
          <span style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--green-50)', display: 'grid', placeItems: 'center', color: 'var(--green-700)' }}><Icon name="check-circle" size={21} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 14.5 }}>Paid in full</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>{r.paidOn} · {r.invoice}</div>
          </div>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><RailChip rail={r.rail} size={26} /><span style={{ fontWeight: 700, fontSize: 13.5 }}>{RAIL[r.rail].label}</span></span>
        </div>
      </div>

      {/* visit list */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="green" icon="shield" style={{ marginBottom: 12 }}>The {r.visits} verified visits</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          {visitDates.slice(0, r.visits).map((d, i) => (
            <div key={i} onClick={() => go('h_visit', { id: 'v2' })} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 14px', borderTop: i ? '1px solid var(--ink-100)' : 'none', cursor: 'pointer' }}>
              <PhotoTile scene="pool-after" height={40} radius={10} style={{ width: 48, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>Pool service</div>
                <div style={{ fontSize: 11.5, color: 'var(--blue-700)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="shield" size={11} strokeWidth={2.4} />{d} · Verified</div>
              </div>
              <Amount cents={6500} size={14} />
            </div>
          ))}
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { HomeLedger, HomeSummary });
