/* ============================================================================
   MOWDEW LIVE DEMO — the three phone shells
   Each shell maps the App.html screen ids onto its tabs. Static tabs render
   the REAL app screens (ProDone, ProNotes, Settings, OwnerCustomersM);
   synced tabs render app-spec clones from mowdew-demo-tabs.jsx, wired to
   the shared `world`.
   ========================================================================= */

/* shared header for synced home screens: brand + self portrait + bell */
function DmHeader({ persona, world, act, sub, title }) {
  return (
    <div style={{ padding: '8px 18px 6px', display: 'flex', alignItems: 'center', gap: 12 }}>
      <Logo size={34} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.5, color: 'var(--ink-500)', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 21, letterSpacing: '-0.02em' }}>{title}</div>
      </div>
      <PaperAvatar who={persona === 'home' ? 'home' : persona} size={42} />
      <DemoBell persona={persona} world={world} act={act} />
    </div>
  );
}

/* ============================ PRO PHONE ============================== */
function ProTodayDemo({ world, act, nav }) {
  const v = world.visit;
  const chem = world.chem;
  return (
    <Screen padBottom={24} footer={<TabBar role="provider" active="pro_today" go={nav} onFab={() => {}} />}>
      <DmHeader persona="pro" world={world} act={act} sub={`Tue, May 12 · ${v === 'done' ? 2 : 1} of 5 done`} title="Hi, Marco" />

      {/* route map — the same component as the main prototype */}
      <div style={{ padding: '4px 18px 0' }}><RouteMap height={130} onExpand={() => {}} /></div>

      {/* THE interactive stop */}
      <div style={{ padding: '14px 18px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
          {v === 'scheduled' && <DmMark tone="yellow">UP NEXT</DmMark>}
          {v === 'driving' && <DmMark tone="blue" pulse>EN ROUTE</DmMark>}
          {v === 'onsite' && <DmMark tone="blue" pulse>ON-SITE NOW</DmMark>}
          {v === 'done' && <DmMark tone="green">DONE</DmMark>}
        </div>
        <div className="card" style={{ padding: 14, minWidth: 0, boxSizing: 'border-box', borderColor: v === 'onsite' ? 'var(--blue-300)' : 'var(--ink-100)', boxShadow: v === 'onsite' ? '0 0 0 3px var(--blue-50), var(--shadow-md)' : 'var(--shadow-sm)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
            <IconBadge icon="droplet" tone="aqua" size={42} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Crestline Ave pool</div>
              <div style={{ fontSize: 12, color: 'var(--ink-500)' }}>Pool service · weekly</div>
            </div>
          </div>
          <ProAddedWork world={world} />
          {/* property tools — REAL app screens (equipment always; recap once done) */}
          <div style={{ display: 'flex', gap: 8, marginTop: 11 }}>
            <button onClick={() => nav('pro_equipment', { id: 'c2' })} className="btn btn-secondary" style={{ flex: 1, minHeight: 40, fontSize: 12.5 }}><Icon name="flask" size={15} />Equipment</button>
            {v === 'done' && <button onClick={() => nav('pro_recap', { id: 'v2' })} className="btn btn-secondary" style={{ flex: 1, minHeight: 40, fontSize: 12.5 }}><Icon name="camera" size={15} />Visit recap</button>}
          </div>

          {v === 'scheduled' && (
            <div style={{ marginTop: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, marginBottom: 11, flexWrap: 'wrap' }}>
                <Icon name="clock" size={14} style={{ color: 'var(--yellow-700)', flexShrink: 0 }} />
                <span style={{ fontWeight: 600, color: 'var(--ink-700)', whiteSpace: 'nowrap' }}>ETA 10:05 AM</span>
                <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: 'var(--blue-700)', whiteSpace: 'nowrap' }}><Icon name="target" size={13} strokeWidth={2.4} />Auto check-in armed</span>
              </div>
              <button onClick={act.startDrive} className="btn btn-blue btn-block" style={{ minHeight: 46 }}><Icon name="navigation" size={18} />Start driving</button>
            </div>
          )}

          {v === 'driving' && (
            <div style={{ marginTop: 12, background: 'var(--blue-50)', border: '1px solid var(--blue-100)', borderRadius: 13, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 11 }}>
              <span style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--blue-500)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}><Icon name="navigation" size={18} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--blue-700)' }}>Driving to Crestline Ave</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-600,#6E6B60)' }}>Geofence will check you in on arrival</div>
              </div>
            </div>
          )}

          {(v === 'onsite' || v === 'done') && (
            <div style={{ marginTop: 12 }}>
              <div style={{ background: 'var(--ink-900)', borderRadius: 16, padding: '13px 14px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.1em', color: 'rgba(255,255,255,.6)', whiteSpace: 'nowrap' }}>{v === 'done' ? 'ON-SITE TIME' : 'ON-SITE TIMER'}</span>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: '#9FD6F8', fontSize: 10.5, fontWeight: 700, whiteSpace: 'nowrap' }}><Icon name="shield" size={12} strokeWidth={2.4} />In at {world.checkInAt}</span>
                </div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 36, letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums', lineHeight: 1.1, marginTop: 6 }}>{dmClock(world.sec)}</div>
              </div>

              {v === 'onsite' && (
                <>
                  {!chem || chem === 'scanning' ? (
                    <div onClick={chem === 'scanning' ? undefined : act.scanChem} style={{ cursor: chem === 'scanning' ? 'default' : 'pointer', border: '1.5px dashed var(--aqua-200)', background: 'var(--aqua-50)', borderRadius: 14, padding: 13, display: 'flex', alignItems: 'center', gap: 12, marginTop: 10 }}>
                      <span style={{ width: 42, height: 42, borderRadius: 12, background: chem === 'scanning' ? 'var(--aqua-700)' : 'var(--aqua-500)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}>
                        {chem === 'scanning' ? <span className="tn-pulse" style={{ display: 'inline-flex' }}><Icon name="sparkle" size={21} /></span> : <Icon name="flask" size={21} />}
                      </span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14.5 }}>{chem === 'scanning' ? 'Reading test strip…' : 'Snap the pH test'}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--aqua-700)' }}>{chem === 'scanning' ? 'Matching colors to the chart' : 'Photo → Mowdew reads pH, chlorine & alkalinity'}</div>
                      </div>
                      {chem !== 'scanning' && <Icon name="camera" size={20} style={{ color: 'var(--aqua-700)', flexShrink: 0 }} />}
                    </div>
                  ) : (
                    <div className="card" style={{ padding: '4px 13px', marginTop: 10, borderColor: 'var(--aqua-100)' }}>
                      <ChemReadout rkey="ph" value={chem.ph} />
                      <div style={{ borderTop: '1px solid var(--ink-100)' }} />
                      <ChemReadout rkey="cl" value={chem.cl} sub="Topped up on-site" />
                    </div>
                  )}
                  {chem && chem !== 'scanning' && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11.5, color: 'var(--aqua-700)', fontWeight: 700, padding: '8px 2px 0' }}>
                      <Icon name="check-circle" size={14} style={{ flexShrink: 0 }} />Shared with the homeowner
                    </div>
                  )}
                  <button onClick={act.checkOut} className="btn btn-blue btn-block" style={{ minHeight: 46, marginTop: 10 }}><Icon name="navigation" size={18} />Drive to next stop</button>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11.5, color: 'var(--ink-500)', padding: '8px 2px 0' }}>
                    <Icon name="target" size={13} style={{ color: 'var(--blue-700)', flexShrink: 0 }} />Leaving the property clocks you out automatically — same as check-in.
                  </div>
                </>
              )}

              {v === 'done' && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 10, fontSize: 12, color: 'var(--ink-500)', whiteSpace: 'nowrap' }}>
                  <Icon name="clock" size={14} style={{ flexShrink: 0 }} /> {world.checkInAt} – {world.checkOutAt} · {dmClock(world.sec)}
                  <span style={{ marginLeft: 'auto' }}><DmMark tone="blue">AUTO CHECK-IN</DmMark></span>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* field note — routes to the office, kicks off the chat storyline */}
      {(v === 'onsite' || v === 'done') && (
        <div style={{ padding: '14px 18px 0' }}>
          <SectionHead tone="green" icon="notes" style={{ marginBottom: 10 }} meta={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap' }}><Icon name="lock" size={12} />to the office</span>}>Field note</SectionHead>
          <div className="card" style={{ padding: 14 }}>
            <p style={{ fontSize: 13, color: 'var(--ink-700)', lineHeight: 1.5, margin: 0 }}>“Emma asked about a monthly filter deep-clean — routing to you.”</p>
            {!world.note && <button onClick={act.sendNote} className="btn btn-secondary btn-block" style={{ minHeight: 42, marginTop: 11 }}><Icon name="send" size={16} />Send to office</button>}
            {world.note && world.note !== 'closed' && <div style={{ marginTop: 10 }}><DmMark tone="yellow" pulse>SENT · WITH THE OFFICE</DmMark></div>}
            {world.note === 'closed' && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, background: 'var(--green-50)', borderRadius: 11, padding: '9px 12px', fontSize: 12, fontWeight: 600, color: 'var(--green-800)' }}>
                <Icon name="check-circle" size={15} style={{ flexShrink: 0 }} />{world.noteYes ? 'Resolved — deep-clean added to this stop.' : 'Resolved — Emma passed for now.'}
              </div>
            )}
          </div>
        </div>
      )}

      {/* the rest of today — same quiet numbered list as the main prototype */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="ink" icon="route" style={{ marginBottom: 10 }} meta={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, whiteSpace: 'nowrap' }}><Icon name="target" size={12} strokeWidth={2.4} />auto check-in on</span>}>The rest of today</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          {[
            { n: <Icon name="check" size={14} strokeWidth={3} />, done: true, label: 'Oak Ridge Ct garden', meta: '9:06 – 9:41 AM' },
            { n: 3, label: 'Brookhaven Ln garden', meta: 'ETA 11:15 AM' },
            { n: 4, label: 'Marin Vista pool', meta: 'ETA 2:30 PM' },
          ].map((r, i) => (
            <div key={r.label} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderTop: i ? '1px solid var(--ink-100)' : 'none', opacity: r.done ? 0.55 : 1 }}>
              <span style={{ width: 26, height: 26, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', background: r.done ? 'var(--green-50)' : 'var(--ink-50)', color: r.done ? 'var(--green-700)' : 'var(--ink-600,#6E6B60)', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 12 }}>{r.n}</span>
              <div style={{ flex: 1, minWidth: 0, fontWeight: 700, fontSize: 13.5, color: r.done ? 'var(--ink-500)' : 'var(--ink-900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.label}</div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600, color: 'var(--ink-400,#A8A498)', whiteSpace: 'nowrap', flexShrink: 0 }}>{r.meta}</span>
            </div>
          ))}
          <div style={{ padding: '8px 14px 6px', borderTop: '1px solid var(--ink-100)', fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.12em', color: 'var(--ink-400,#A8A498)' }}>NEXT WEEK</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '4px 14px 12px' }}>
            <span style={{ width: 26, height: 26, borderRadius: '50%', flexShrink: 0, display: 'grid', placeItems: 'center', background: 'var(--aqua-50)', color: 'var(--aqua-700)' }}><Icon name="droplet" size={14} strokeWidth={2.4} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Crestline Ave pool</div>
              {world.nextVisit.moved && <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.05em', color: 'var(--yellow-700)', marginTop: 2, whiteSpace: 'nowrap' }}>MOVED · WAS MON, MAY 18</div>}
            </div>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600, color: world.nextVisit.moved ? 'var(--ink-700)' : 'var(--ink-400,#A8A498)', whiteSpace: 'nowrap', flexShrink: 0 }}>{world.nextVisit.when}</span>
          </div>
        </div>
      </div>
    </Screen>
  );
}

function ProDemoPhone({ world, act, toast, say }) {
  const [tab, setTab] = React.useState('pro_today');
  const [autoCk, setAutoCk] = React.useState(true);
  const [screen, setScreen] = React.useState(null); // full-screen push: equipment / recap (REAL app components)
  const nav = (scr, params) => {
    const t = scr === 'pro_visit' ? 'pro_today' : scr;
    if (['pro_equipment', 'pro_equip_detail', 'pro_recap'].includes(scr)) { setScreen({ name: scr, params }); return; }
    if (['pro_today', 'pro_done', 'pro_notes', 'settings'].includes(t)) { setScreen(null); setTab(t); }
    if (scr === 'p_notifs') act.openNotifs('pro');
  };
  let body;
  if (screen) {
    if (screen.name === 'pro_equipment') body = <OwnerEquipList go={nav} params={screen.params} toast={say} pro />;
    else if (screen.name === 'pro_equip_detail') body = <EquipDetail go={nav} params={screen.params} toast={say} pro />;
    else body = <VisitRecap go={nav} params={screen.params} viewer="pro" toast={say} />;
  }
  else if (tab === 'pro_done') body = <ProDone go={nav} openFab={() => {}} />;
  else if (tab === 'pro_notes') body = <ProNotes go={nav} openFab={() => {}} toast={say} />;
  else if (tab === 'settings') body = <Settings go={nav} back={() => setTab('pro_today')} role="provider" setRole={() => {}} autoCheckin={autoCk} setAutoCheckin={setAutoCk} toast={say} />;
  else body = <ProTodayDemo world={world} act={act} nav={nav} />;
  return (
    <>
      {body}
      <DemoNotifSheet persona="pro" world={world} act={act} />
      <Toast msg={toast && toast.msg} tone={toast && toast.tone} />
    </>
  );
}

/* =========================== HOMEOWNER PHONE ========================= */
function HomeDemoPhone({ world, act, toast, say }) {
  const [tab, setTab] = React.useState('h_feed');
  const [sheet, setSheet] = React.useState(false);
  const [reqSheet, setReqSheet] = React.useState(false);
  const [screen, setScreen] = React.useState(null); // full-screen push: equipment / recap (REAL app components)
  const [slot, setSlot] = React.useState('Thu, May 21 · 10 AM');
  const [reason, setReason] = React.useState('Guests coming Monday');
  const nav = (scr, params) => {
    if (['h_feed', 'h_chem', 'h_inbox', 'h_ledger'].includes(scr)) { setScreen(null); setTab(scr); }
    else if (['h_equipment', 'h_equip_detail', 'h_recap'].includes(scr)) setScreen({ name: scr, params });
    else if (scr === 'h_request') setSheet(true);
    else if (scr === 'h_notifs') act.openNotifs('home');
  };
  const openRequest = () => { if (!world.resched) setSheet(true); };
  const send = () => { setSheet(false); act.sendResched(slot, reason); };

  let body;
  if (screen) {
    if (screen.name === 'h_equipment') body = <HomeEquip go={nav} />;
    else if (screen.name === 'h_equip_detail') body = <HomeEquipDetail go={nav} params={screen.params} />;
    else body = <VisitRecap go={nav} params={screen.params} viewer="homeowner" toast={say} />;
  }
  else if (tab === 'h_chem') body = <HomePoolTab world={world} nav={nav} openRequest={openRequest} />;
  else if (tab === 'h_inbox') body = <HomeInvoicesTab world={world} act={act} nav={nav} openRequest={openRequest} />;
  else if (tab === 'h_ledger') body = <HomeLedgerTab world={world} nav={nav} openRequest={openRequest} />;
  else body = <HomeFeedTab world={world} act={act} nav={nav} openRequest={openRequest} openReq={() => setReqSheet(true)} toast={say} />;

  return (
    <>
      {body}
      {/* request sheet — same options as the app's reschedule screen */}
      <Sheet open={sheet} onClose={() => setSheet(false)} title="Move your visit">
        <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: -6, marginBottom: 13 }}>Goes to Diego — he approves, suggests another time, or declines with a reason.</div>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 8 }}>New time</div>
        <div style={{ display: 'grid', gap: 8, marginBottom: 14 }}>
          {['Thu, May 21 · 10 AM', 'Fri, May 22 · 1 PM', 'Sat, May 23 · 9 AM'].map(s => {
            const on = slot === s;
            return (
              <button key={s} onClick={() => setSlot(s)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '12px 13px', borderRadius: 13, border: on ? '2px solid var(--green-500)' : '1.5px solid var(--ink-100)', background: on ? 'var(--green-50)' : '#fff', cursor: 'pointer', textAlign: 'left' }}>
                <Icon name="calendar" size={17} style={{ color: on ? 'var(--green-700)' : 'var(--ink-400,#A8A498)', flexShrink: 0 }} />
                <span style={{ flex: 1, fontWeight: 700, fontSize: 13.5, fontFamily: 'var(--font-mono)' }}>{s}</span>
                <span style={{ width: 20, height: 20, borderRadius: '50%', border: on ? 'none' : '2px solid var(--ink-200)', background: on ? 'var(--green-700)' : 'transparent', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}>{on && <Icon name="check" size={12} strokeWidth={3} />}</span>
              </button>
            );
          })}
        </div>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 8 }}>Why? Diego sees this</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 14 }}>
          {['Guests coming Monday', 'Gate will be locked', "We'll be away"].map(r => (
            <button key={r} onClick={() => setReason(r)} style={{ padding: '8px 12px', borderRadius: 11, border: reason === r ? '2px solid var(--green-500)' : '1.5px solid var(--ink-200)', background: reason === r ? 'var(--green-50)' : '#fff', color: reason === r ? 'var(--green-800)' : 'var(--ink-700)', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>{r}</button>
          ))}
        </div>
        <button onClick={send} className="btn btn-primary btn-block" style={{ minHeight: 48 }}><Icon name="send" size={18} />Send to Diego</button>
      </Sheet>
      <DemoNotifSheet persona="home" world={world} act={act} />
      <HomeRequestSheet open={reqSheet} onClose={() => setReqSheet(false)} act={act} />
      <Toast msg={toast && toast.msg} tone={toast && toast.tone} />
    </>
  );
}

