/* ============================================================================
   MOWDEW — Homeowner screens
   h_feed (Visit feed · HERO) · h_visit · h_inbox (invoice + pay) ·
   h_ledger (payment ledger) · h_summary (monthly summary)
   ========================================================================= */

/* ============================== VISIT FEED (HERO) ====================== */
function HomeFeed({ go, openFab, toast }) {
  const [arr, setArr] = React.useState('enroute');
  const [banner, setBanner] = React.useState('enroute');
  const advance = (n) => { setArr(n); if (n === 'enroute' || n === 'complete') setBanner(n); };
  return (
    <Screen padBottom={26} footer={<TabBar role="homeowner" active="h_feed" go={go} onFab={openFab} />}>
      <ArrivalBanner state={banner} onClose={() => setBanner(null)} onOpen={() => { setBanner(null); if (arr === 'complete') go('h_visit', { id: 'v2' }); else go('h_arrival'); }} />
      {/* header */}
      <div style={{ padding: '8px 18px 6px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <Logo size={34} />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12.5, color: 'var(--ink-500)', fontWeight: 600 }}>88 Crestline Ave</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 21, letterSpacing: '-0.02em' }}>Your visits</div>
        </div>
        <NotifBell count={notifUnreadCount('homeowner')} onClick={() => go('h_notifs')} />
        <button onClick={() => go('settings')} aria-label="Settings" style={{ width: 42, height: 42, borderRadius: '50%', border: '1px solid var(--ink-100)', background: '#fff', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon name="settings" size={20} /></button>
      </div>

      {/* provider strip — with a clear request action at top */}
      <div style={{ padding: '8px 18px 0' }}>
        <div className="card" style={{ padding: 13, background: 'var(--green-50)', borderColor: 'var(--green-100)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name="Diego Marta" size={42} ring />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 15 }}>Diego Marta</div>
              <div style={{ fontSize: 12.5, color: 'var(--green-800)' }}>Marta Lawn &amp; Pool · Weekly pool</div>
            </div>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: 'var(--green-700)' }}><Icon name="star" size={14} />4.9</span>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 11 }}>
            <button onClick={() => go('h_request')} style={{ flex: 1, minHeight: 42, border: 'none', background: 'var(--green-700)', color: '#fff', borderRadius: 12, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13.5, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: 'pointer', boxShadow: 'var(--shadow-green)' }}>
              <Icon name="calendar-check" size={17} />Reschedule
            </button>
            <button onClick={() => go('h_request')} style={{ flex: 1, minHeight: 42, border: '1px solid var(--green-100)', background: '#fff', color: 'var(--green-800)', borderRadius: 12, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13.5, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: 'pointer' }}>
              <Icon name="message" size={17} />Message
            </button>
          </div>
          <button onClick={() => go('h_request_work')} style={{ width: '100%', marginTop: 8, minHeight: 42, border: 'none', background: 'var(--aqua-500)', color: '#fff', borderRadius: 12, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13.5, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, cursor: 'pointer', boxShadow: 'var(--shadow-sm)' }}>
            <Icon name="camera" size={17} />Request work · snap a photo
          </button>
        </div>
      </div>

      {/* TODAY'S VISIT — live arrival arc (the verified-visit spine, real-time) */}
      <div style={{ padding: '12px 18px 0' }}>
        <SectionHead tone="aqua" icon="navigation" style={{ marginBottom: 10 }} meta={<button onClick={() => go('h_arrival')} style={{ border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 600, letterSpacing: '.06em', color: 'var(--aqua-700)' }}>SEE THE ARC</button>}>Today's visit</SectionHead>
        <EtaCard state={arr} onAdvance={advance} go={go} />
      </div>

      {/* live reschedule negotiation — Diego suggested a new time */}
      <div style={{ padding: '10px 18px 0' }}>
        <button onClick={() => go('h_resched')} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 11, padding: 12, borderRadius: 'var(--radius-lg)', border: '1px solid var(--yellow-100)', background: 'var(--yellow-50)', cursor: 'pointer', textAlign: 'left' }}>
          <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--yellow-500)', display: 'grid', placeItems: 'center', color: 'var(--ink-900)', flexShrink: 0 }}><Icon name="clock" size={19} /></span>
          <span style={{ flex: 1, minWidth: 0 }}>
            <span style={{ display: 'block', fontWeight: 700, fontSize: 13.5, color: 'var(--ink-900)' }}>Diego suggested a new time</span>
            <span style={{ display: 'block', fontSize: 12, color: 'var(--yellow-700)', fontWeight: 600, marginTop: 1 }}>Sat, May 23 · 9 AM — tap to accept or propose another</span>
          </span>
          <Icon name="chevron-right" size={18} style={{ color: 'var(--yellow-700)', flexShrink: 0 }} />
        </button>
      </div>

      {/* coming up — scheduled work waiting on your OK (heterogeneous timeline starts here) */}
      <div style={{ padding: '12px 18px 0' }}>
        <SectionHead tone="yellow" icon="filter" style={{ marginBottom: 10 }} meta="approve before anyone shows up">Coming up</SectionHead>
        <HomeWorkUpcoming toast={toast} />
      </div>

      {/* tagline banner */}
      <div style={{ padding: '12px 18px 2px' }}>
        <SectionHead tone="blue" icon="shield" meta={`${FEED.length} this month`}>Every visit, on the record</SectionHead>
        <div style={{ fontSize: 11.5, color: 'var(--ink-500)', marginTop: 6, lineHeight: 1.5 }}>GPS check-in proves when your pro arrived and left — no honor system.</div>
      </div>

      {/* timeline */}
      <div style={{ padding: '8px 18px 0', position: 'relative' }}>
        <div style={{ position: 'absolute', left: 36, top: 14, bottom: 10, width: 2, background: 'var(--ink-100)' }} />
        <div style={{ display: 'grid', gap: 16 }}>
          {(() => { const out = []; FEED.forEach((v, i) => { out.push(<FeedCard key={v.id} v={v} go={go} alt={i % 2 === 1} />); if (i === 1) out.push(<HomeWorkDone key="w-done" />); }); return out; })()}
        </div>
      </div>
    </Screen>
  );
}

