/* ============================================================================
   MOWDEW — The Visit Recap
   Mowdew's answer to the beloved photo+chemistry service email — but in-app,
   two-way, and SHAREABLE. It's the canonical object an invoice line points to.
   A keepsake of "look what got done", not a receipt.
     • HOMEOWNER  VisitRecap (primary) — share → branded, EXIF-stripped image
     • OWNER/PRO  the SAME recap surface (viewer flag; name-hidden for pro)
   Reuses the kit + ChemVerdictHero (chemistry feature). Loads after the
   homeowner screens; exposed on window.
   ========================================================================= */

/* per-visit recap content. Pool visits carry chemistry; garden visits don't. */
const RECAPS = {
  v2: { svc: 'pool', date: 'Mon, May 5', in: '10:04a', out: '10:41a', dur: '37 min', pro: 'Diego', label: 'Crestline Ave pool',
    photos: true, before: 'pool-before', after: 'pool-clean',
    tasks: ['Skimmed surface & emptied baskets', 'Brushed walls & steps', 'Vacuumed floor', 'Backwashed filter', 'Tested & balanced water'],
    chem: { ph: 7.4, cl: 1.8, alk: 100, cya: 45, ch: 300, temp: 80, date: 'Mon, May 5' },
    note: 'Filter looking good. Saw the gate latch is a little loose — flagged it for the office.' },
  v3: { svc: 'pool', date: 'Mon, Apr 28', in: '9:58a', out: '10:25a', dur: '27 min', pro: 'Diego', label: 'Crestline Ave pool',
    photos: true, before: 'pool-before', after: 'pool-clean',
    tasks: ['Skimmed surface', 'Brushed walls', 'Emptied baskets', 'Tested water — corrected low chlorine'],
    chem: { ph: 7.2, cl: 0.8, alk: 95, cya: 53, ch: 295, temp: 78, date: 'Mon, Apr 28', handled: 'cl' },
    note: 'Chlorine was a touch low — added tablets, all set now.' },
  v4: { svc: 'pool', date: 'Mon, Apr 21', in: '10:20a', out: '10:42a', dur: '22 min', pro: 'Diego', label: 'Crestline Ave pool',
    photos: false, before: 'pool-before', after: 'pool-clean',
    tasks: ['Skimmed surface', 'Brushed walls', 'Emptied baskets', 'Tested & balanced water'],
    chem: { ph: 7.5, cl: 2.0, alk: 105, cya: 50, ch: 305, temp: 77, date: 'Mon, Apr 21' },
    note: '' },
  g1: { svc: 'mow', date: 'Mon, May 12', in: '9:06a', out: '9:41a', dur: '35 min', pro: 'Diego', label: 'Oak Ridge Ct garden',
    photos: true, before: 'lawn-before', after: 'lawn-after',
    tasks: ['Mowed front & back', 'Edged all borders', 'Blew down paths & patio', 'Bagged clippings'],
    chem: null,
    note: 'Lawn\u2019s filling in nicely with the warmer weather. Bay-friendly mow height for summer.' },
};
function getRecap(id) { return RECAPS[id] || RECAPS.v2; }

/* ─── Before/After compare — draggable divider (keepsake, not a receipt) ─ */
function BeforeAfter({ before, after, height = 230 }) {
  const [pct, setPct] = React.useState(52);
  return (
    <div style={{ position: 'relative', height, borderRadius: 'var(--radius-xl)', overflow: 'hidden', userSelect: 'none', touchAction: 'none' }}>
      {/* after = base layer (full) */}
      <div style={{ position: 'absolute', inset: 0 }}><PhotoTile scene={after} height={height} radius="var(--radius-xl)" /></div>
      {/* before = clipped from the left to pct */}
      <div style={{ position: 'absolute', inset: 0, clipPath: `inset(0 ${100 - pct}% 0 0)` }}><PhotoTile scene={before} height={height} radius="var(--radius-xl)" /></div>
      {/* labels */}
      <span style={{ position: 'absolute', top: 10, left: 10, fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700, letterSpacing: '.06em', color: '#fff', background: 'rgba(27,26,23,.6)', padding: '4px 8px', borderRadius: 7 }}>BEFORE</span>
      <span style={{ position: 'absolute', top: 10, right: 10, fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700, letterSpacing: '.06em', color: '#fff', background: 'rgba(18,188,201,.85)', padding: '4px 8px', borderRadius: 7 }}>AFTER</span>
      {/* divider */}
      <div style={{ position: 'absolute', top: 0, bottom: 0, left: `${pct}%`, width: 3, background: '#fff', boxShadow: '0 0 0 1px rgba(27,26,23,.15)', transform: 'translateX(-50%)', pointerEvents: 'none' }}>
        <span style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 34, height: 34, borderRadius: '50%', background: '#fff', boxShadow: 'var(--shadow-md)', display: 'grid', placeItems: 'center', color: 'var(--aqua-700)' }}><Icon name="arrow-right" size={15} style={{ transform: 'scaleX(-1)' }} /><Icon name="arrow-right" size={15} style={{ marginLeft: -3 }} /></span>
      </div>
      <input type="range" min="0" max="100" value={pct} onChange={e => setPct(+e.target.value)} aria-label="Drag to compare before and after"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0, cursor: 'ew-resize', margin: 0 }} />
    </div>
  );
}