/* ============================ OWNER PHONE ============================ */
function OwnerHomeTab({ world, act, nav, setTab }) {
  const v = world.visit;
  const rq = world.resched;
  return (
    <Screen padBottom={24} footer={<TabBar role="owner" active="o_home" go={nav} onFab={() => setTab('o_money')} />}>
      <DmHeader persona="owner" world={world} act={act} sub="Marta Lawn & Pool" title="Good morning, Diego" />
      {/* money + ops — the owner pulse: dark statement band + calm ops pair */}
      <div style={{ padding: '4px 18px 0' }}>
        <OwnerStatBand
          collected={184000 + (world.invoice === 'paid' ? 26000 : 0)}
          collectedSub={world.invoice === 'paid' ? '29 invoices paid' : '28 invoices paid'}
          owed={world.invoice === 'sent' ? 26000 : 0}
          owedSub={world.invoice === 'sent' ? '1 invoice open' : 'All collected'}
          onOwed={() => setTab('o_money')}
          visitsValue={v === 'done' ? '2/5' : '1/5'}
          visitsSub={v === 'driving' ? 'Marco en route · Crestline' : v === 'onsite' ? `Marco on-site · ${dmClock(world.sec)}` : v === 'done' ? 'Crestline Ave verified' : 'Marco out · next ETA 10:05'}
          visitsLive={v === 'driving' || v === 'onsite'}
          homesValue="38" homesSub="21 garden · 17 pool" onHomes={() => setTab('o_customers')}
        />
      </div>
      {/* needs you — same rows as the app */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="ink" icon="bell" style={{ marginBottom: 12 }}>Needs you</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          <button onClick={() => setTab('o_inbox')} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: 14, border: 'none', borderBottom: '1px solid var(--ink-100)', background: '#fff', 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="calendar-check" size={19} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14.5 }}>Reschedule requests</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>Approve, suggest a time, or move the stop</div>
            </div>
            <span style={{ background: 'var(--yellow-50)', color: 'var(--yellow-700)', borderRadius: 99, minWidth: 22, height: 22, padding: '0 7px', fontSize: 12.5, fontWeight: 800, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{rq && rq.state === 'pending' ? 1 : 0}</span>
            <Icon name="chevron-right" size={18} style={{ color: 'var(--ink-300)', flexShrink: 0 }} />
          </button>
          <button onClick={() => setTab('o_money')} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: 14, border: 'none', background: '#fff', cursor: 'pointer', textAlign: 'left' }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--alert-500)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}><Icon name="nudge" size={19} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14.5 }}>Unpaid invoices</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>{world.invoice === 'sent' ? '$260.00 outstanding · Emma' : 'Nothing outstanding'}</div>
            </div>
            <span style={{ background: 'var(--alert-50)', color: 'var(--alert-700)', borderRadius: 99, minWidth: 22, height: 22, padding: '0 7px', fontSize: 12.5, fontWeight: 800, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{world.invoice === 'sent' ? 1 : 0}</span>
            <Icon name="chevron-right" size={18} style={{ color: 'var(--ink-300)', flexShrink: 0 }} />
          </button>
        </div>
      </div>
      {/* a property at a glance — opens the REAL equipment & recap screens */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="aqua" icon="home" style={{ marginBottom: 12 }} meta="88 Crestline Ave">Emma's property</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          <button onClick={() => nav('o_equipment', { id: 'c2' })} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: 14, border: 'none', borderBottom: '1px solid var(--ink-100)', background: '#fff', cursor: 'pointer', textAlign: 'left' }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--aqua-50)', display: 'grid', placeItems: 'center', color: 'var(--aqua-700)', flexShrink: 0 }}><Icon name="flask" size={19} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14.5 }}>Equipment</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>5 pieces · age &amp; warranty on the record</div>
            </div>
            <Icon name="chevron-right" size={18} style={{ color: 'var(--ink-300)', flexShrink: 0 }} />
          </button>
          <button onClick={() => nav('o_recap', { id: 'v2' })} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: 14, border: 'none', background: '#fff', cursor: 'pointer', textAlign: 'left' }}>
            <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--green-50)', display: 'grid', placeItems: 'center', color: 'var(--green-700)', flexShrink: 0 }}><Icon name="camera" size={19} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14.5 }}>Latest visit recap</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>The same recap Emma sees</div>
            </div>
            <Icon name="chevron-right" size={18} style={{ color: 'var(--ink-300)', flexShrink: 0 }} />
          </button>
        </div>
      </div>
    </Screen>
  );
}

