/* ============================================================================
   MOWDEW — Provider screens
   p_today (Today/Route · HERO) · p_homes · p_property · p_visit ·
   p_invoices · p_invoice_build · p_getpaid
   Each screen: (props) => JSX.  Shared helpers from kit + frame + data.
   ========================================================================= */

/* ---- small shared bits ---- */
function statusChip(h) {
  if (h.status === 'done') return <Chip tone="done" icon="check">Done</Chip>;
  if (h.status === 'onsite') return <Chip tone="live" pulse>On-site</Chip>;
  return <Chip tone="soon">Upcoming</Chip>;
}
function fmtClock(sec) {
  const m = Math.floor(sec / 60), s = sec % 60;
  return `${m}:${String(s).padStart(2, '0')}`;
}

/* ---- Route map: numbered stops over the mini neighborhood ---- */
function RouteMap({ height = 156, onExpand }) {
  const stops = [ [44, 50, 'done'], [104, 98, 'onsite'], [178, 128, 'soon'], [248, 98, 'soon'], [280, 44, 'soon'] ];
  const col = { done: 'var(--green-500)', onsite: 'var(--blue-500)', soon: 'var(--yellow-500)' };
  return (
    <div onClick={onExpand} style={{ position: 'relative', height, borderRadius: 'var(--radius-xl)', overflow: 'hidden', background: '#E8EEE6', cursor: 'pointer' }}>
      <svg width="100%" height="100%" viewBox="0 0 300 160" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0 }}>
        <rect width="300" height="160" fill="#E8EEE6" />
        <rect x="18" y="14" width="74" height="44" rx="6" fill="#D6E7CE" />
        <rect x="210" y="118" width="78" height="42" rx="6" fill="#D6E7CE" />
        <g fill="none" stroke="#fff" strokeLinejoin="round" strokeLinecap="round">
          <path d="M-10 90 H320" strokeWidth="13" />
          <path d="M150 -10 V170" strokeWidth="11" />
          <path d="M-10 36 H110 V170" strokeWidth="7" />
          <path d="M150 64 H320" strokeWidth="7" />
        </g>
        {/* route line connecting stops */}
        <path d="M44 50 Q70 78 104 98 T178 128 Q216 116 248 98 T280 44" fill="none" stroke="var(--green-700)" strokeOpacity="0.5" strokeWidth="2.5" strokeDasharray="3 5" strokeLinecap="round" />
      </svg>
      {stops.map(([x, y, st], i) => (
        <div key={i} style={{ position: 'absolute', left: `${x / 3}%`, top: `${y / 1.6}%`, transform: 'translate(-50%,-50%)', width: 26, height: 26, borderRadius: '50%', background: col[st], border: '3px solid #fff', boxShadow: 'var(--shadow-md)', color: st === 'soon' ? 'var(--ink-900)' : '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 12.5 }}>{i + 1}</div>
      ))}
      <span style={{ position: 'absolute', top: 10, left: 10 }}><Mono tone="blue" icon="navigation">TODAY · 5 STOPS</Mono></span>
    </div>
  );
}