/* ─── The recap surface ─────────────────────────────────────────────── */
function VisitRecap({ go, params, toast, viewer = 'homeowner' }) {
  const id = (params && params.id) || 'v2';
  const r = getRecap(id);
  const isPool = r.svc === 'pool';
  const nameHidden = viewer === 'pro';
  const [share, setShare] = React.useState(false);
  const [shared, setShared] = React.useState(false);
  const back = viewer === 'owner' ? () => go('o_customer', { id: 'c2' }) : viewer === 'pro' ? () => go('pro_today') : () => go('h_feed');
  const accent = isPool ? 'aqua' : 'green';

  return (
    <Screen padBottom={26} footer={
      <ActionBar>
        <button onClick={back} className="btn btn-secondary" style={{ flex: 0.8 }}>Done</button>
        <button onClick={() => setShare(true)} className="btn btn-primary" style={{ flex: 1.5 }}><Icon name="share" size={18} />{shared ? 'Share again' : 'Share this recap'}</button>
      </ActionBar>}>
      <TopBar title="Visit recap" subtitle={r.label.replace(/ (pool|garden)$/, '')} onBack={back}
        right={shared ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--green-50)', borderRadius: 99, padding: '5px 10px', fontSize: 11, fontWeight: 700, color: 'var(--green-700)' }}><Icon name="check" size={12} strokeWidth={3} />Shared</span> : null} />

      {/* header — date, time on-site, verified, pro */}
      <div style={{ padding: '4px 18px 0' }}>
        <div className="card" style={{ padding: 15, borderColor: `var(--${accent}-100)` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {nameHidden
              ? <span style={{ width: 46, height: 46, borderRadius: 13, background: `var(--${accent}-50)`, display: 'grid', placeItems: 'center', color: `var(--${accent}-700)`, flexShrink: 0 }}><Icon name={isPool ? 'droplet' : 'leaf'} size={23} /></span>
              : <PaperAvatar who="pro" size={46} />}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, letterSpacing: '-0.02em' }}>{r.date}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 1 }}>{nameHidden ? r.label : `${r.pro} · ${isPool ? 'pool service' : 'garden service'}`}</div>
            </div>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--blue-50)', border: '1px solid var(--blue-100)', color: 'var(--blue-700)', padding: '5px 10px', borderRadius: 99, fontSize: 11, fontWeight: 700, flexShrink: 0 }}><Icon name="shield" size={13} strokeWidth={2.4} />Verified</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--ink-100)', fontSize: 12.5, color: 'var(--ink-600,#6E6B60)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="clock" size={14} style={{ color: 'var(--blue-700)' }} /><b style={{ color: 'var(--ink-900)' }}>{r.in}–{r.out}</b></span>
            <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{r.dur} on-site</span>
            <span style={{ marginLeft: 'auto' }}><Mono tone="blue">40 FT</Mono></span>
          </div>
        </div>
      </div>

      {/* before / after */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone={accent} icon="camera" style={{ marginBottom: 10 }} meta={r.photos ? 'drag to compare' : null}>Before &amp; after</SectionHead>
        {r.photos ? (
          <BeforeAfter before={r.before} after={r.after} />
        ) : (
          <div className="card" style={{ padding: '22px 16px', textAlign: 'center', borderStyle: 'dashed' }}>
            <Sprout size={58} mood="default" />
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15, marginTop: 6 }}>No photos this visit</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 3, lineHeight: 1.45 }}>{r.pro} didn't snap photos this time — the verified check-in &amp; tasks below are still on the record.</div>
          </div>
        )}
      </div>

      {/* tasks completed */}
      <div style={{ padding: '18px 18px 0' }}>
        <SectionHead tone="green" icon="check-circle" style={{ marginBottom: 10 }} meta={`${r.tasks.length} done`}>What got done</SectionHead>
        <div className="card" style={{ padding: '6px 14px' }}>
          {r.tasks.map((t, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 0', borderTop: i ? '1px solid var(--ink-100)' : 'none' }}>
              <span style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--green-500)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}><Icon name="check" size={14} strokeWidth={3} /></span>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink-900)' }}>{t}</span>
            </div>
          ))}
        </div>
      </div>

      {/* chemistry verdict — pool only */}
      {isPool && r.chem && (
        <div style={{ padding: '18px 18px 0' }}>
          <SectionHead tone="aqua" icon="flask" style={{ marginBottom: 10 }}>Water</SectionHead>
          <ChemVerdictHero reading={r.chem} size="sm" />
        </div>
      )}

      {/* pro note */}
      {r.note && (
        <div style={{ padding: '18px 18px 0' }}>
          <SectionHead tone="green" icon="notes" style={{ marginBottom: 10 }}>Note from {nameHidden ? 'the pro' : r.pro}</SectionHead>
          <div className="card" style={{ padding: 14, display: 'flex', gap: 11 }}>
            {nameHidden ? <span style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--green-50)', display: 'grid', placeItems: 'center', color: 'var(--green-700)', flexShrink: 0 }}><Icon name="notes" size={17} /></span> : <PaperAvatar who="pro" size={34} />}
            <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--ink-700)', margin: 0 }}>{r.note}</p>
          </div>
        </div>
      )}

      {/* keepsake footer */}
      <div style={{ padding: '18px 18px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, background: `var(--${accent}-50)`, border: `1px solid var(--${accent}-100)`, borderRadius: 'var(--radius-lg)', padding: '13px 14px' }}>
          <Dewy size={42} mood="happy" />
          <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-700)', lineHeight: 1.45 }}>{viewer === 'homeowner' ? 'Proud of the pool? Share this recap with family — or post it.' : 'This is exactly what the homeowner sees — every visit, on the record.'}</div>
          {viewer === 'homeowner' && <button onClick={() => setShare(true)} className="btn btn-primary" style={{ minHeight: 40, padding: '0 15px', flexShrink: 0 }}><Icon name="share" size={16} />Share</button>}
        </div>
      </div>

      <ShareRecapSheet open={share} onClose={() => setShare(false)} r={r} onShared={() => { setShared(true); setShare(false); toast && toast('Recap shared · location data removed', 'green'); }} />
      {/* review capture at peak trust — homeowner only, after a good recap */}
      {viewer === 'homeowner' && r.photos && (!isPool || (r.chem && !r.chem.handled)) && (
        <div style={{ padding: '18px 18px 0' }}>
          <SectionHead tone="green" icon="star" style={{ marginBottom: 10 }}>One quick thing</SectionHead>
          <ReviewCapture proName={r.pro} />
        </div>
      )}
    </Screen>
  );
}