function FeedCard({ v, go, alt = false }) {
  const s = SERVICE[v.svc];
  const sx = alt ? '-2' : '';
  return (
    <div style={{ display: 'flex', gap: 12, position: 'relative' }}>
      {/* node */}
      <div style={{ flexShrink: 0, zIndex: 1 }}>
        <span style={{ width: 36, height: 36, borderRadius: '50%', background: v.live ? 'var(--blue-500)' : 'var(--green-500)', display: 'grid', placeItems: 'center', color: '#fff', border: '3px solid var(--paper)', boxShadow: 'var(--shadow-sm)' }}>
          <Icon name={v.live ? 'pin' : 'check'} size={17} strokeWidth={2.6} />
        </span>
      </div>
      <div onClick={() => go(v.live ? 'h_visit' : 'h_recap', { id: v.id })} className="card" style={{ flex: 1, padding: 13, cursor: 'pointer', borderColor: v.live ? 'var(--blue-200,#8FD2F6)' : 'var(--ink-100)', boxShadow: v.live ? '0 0 0 3px var(--blue-50), var(--shadow-sm)' : 'var(--shadow-sm)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}>
          <PaperAvatar who="pro" size={30} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 14, lineHeight: 1.2 }}>{s.label}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>Marco · {v.date}</div>
          </div>
          {v.live ? <Chip tone="live" pulse>On-site</Chip> : <Chip tone="done" icon="check">Recap</Chip>}
        </div>
        {/* photos */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 7 }}>
          <PhotoTile scene={s.scene + '-before' + sx} label="BEFORE" height={84} />
          {v.live ? <PhotoTile scene="empty" label="AFTER" height={84} icon="camera">In progress</PhotoTile> : <PhotoTile scene={s.scene + '-after' + sx} label="AFTER" height={84} />}
        </div>
        {/* meta */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 11, fontSize: 12, color: 'var(--ink-500)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="clock" size={13} />{v.in}{v.out ? `–${v.out}` : ''}</span>
          <span style={{ fontWeight: 700, color: v.live ? 'var(--blue-700)' : 'var(--ink-700)' }}>{v.dur}</span>
          <span style={{ marginLeft: 'auto' }}><Mono tone="blue" icon="shield">AUTO CHECK-IN</Mono></span>
        </div>
      </div>
    </div>
  );
}