/* ============================== TODAY / ROUTE (HERO) ===================== */
function ProviderToday({ go, openFab }) {
  const done = HOMES.filter(h => h.status === 'done').length;
  const earned = HOMES.reduce((s, h) => s + SERVICE[h.svc].price, 0);
  return (
    <Screen padBottom={26} footer={<TabBar role="provider" active="p_today" go={go} onFab={openFab} />}>
      {/* 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 }}>{TODAY}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 21, letterSpacing: '-0.02em' }}>Good morning, Diego</div>
        </div>
        <button onClick={() => go('settings')} style={{ width: 42, height: 42, borderRadius: '50%', border: '1px solid var(--ink-100)', background: '#fff', display: 'grid', placeItems: 'center', cursor: 'pointer', position: 'relative' }}>
          <Icon name="bell" size={20} />
          <span style={{ position: 'absolute', top: 8, right: 9, width: 8, height: 8, borderRadius: '50%', background: 'var(--alert-500)', border: '1.5px solid #fff' }} />
        </button>
      </div>

      {/* summary strip */}
      <div style={{ padding: '8px 18px 4px', display: 'flex', gap: 10 }}>
        {[['Stops', '5', 'route', 'green'], ['Done', String(done), 'check-circle', 'green'], ['On track', fmtMoney(earned), 'invoice', 'blue']].map(([k, v, ic, tn], i) => (
          <div key={i} style={{ flex: 1, background: '#fff', border: '1px solid var(--ink-100)', borderRadius: 'var(--radius-lg)', padding: '11px 12px', boxShadow: 'var(--shadow-sm)' }}>
            <Icon name={ic} size={17} style={{ color: tn === 'blue' ? 'var(--blue-700)' : 'var(--green-700)' }} />
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, marginTop: 5, letterSpacing: '-0.02em' }}>{v}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-500)', fontWeight: 600 }}>{k}</div>
          </div>
        ))}
      </div>

      {/* auto check-in banner */}
      <div style={{ margin: '12px 18px 4px', background: 'var(--blue-50)', border: '1px solid var(--blue-100)', borderRadius: 'var(--radius-lg)', padding: '11px 14px', display: 'flex', alignItems: 'center', gap: 11 }}>
        <span style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--blue-500)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}><Icon name="target" size={19} strokeWidth={2.3} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--blue-700)' }}>Auto check-in is on</div>
          <div style={{ fontSize: 12, color: 'var(--ink-600,#6E6B60)' }}>You'll clock in automatically when you arrive.</div>
        </div>
        <span className="tn-pulse" style={{ width: 9, height: 9, borderRadius: '50%', background: 'var(--blue-500)' }} />
      </div>

      {/* map */}
      <div style={{ padding: '8px 18px 6px' }}>
        <RouteMap onExpand={() => {}} />
      </div>

      {/* route list */}
      <div style={{ padding: '6px 18px 0' }}>
        <SectionHead tone="green" icon="route" meta="5 homes">The route</SectionHead>
      </div>

      <div style={{ padding: '10px 18px 0', display: 'grid', gap: 12 }}>
        {HOMES.map((h, i) => <RouteCard key={h.id} h={h} n={i + 1} go={go} />)}
      </div>
    </Screen>
  );
}

function RouteCard({ h, n, go }) {
  const s = SERVICE[h.svc];
  const onsite = h.status === 'onsite';
  const done = h.status === 'done';
  return (
    <div onClick={() => go(h.status === 'onsite' ? 'p_visit' : 'p_property', { id: h.id })} className="card" style={{ padding: 14, cursor: 'pointer', borderColor: onsite ? 'var(--blue-200,#8FD2F6)' : 'var(--ink-100)', boxShadow: onsite ? '0 0 0 3px var(--blue-50), var(--shadow-md)' : 'var(--shadow-sm)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ position: 'relative' }}>
          <IconBadge icon={s.icon} tone={s.tone} size={46} />
          <span style={{ position: 'absolute', top: -6, left: -6, width: 20, height: 20, borderRadius: '50%', background: 'var(--ink-900)', color: '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 11, border: '2px solid #fff' }}>{n}</span>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <h3 style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h.addr}</h3>
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h.who} · {s.label}</div>
        </div>
        {statusChip(h)}
      </div>

      {done && (
        <div style={{ marginTop: 12 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <PhotoTile scene="lawn-before" label="BEFORE" height={78} />
            <PhotoTile scene="lawn-after" label="AFTER" height={78} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 9, fontSize: 12.5, color: 'var(--ink-500)' }}>
            <Icon name="clock" size={14} /> {h.in} – {h.out} · {h.dur}
            <span style={{ marginLeft: 'auto' }}><Mono tone="blue" icon="shield">VERIFIED</Mono></span>
          </div>
        </div>
      )}
      {onsite && <OnsiteFooter h={h} go={go} />}
      {h.status === 'upcoming' && (
        <div style={{ marginTop: 11, display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5 }}>
          <Icon name="clock" size={14} style={{ color: 'var(--yellow-700)' }} />
          <span style={{ color: 'var(--ink-700)', fontWeight: 600 }}>ETA {h.eta}</span>
          <span style={{ marginLeft: 'auto' }}>
            {h.geo
              ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: 'var(--blue-700)' }}><Icon name="target" size={13} strokeWidth={2.4} />Auto check-in armed</span>
              : <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, color: 'var(--ink-500)' }}><Icon name="pin" size={13} strokeWidth={2.2} />Manual check-in</span>}
          </span>
        </div>
      )}
    </div>
  );
}

function OnsiteFooter({ h, go }) {
  const [sec, setSec] = React.useState(764);
  React.useEffect(() => { const t = setInterval(() => setSec(s => s + 1), 1000); return () => clearInterval(t); }, []);
  return (
    <div style={{ marginTop: 12, background: 'var(--blue-50)', borderRadius: 'var(--radius-lg)', padding: '11px 13px', display: 'flex', alignItems: 'center', gap: 11 }}>
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11.5, fontWeight: 700, color: 'var(--blue-700)', letterSpacing: '.04em' }}>
          <Icon name="shield" size={14} strokeWidth={2.4} />CHECKED IN · {h.in}
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 22, color: 'var(--blue-700)', fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>{fmtClock(sec)}</div>
      </div>
      <button onClick={e => { e.stopPropagation(); go('p_visit', { id: h.id }); }} className="btn btn-blue" style={{ minHeight: 44, padding: '11px 18px' }}>Open visit<Icon name="arrow-right" size={18} /></button>
    </div>
  );
}