function OwnerInboxTab({ world, act, nav }) {
  const rq = world.resched;
  return (
    <Screen padBottom={24} footer={<TabBar role="owner" active="o_inbox" go={nav} onFab={() => {}} />}>
      <TopBar title="Inbox" big subtitle="Approvals & field notes" />
      <div style={{ padding: '0 18px' }}>
        {rq ? <OwnerReschedCard world={world} act={act} /> : world.req ? null : (
          <div className="card" style={{ padding: '22px 14px', textAlign: 'center' }}>
            <Sprout size={70} mood="wink" />
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15, marginTop: 6 }}>No requests right now.</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 4 }}>When Emma asks to move a visit, it lands here instantly.</div>
          </div>
        )}
      </div>
      {/* approve-before-work — photo'd request → priced quote */}
      <OwnerRequestCard world={world} act={act} />

      {/* reviews — public 5★ or a private fix-it note */}
      <OwnerReviewCard world={world} />
      {/* field note from Marco → chat with Emma → closure */}
      {world.note && (
        <div style={{ padding: '14px 18px 0' }}>
          <SectionHead tone="green" icon="notes" style={{ marginBottom: 10 }} meta="from the field">Field notes</SectionHead>
          <div className="card" style={{ padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}>
              <PaperAvatar who="pro" size={34} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Crestline Ave pool</div>
                <div style={{ fontSize: 11, color: 'var(--ink-500)' }}>Marco · 10:31 AM</div>
              </div>
              {world.note === 'sent' && <DmMark tone="yellow" pulse>NEEDS YOU</DmMark>}
              {(world.note === 'asked') && <DmMark tone="yellow" pulse>WAITING ON EMMA</DmMark>}
              {world.note === 'replied' && <DmMark tone="green" pulse>EMMA REPLIED</DmMark>}
              {world.note === 'closed' && <DmMark tone="green">RESOLVED</DmMark>}
            </div>
            <div style={{ background: 'var(--paper)', border: '1px solid var(--ink-100)', borderRadius: 12, padding: '10px 13px', fontSize: 13, color: 'var(--ink-700)', lineHeight: 1.5 }}>“Emma asked about a monthly filter deep-clean — routing to you.”</div>
            {world.note !== 'sent' && (
              <div style={{ marginTop: 10, display: 'grid', gap: 8 }}>
                <div style={{ justifySelf: 'end', maxWidth: '85%', background: 'var(--green-700)', color: '#fff', borderRadius: '14px 14px 4px 14px', padding: '9px 12px', fontSize: 12.5, lineHeight: 1.45 }}>Marco says you'd like a monthly filter deep-clean — I can add it for $20/visit. Want it?</div>
                {(world.note === 'replied' || world.note === 'closed') && (
                  <div style={{ justifySelf: 'start', maxWidth: '85%', background: '#fff', border: '1px solid var(--ink-100)', color: 'var(--ink-900)', borderRadius: '14px 14px 14px 4px', padding: '9px 12px', fontSize: 12.5, lineHeight: 1.45 }}>{world.noteYes ? 'Yes please — add it.' : 'Not right now, thanks.'}</div>
                )}
              </div>
            )}
            <div style={{ marginTop: 11 }}>
              {world.note === 'sent' && <button onClick={act.ownerMessage} className="btn btn-primary btn-block" style={{ minHeight: 44 }}><Icon name="message" size={17} />Message Emma about this</button>}
              {world.note === 'replied' && <button onClick={act.closeNote} className="btn btn-primary btn-block" style={{ minHeight: 44 }}><Icon name="check" size={17} />{world.noteYes ? 'Close — add to her service' : 'Close the note'}</button>}
              {world.note === 'closed' && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--green-50)', borderRadius: 11, padding: '9px 12px', fontSize: 12, fontWeight: 600, color: 'var(--green-800)' }}>
                  <Icon name="check-circle" size={15} style={{ flexShrink: 0 }} />{world.noteYes ? 'Added to Emma\u2019s weekly service — Marco notified.' : 'Closed — Emma passed for now. Marco notified.'}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </Screen>
  );
}

function OwnerDemoPhone({ world, act, toast, say }) {
  const [tab, setTab] = React.useState('o_home');
  const [screen, setScreen] = React.useState(null); // full-screen push: equipment / recap (REAL app components)
  const nav = (scr, params) => {
    if (['o_equipment', 'o_equip_detail', 'o_recap'].includes(scr)) { setScreen({ name: scr, params }); return; }
    if (['o_home', 'o_money', 'o_inbox', 'o_customers'].includes(scr)) { setScreen(null); setTab(scr); }
    else if (['o_customer', 'o_new_customer', 'o_thread', 'o_schedule_work'].includes(scr)) { setScreen(null); setTab('o_customers'); }
    if (scr === 'o_notifs') act.openNotifs('owner');
  };
  let body;
  if (screen) {
    if (screen.name === 'o_equipment') body = <OwnerEquipList go={nav} params={screen.params} toast={say} />;
    else if (screen.name === 'o_equip_detail') body = <EquipDetail go={nav} params={screen.params} toast={say} />;
    else body = <VisitRecap go={nav} params={screen.params} viewer="owner" toast={say} />;
  }
  else if (tab === 'o_money') body = <OwnerMoneyTab world={world} act={act} nav={nav} />;
  else if (tab === 'o_inbox') body = <OwnerInboxTab world={world} act={act} nav={nav} />;
  else if (tab === 'o_customers') body = <OwnerCustomersM go={nav} openFab={() => {}} toast={say} />;
  else body = <OwnerHomeTab world={world} act={act} nav={nav} setTab={setTab} />;
  return (
    <>
      {body}
      <DemoNotifSheet persona="owner" world={world} act={act} />
      <Toast msg={toast && toast.msg} tone={toast && toast.tone} />
    </>
  );
}

/* owner's reschedule card — shared by Home + Inbox tabs */
function OwnerReschedCard({ world, act }) {
  const rq = world.resched;
  return (
    <div className="card" style={{ padding: 14, borderColor: rq.state === 'pending' ? 'var(--yellow-100)' : 'var(--ink-100)', boxShadow: rq.state === 'pending' ? '0 0 0 3px var(--yellow-50), var(--shadow-md)' : 'var(--shadow-sm)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}>
        <PaperAvatar who="home" size={34} />
        <div style={{ flex: 1, minWidth: 0, fontWeight: 700, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Emma Walsh</div>
        {(() => { const [t, l, p] = rqMark(rq.state, 'owner'); return <DmMark tone={t} pulse={p}>{l}</DmMark>; })()}
      </div>
      <TimeChange compact from="Mon, May 18 · 10 AM" to={rq.proposedTo || rq.to} toLabel={rq.state === 'approved' ? 'CONFIRMED' : rq.proposedTo ? 'YOU SUGGESTED' : 'REQUESTED'} toTone={rq.state === 'declined' ? 'alert' : 'green'} />
      <div style={{ margin: '11px 0 0' }}>
        <NegotiationThread thread={rq.thread} compact names={{ owner: 'You', homeowner: 'Emma' }} />
      </div>
      <div style={{ marginTop: 11 }}>
        {rq.state === 'pending' && (
          <div style={{ display: 'grid', gap: 8 }}>
            <button onClick={act.ownerApprove} className="btn btn-primary btn-block" style={{ minHeight: 44 }}><Icon name="check" size={17} />Approve {rq.to}</button>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={act.ownerPropose} className="btn btn-secondary" style={{ flex: 1.3, minHeight: 42, fontSize: 12.5 }}><Icon name="clock" size={15} />Suggest Sat 9 AM</button>
              <button onClick={act.ownerDecline} className="btn btn-secondary" style={{ flex: 1, minHeight: 42, fontSize: 12.5, color: 'var(--alert-700)' }}>Decline</button>
            </div>
          </div>
        )}
        {rq.state === 'proposed' && <ReschedStatusBar state="waiting" text="Waiting on Emma — she can accept or keep her original time." />}
        {rq.state === 'approved' && <ReschedStatusBar state="approved" text={`Confirmed for ${rq.final}. Marco's route updated — Emma notified.`} />}
        {rq.state === 'declined' && <ReschedStatusBar state="declined" text="Declined — Emma keeps Mon, May 18. She saw your reason." />}
      </div>
    </div>
  );
}

Object.assign(window, { ProDemoPhone, HomeDemoPhone, OwnerDemoPhone, OwnerReschedCard, OwnerHomeTab, OwnerInboxTab, ProTodayDemo, DmHeader });