/* ============================== VISIT DETAIL =========================== */
function HomeVisit({ go, params }) {
  const v = FEED.find(x => x.id === params.id) || FEED[1];
  const s = SERVICE[v.svc];
  return (
    <Screen padBottom={28}>
      <TopBar title={s.label} subtitle={v.date} onBack={() => go('h_feed')} />
      {/* big before/after */}
      <div style={{ padding: '4px 18px 0' }}>
        <div style={{ display: 'grid', gap: 9 }}>
          <PhotoTile scene={s.scene + '-before'} label="BEFORE" time={v.in} height={150} radius="var(--radius-xl)" />
          <PhotoTile scene={v.live ? 'empty' : s.scene + '-after'} label="AFTER" time={v.out || ''} height={150} radius="var(--radius-xl)" icon="camera">{v.live ? 'In progress' : ''}</PhotoTile>
        </div>
      </div>

      {/* verified row */}
      <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(--blue-50)', display: 'grid', placeItems: 'center', color: 'var(--blue-700)' }}><Icon name="shield" size={20} strokeWidth={2.3} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 14.5 }}>Verified on-site</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>Auto check-in · {v.in}{v.out ? ` – ${v.out}` : ''} · {v.dur}</div>
          </div>
          <Mono tone="blue">40 FT</Mono>
        </div>
      </div>

      {/* map */}
      <div style={{ padding: '14px 18px 0' }}>
        <SectionHead tone="blue" icon="pin" style={{ marginBottom: 12 }}>Where Diego checked in</SectionHead>
        <MiniMap height={158} label={`88 Crestline Ave · ${v.in}`} />
      </div>

      {/* notes */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="green" icon="notes" style={{ marginBottom: 12 }}>Notes from Diego</SectionHead>
        <div className="card" style={{ padding: 15 }}>
          <div style={{ display: 'flex', gap: 11 }}>
            <Avatar name="Diego Marta" size={34} />
            <p style={{ fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink-700)' }}>{v.note}</p>
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* ============================== INVOICE INBOX + PAY ==================== */
function HomeInbox({ go, openFab, toast }) {
  const inv = INVOICES[0];
  const [paid, setPaid] = React.useState(false);
  const [rail, setRail] = React.useState(null);
  const [sheet, setSheet] = React.useState(false);
  const [share, setShare] = React.useState(false);

  const confirmPay = () => { setSheet(false); setPaid(true); toast(`Paid via ${RAIL[rail].label} · ${fmtMoney(inv.total)}`, 'green'); };

  return (
    <>
    <Screen padBottom={24} footer={<TabBar role="homeowner" active="h_inbox" go={go} onFab={openFab} />}>
      <TopBar title="Invoice inbox" subtitle={`From ${inv.from}`} onBack={() => go('h_feed')}
        right={<button onClick={() => setShare(true)} aria-label="Download or share the invoice PDF" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, minHeight: 40, padding: '0 13px', borderRadius: 12, border: '1px solid var(--ink-100)', background: '#fff', color: 'var(--ink-700)', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12.5, cursor: 'pointer' }}><Icon name="file" size={16} />PDF</button>} />

      {/* invoice hero */}
      <div style={{ padding: '4px 18px 0' }}>
        <div className="card card-feature" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '18px 18px 16px', background: paid ? 'var(--green-50)' : 'var(--yellow-50)', borderBottom: '1px solid var(--ink-100)' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Avatar name="Diego Marta" size={38} />
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14.5 }}>{inv.biz}</div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-500)', letterSpacing: '.04em' }}>{inv.id} · DUE {inv.due.toUpperCase()}</div>
                </div>
              </div>
              {paid ? <Chip tone="done" icon="check">Paid</Chip> : <Chip tone="soon">Due {inv.due}</Chip>}
            </div>
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)', fontWeight: 600 }}>{paid ? 'Paid in full' : 'Amount due'}</div>
              <Amount cents={inv.total} size={40} tone={paid ? 'paid' : 'plain'} />
            </div>
          </div>
          {/* lines — same verified visits */}
          <div style={{ padding: '6px 16px 8px' }}>
            <div style={{ padding: '10px 0 8px', display: 'flex', alignItems: 'center', gap: 7 }}>
              <Icon name="shield" size={15} style={{ color: 'var(--blue-700)' }} />
              <span style={{ fontSize: 12, color: 'var(--ink-500)' }}>4 visits in May · tap any to see its recap</span>
            </div>
            {inv.lines.map((v, i) => (
              <div key={i} onClick={() => go('h_recap', { id: FEED[i] ? FEED[i].id : 'v2' })} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 0', borderTop: '1px solid var(--ink-100)', cursor: 'pointer' }}>
                <PhotoTile scene="pool-after" height={38} radius={10} style={{ width: 46, flexShrink: 0 }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{v.label}</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} />{v.date} · Verified · see recap</div>
                </div>
                <Amount cents={v.cents} size={14} />
                <Icon name="chevron-right" size={16} style={{ color: 'var(--ink-300)', flexShrink: 0 }} />
              </div>
            ))}
          </div>
          {/* pay module — one amount (in header above) + 3 brand rails; no amount on the buttons */}
          {!paid ? (
            <div style={{ padding: '2px 16px 16px' }}>
              <div style={{ borderTop: '1px solid var(--ink-100)', paddingTop: 13, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 7 }}>
                <Icon name="wallet" size={16} style={{ color: 'var(--green-700)' }} />
                <span style={{ fontSize: 13, color: 'var(--ink-900)', fontWeight: 700 }}>Pay Diego in one tap</span>
              </div>
              <div style={{ display: 'grid', gap: 10 }}>
                {PROVIDER.rails.map(r => <RailPayButton key={r} rail={r} onClick={() => { setRail(r); setSheet(true); }} />)}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginTop: 13, fontSize: 11.5, color: 'var(--ink-500)' }}><Icon name="shield" size={13} />Mowdew never touches your money.</div>
            </div>
          ) : (
            <div style={{ padding: '2px 16px 16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'var(--green-50)', border: '1px solid var(--green-100)', borderRadius: 14, padding: '13px 14px' }}>
                <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--green-700)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}><Icon name="check" size={20} strokeWidth={2.6} /></span>
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14 }}>Paid via {RAIL[rail].label}</div><div style={{ fontSize: 12, color: 'var(--ink-500)' }}>Marked in your ledger — you won't pay this twice.</div></div>
                <RailChip rail={rail} size={28} />
              </div>
            </div>
          )}
        </div>
      </div>

      {/* never double-pay reassurance */}
      {!paid && (
      <div style={{ padding: '14px 18px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--blue-50)', border: '1px solid var(--blue-100)', borderRadius: 'var(--radius-lg)', padding: '12px 14px' }}>
          <Icon name="ledger" size={20} style={{ color: 'var(--blue-700)', flexShrink: 0 }} />
          <div style={{ fontSize: 12.5, color: 'var(--ink-700)' }}>This invoice isn't in your <b>ledger</b> as paid yet. Pay once here and it's marked — you'll never pay twice.</div>
        </div>
      </div>
      )}
      </Screen>

      {/* slim confirm sheet — rail already chosen; no re-pick, no amount on the button */}
      <Sheet open={sheet} onClose={() => setSheet(false)} title={`Pay with ${rail ? RAIL[rail].label : ''}`}>
        <div style={{ fontSize: 13.5, color: 'var(--ink-500)', marginBottom: 14, marginTop: -6 }}>Mowdew opens {rail ? RAIL[rail].label : 'the app'} with the amount and Diego prefilled — confirm there to finish.</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '13px 15px', background: 'var(--paper)', borderRadius: 14, border: '1px solid var(--ink-100)', marginBottom: 14 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 11 }}>
            <RailChip rail={rail || 'zelle'} size={38} />
            <span>
              <div style={{ fontWeight: 700, fontSize: 14.5 }}>{rail ? RAIL[rail].label : ''}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-500)' }}>{rail === 'zelle' ? PROVIDER.zelle : rail === 'venmo' ? PROVIDER.venmo : 'pay.mowdew.co/diego'}</div>
            </span>
          </span>
          <Amount cents={inv.total} size={20} />
        </div>
        <RailPayButton rail={rail || 'zelle'} height={56} size={21} onClick={confirmPay} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginTop: 12, fontSize: 12, color: 'var(--ink-500)' }}><Icon name="shield" size={14} />Mowdew never touches your money.</div>
      </Sheet>

      {/* share / download the same PDF Diego emailed */}
      <SharePdfSheet open={share} onClose={() => setShare(false)} inv={inv.id} toast={toast} />
    </>
  );
}

Object.assign(window, { HomeFeed, FeedCard, HomeVisit, HomeInbox });