/* ============================== HOMES LIST ============================== */
function ProviderHomes({ go, openFab }) {
  return (
    <Screen footer={<TabBar role="provider" active="p_homes" go={go} onFab={openFab} />}>
      <TopBar title="Homes" subtitle="12 active · Bay Area" big right={<button style={{ width: 42, height: 42, borderRadius: 12, border: '1px solid var(--ink-100)', background: '#fff', display: 'grid', placeItems: 'center', cursor: 'pointer' }}><Icon name="search" size={20} /></button>} />
      <div style={{ padding: '6px 18px 0', display: 'grid', gap: 11 }}>
        {HOMES.map(h => {
          const s = SERVICE[h.svc];
          return (
            <div key={h.id} onClick={() => go('p_property', { id: h.id })} className="card" style={{ padding: 14, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
              <IconBadge icon={s.icon} tone={s.tone} size={46} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <h3>{h.addr}</h3>
                <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>{h.who} · {h.city}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <Tag tone="yellow" style={{ justifyContent: 'flex-end' }}>{h.cadence.replace('Every ', '')}</Tag>
                <Icon name="chevron-right" size={18} style={{ color: 'var(--ink-300)', marginTop: 6 }} />
              </div>
            </div>
          );
        })}
      </div>
    </Screen>
  );
}

/* ============================== PROPERTY DETAIL ========================= */
function ProviderProperty({ go, params }) {
  const h = HOMES.find(x => x.id === params.id) || HOMES[0];
  const s = SERVICE[h.svc];
  return (
    <Screen padBottom={28} footer={
      <ActionBar>
        <button onClick={() => go('p_invoice_build', { id: h.id })} className="btn btn-secondary" style={{ flex: 1 }}><Icon name="invoice" size={19} />Invoice</button>
        <button onClick={() => go('p_visit', { id: h.id })} className="btn btn-primary" style={{ flex: 1.4 }}><Icon name="pin" size={19} />Start visit</button>
      </ActionBar>}>
      <TopBar title={h.who} subtitle={h.addr} onBack={() => go('p_today')} />
      {/* hero map */}
      <div style={{ padding: '4px 18px 0' }}>
        <MiniMap height={150} label={`${h.addr} · ${h.city}`} />
      </div>
      {/* meta cards */}
      <div style={{ padding: '14px 18px 0', display: 'flex', gap: 10 }}>
        <div className="card" style={{ flex: 1, padding: 13 }}>
          <Tag tone="yellow">Cadence</Tag>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 16, marginTop: 7 }}>{h.cadence}</div>
        </div>
        <div className="card" style={{ flex: 1, padding: 13 }}>
          <Tag tone="green">Service</Tag>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 7 }}>
            <IconBadge icon={s.icon} tone={s.tone} size={26} />
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15 }}>{fmtMoney(s.price)}</span>
          </div>
        </div>
      </div>
      {/* homeowner contact */}
      <div style={{ padding: '14px 18px 0' }}>
        <div className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <Avatar name={h.name} size={44} />
          <div style={{ flex: 1 }}>
            <h3>{h.name}</h3>
            <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>Homeowner · on Mowdew</div>
          </div>
          <button style={{ width: 42, height: 42, borderRadius: 12, border: '1px solid var(--ink-100)', background: '#fff', display: 'grid', placeItems: 'center', cursor: 'pointer', color: 'var(--green-700)' }}><Icon name="phone" size={19} /></button>
        </div>
      </div>
      {/* recent visits */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="green" icon="history" style={{ marginBottom: 12 }}>Recent visits</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          {h.visits.map((v, i) => (
            <div key={i} onClick={() => go('h_visit', { id: h.id })} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderTop: i ? '1px solid var(--ink-100)' : 'none', cursor: 'pointer' }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--green-50)', display: 'grid', placeItems: 'center', color: 'var(--green-700)' }}><Icon name="check" size={18} strokeWidth={2.6} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 14.5 }}>{v.date}</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>{v.who} · {v.dur}</div>
              </div>
              <Mono tone="blue" icon="shield">VERIFIED</Mono>
            </div>
          ))}
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { ProviderToday, ProviderHomes, ProviderProperty, RouteMap, statusChip, fmtClock });