/* ─── Share sheet — branded, EXIF-stripped shareable card ────────────── */
function ShareRecapSheet({ open, onClose, r, onShared }) {
  const isPool = r.svc === 'pool';
  return (
    <Sheet open={open} onClose={onClose} title="Share your recap">
      <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: -6, marginBottom: 14 }}>A clean, branded card — safe to text family or post anywhere.</div>

      {/* the shareable preview */}
      <div style={{ borderRadius: 'var(--radius-xl)', overflow: 'hidden', border: '1px solid var(--ink-100)', boxShadow: 'var(--shadow-md)', marginBottom: 14 }}>
        <div style={{ position: 'relative' }}>
          <PhotoTile scene={r.after} height={150} radius={0} />
          <span style={{ position: 'absolute', top: 10, left: 10, fontFamily: 'var(--font-mono)', fontSize: 9.5, fontWeight: 700, letterSpacing: '.06em', color: '#fff', background: 'rgba(18,188,201,.9)', padding: '4px 9px', borderRadius: 7 }}>AFTER · {r.date.toUpperCase()}</span>
          <span style={{ position: 'absolute', bottom: 10, right: 10, display: 'inline-flex', alignItems: 'center', gap: 5, background: 'rgba(255,255,255,.95)', padding: '5px 10px', borderRadius: 99, fontSize: 11, fontWeight: 700, color: 'var(--blue-700)' }}><Icon name="shield" size={13} />Verified on-site</span>
        </div>
        <div style={{ padding: '13px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Logo size={30} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14.5, letterSpacing: '-0.02em' }}>{isPool ? 'Pool' : 'Garden'} service · {r.dur}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>Marta Lawn &amp; Pool · on Mowdew</div>
          </div>
          {isPool && r.chem && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--green-50)', border: '1px solid var(--green-100)', borderRadius: 9, padding: '5px 9px', fontSize: 11, fontWeight: 700, color: 'var(--green-700)' }}><Icon name="check-circle" size={13} />Balanced</span>}
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 14, fontSize: 11.5, color: 'var(--ink-500)' }}>
        <Icon name="shield" size={14} style={{ color: 'var(--green-700)', flexShrink: 0 }} />Location data (EXIF) is stripped — your address never travels with the photo.
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
        <button onClick={onShared} className="btn btn-secondary" style={{ minHeight: 46 }}><Icon name="copy" size={17} />Copy link</button>
        <button onClick={onShared} className="btn btn-secondary" style={{ minHeight: 46 }}><Icon name="share" size={17} />Save image</button>
      </div>
      <button onClick={onShared} className="btn btn-primary btn-block" style={{ minHeight: 48 }}><Icon name="share" size={18} />Share</button>
    </Sheet>
  );
}

Object.assign(window, { RECAPS, getRecap, BeforeAfter, VisitRecap, ShareRecapSheet });
