/* ============================================================================
   MOWDEW — Equipment on the record
   "Every visit AND every part, on the record." Track the gear at each property
   (pump, filter, heater, salt cell, robot) and make it homeowner-visible so age
   + warranty feed the no-surprise-charges repair loop.
     • OWNER/PRO  OwnerEquipList / EquipDetail — per-property list, add/edit
     • HOMEOWNER  HomeEquip — calm, proud list + per-item service history
     • LOOP       equipment → scheduled repair → approved → done → timeline
   Reuses the kit (cards, chips, Mono, IconBadge, Sprout/Dewy) + the workitems
   flow (WORK_TYPES, WORKITEMS). Loads after mowdew-workitems.jsx.
   ========================================================================= */

const EQUIP_TYPES = {
  pump:   { label: 'Pump',          life: '8–12 yrs' },
  filter: { label: 'Filter',        life: '1–2 yrs (cartridge)' },
  heater: { label: 'Heater',        life: '7–12 yrs' },
  salt:   { label: 'Salt cell',     life: '3–5 yrs' },
  robot:  { label: 'Robot cleaner', life: '4–6 yrs' },
};

/* Emma's pool gear · 88 Crestline Ave (customer c2) */
const EQUIPMENT = {
  c2: [
    { id: 'e1', type: 'pump', make: 'Pentair', model: 'IntelliFlo VSF', installed: 'Mar 2025', age: 'installed 14 months ago',
      warranty: { until: 'Mar 2027', covered: true }, scene: 'pool',
      history: [{ date: 'Apr 2', label: 'Inspected — running quiet', by: 'Marco' }] },
    { id: 'e2', type: 'filter', make: 'Hayward', model: 'ProGrid · C-7468 cartridge', installed: 'Jan 2024', age: 'installed 2 years ago',
      warranty: { until: 'Jan 2025', covered: false }, scene: 'pool', work: 'w1',
      history: [{ date: 'Apr 2', label: 'Cartridge rinsed', by: 'Marco' }, { date: 'Jan 12', label: 'Cartridge replaced', by: 'Marco', cents: 18000 }] },
    { id: 'e3', type: 'heater', make: 'Raypak', model: 'Digital 266K BTU', installed: 'May 2019', age: 'installed ~7 years ago',
      warranty: { until: 'May 2021', covered: false }, scene: 'pool', nudge: "Your heater's getting on — your pro may suggest a replacement before next winter. No rush.",
      history: [{ date: 'Mar 10', label: 'Pilot & vents checked', by: 'Marco' }] },
    { id: 'e4', type: 'salt', make: 'Pentair', model: 'IntelliChlor IC40', installed: 'Apr 2024', age: 'installed 13 months ago',
      warranty: { until: 'Apr 2027', covered: true }, scene: 'pool',
      history: [{ date: 'Apr 24', label: 'Salt cell cleaned & descaled', by: 'Marco', cents: 9000 }] },
    { id: 'e5', type: 'robot', make: 'Polaris', model: 'VRX iQ+', installed: 'Jun 2025', age: 'installed 11 months ago',
      warranty: { until: 'Jun 2027', covered: true }, scene: 'pool', history: [] },
  ],
};
function equipFor(cid) { return EQUIPMENT[cid] || EQUIPMENT.c2; }

/* ─── Papercraft equipment icons — flat cut-paper, left-lit ─────────── */
function EquipPaper({ type, size = 52 }) {
  const s = { width: size, height: size, display: 'block' };
  const wrap = (kids) => <svg viewBox="0 0 64 64" style={{ ...s, filter: 'drop-shadow(0 3px 4px rgba(27,26,23,.16))' }} aria-hidden="true">{kids}</svg>;
  if (type === 'pump') return wrap(<g>
    <rect x="6" y="34" width="40" height="18" rx="4" fill="#12BCC9" /><rect x="26" y="34" width="20" height="18" rx="4" fill="#0E98A3" />
    <circle cx="44" cy="28" r="16" fill="#46B6F0" /><circle cx="44" cy="28" r="16" fill="#2E9FDC" opacity="0" /><path d="M44 12a16 16 0 0 1 0 32Z" fill="#2E9FDC" />
    <circle cx="44" cy="28" r="6" fill="#FBFAF6" /><circle cx="44" cy="28" r="2.4" fill="#0A767F" />
    <rect x="9" y="50" width="7" height="6" rx="1.5" fill="#1B1A17" /><rect x="34" y="50" width="7" height="6" rx="1.5" fill="#1B1A17" />
    <rect x="4" y="38" width="6" height="9" rx="2" fill="#0A767F" />
  </g>);
  if (type === 'filter') return wrap(<g>
    <path d="M20 18a12 12 0 0 1 24 0v34a4 4 0 0 1-4 4H24a4 4 0 0 1-4-4Z" fill="#12BCC9" />
    <path d="M32 6a12 12 0 0 1 12 12v34a4 4 0 0 1-4 4h-8Z" fill="#0E98A3" />
    <rect x="18" y="30" width="28" height="6" fill="#0A767F" />
    <circle cx="32" cy="14" r="4" fill="#FBFAF6" /><circle cx="32" cy="14" r="1.6" fill="#0A767F" />
    <rect x="29" y="54" width="6" height="6" fill="#1B1A17" />
  </g>);
  if (type === 'heater') return wrap(<g>
    <rect x="8" y="14" width="48" height="38" rx="5" fill="#46B6F0" /><path d="M32 14h24v38H32Z" fill="#2E9FDC" />
    <path d="M14 20h36M14 26h36M14 32h28" stroke="#FBFAF6" strokeWidth="2.4" strokeLinecap="round" opacity=".75" />
    <path d="M32 38c2.5 2 3.5 3.6 3.5 5.2A3.5 3.5 0 0 1 28.5 43c0-1.6 1-3.2 3.5-5.2Z" fill="#FFCB3D" />
    <path d="M34 40.5c1.4 1.1 2 2 2 2.9a2 2 0 1 1-4 0c0-.9.6-1.8 2-2.9Z" fill="#F2683C" />
    <rect x="13" y="52" width="6" height="6" rx="1.5" fill="#1B1A17" /><rect x="45" y="52" width="6" height="6" rx="1.5" fill="#1B1A17" />
  </g>);
  if (type === 'salt') return wrap(<g>
    <rect x="10" y="20" width="44" height="24" rx="6" fill="#12BCC9" /><path d="M32 20h22v24H32Z" fill="#0E98A3" />
    <rect x="20" y="24" width="24" height="16" rx="3" fill="#E2F8FA" />
    <path d="M24 26v12M30 26v12M36 26v12M42 26v12" stroke="#0A767F" strokeWidth="2" />
    <rect x="6" y="28" width="6" height="8" rx="2" fill="#0A767F" /><rect x="52" y="28" width="6" height="8" rx="2" fill="#0A767F" />
    <path d="M48 14l1.4 3.2L52.6 18l-2.2 2.4.5 3.3-2.9-1.6-2.9 1.6.5-3.3L43.4 18l3.2-.8Z" fill="#FFCB3D" />
  </g>);
  // robot
  return wrap(<g>
    <path d="M10 44a22 16 0 0 1 44 0v4a4 4 0 0 1-4 4H14a4 4 0 0 1-4-4Z" fill="#46B6F0" />
    <path d="M32 28a22 16 0 0 1 22 16v4a4 4 0 0 1-4 4H32Z" fill="#2E9FDC" />
    <rect x="22" y="34" width="20" height="8" rx="4" fill="#1B1A17" /><circle cx="28" cy="38" r="2" fill="#46B6F0" /><circle cx="36" cy="38" r="2" fill="#46B6F0" />
    <rect x="12" y="50" width="40" height="6" rx="3" fill="#0A767F" />
    <path d="M50 28c8-4 10-12 6-18" stroke="#FFCB3D" strokeWidth="3" fill="none" strokeLinecap="round" />
  </g>);
}

/* ─── Warranty chip — green covered / grey expired ──────────────────── */
function WarrantyChip({ warranty, size = 'md' }) {
  const big = size === 'lg';
  const c = warranty.covered
    ? ['var(--green-50)', 'var(--green-100)', 'var(--green-700)', 'shield']
    : ['var(--ink-50)', 'var(--ink-100)', 'var(--ink-500)', 'clock'];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: c[0], border: `1px solid ${c[1]}`, borderRadius: 9, padding: big ? '6px 11px' : '4px 9px', flexShrink: 0 }}>
      <Icon name={c[3]} size={big ? 14 : 12} style={{ color: c[2] }} strokeWidth={2.4} />
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: big ? 11 : 10, fontWeight: 600, letterSpacing: '.04em', color: c[2], whiteSpace: 'nowrap' }}>
        {warranty.covered ? `WARRANTY TO ${warranty.until.toUpperCase()}` : 'WARRANTY EXPIRED'}
      </span>
    </span>
  );
}

/* ─── Repair-loop chain — equipment → scheduled → approved → done → timeline ── */
function EquipRepairChain({ stage = 1 }) {
  const steps = [['Equipment', 'flask'], ['Scheduled', 'calendar'], ['Approved', 'check'], ['Done', 'shield'], ['Timeline', 'ledger']];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
      {steps.map(([lb, ic], i) => {
        const done = i <= stage;
        return (
          <React.Fragment key={lb}>
            {i > 0 && <span style={{ flex: 1, height: 2, background: i <= stage ? 'var(--aqua-500)' : 'var(--ink-100)', borderRadius: 2 }} />}
            <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, flexShrink: 0 }}>
              <span style={{ width: 26, height: 26, borderRadius: '50%', display: 'grid', placeItems: 'center', background: done ? 'var(--aqua-500)' : '#fff', border: done ? 'none' : '1.5px solid var(--ink-200)', color: done ? '#fff' : 'var(--ink-400,#A8A498)' }}><Icon name={ic} size={13} strokeWidth={2.4} /></span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 8, letterSpacing: '.04em', color: done ? 'var(--aqua-700)' : 'var(--ink-400,#A8A498)', whiteSpace: 'nowrap' }}>{lb.toUpperCase()}</span>
            </span>
          </React.Fragment>
        );
      })}
    </div>
  );
}

/* ─── Equipment row (used by owner/pro list + homeowner list) ───────── */
function EquipRow({ eq, onClick, homeowner }) {
  const t = EQUIP_TYPES[eq.type];
  return (
    <div onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', cursor: onClick ? 'pointer' : 'default' }}>
      <EquipPaper type={eq.type} size={46} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.label} · {eq.make}</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-500)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{homeowner ? eq.age : `${eq.model} · ${eq.installed}`}</div>
        <div style={{ marginTop: 6 }}><WarrantyChip warranty={eq.warranty} /></div>
      </div>
      {onClick && <Icon name="chevron-right" size={17} style={{ color: 'var(--ink-300)', flexShrink: 0 }} />}
    </div>
  );
}

/* ============================================================================
   OWNER / PRO — Equipment list on the property
   ========================================================================= */
function OwnerEquipList({ go, params, toast, pro }) {
  const cid = (params && params.id) || 'c2';
  const c = (window.CUSTOMERS || []).find(x => x.id === cid) || { name: 'Emma Walsh', label: 'Crestline Ave', addr: '88 Crestline Ave', city: 'San Jose' };
  const [list, setList] = React.useState(equipFor(cid));
  const [add, setAdd] = React.useState(false);
  const title = pro ? `${c.label} pool` : c.name;
  const sub = pro ? 'Equipment on this property' : `${c.addr} · equipment`;
  const back = () => pro ? go('pro_visit', { id: 's2' }) : go('o_customer', { id: cid });

  const addItem = (item) => { setList(l => [...l, { ...item, id: 'e' + (l.length + 9), history: [] }]); setAdd(false); toast && toast('Equipment added · on the record', 'green'); };

  return (
    <Screen padBottom={26} footer={
      <ActionBar><button onClick={() => setAdd(true)} className="btn btn-primary btn-lg btn-block"><Icon name="plus" size={20} strokeWidth={2.4} />Add equipment</button></ActionBar>}>
      <TopBar title="Equipment" subtitle={sub} onBack={back}
        right={pro ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--ink-50)', borderRadius: 99, padding: '5px 10px', fontSize: 11, fontWeight: 700, color: 'var(--ink-500)' }}><Icon name="lock" size={12} />Private</span> : null} />

      {list.length === 0 ? (
        <div style={{ padding: '24px 18px 0', textAlign: 'center' }}>
          <Sprout size={92} mood="wink" />
          <h1 style={{ fontSize: 22, marginTop: 12 }}>No equipment on file yet</h1>
          <p style={{ fontSize: 14, color: 'var(--ink-500)', marginTop: 6, lineHeight: 1.55, maxWidth: 290, marginLeft: 'auto', marginRight: 'auto' }}>Add the pump, filter, heater and salt cell here. Once it's on the record, age &amp; warranty drive the no-surprise repair loop.</p>
          <button onClick={() => setAdd(true)} className="btn btn-primary" style={{ marginTop: 16, minHeight: 46, padding: '0 22px' }}><Icon name="plus" size={19} strokeWidth={2.4} />Add the first piece</button>
        </div>
      ) : (
        <>
          <div style={{ padding: '4px 18px 0' }}>
            <SectionHead tone="aqua" icon="flask" style={{ marginBottom: 10 }} meta={`${list.length} items`}>On the record</SectionHead>
            <div className="card" style={{ overflow: 'hidden' }}>
              {list.map((eq, i) => (
                <div key={eq.id} style={{ borderTop: i ? '1px solid var(--ink-100)' : 'none' }}>
                  <EquipRow eq={eq} onClick={() => go(pro ? 'pro_equip_detail' : 'o_equip_detail', { id: cid, eq: eq.id })} />
                </div>
              ))}
            </div>
          </div>
          {!pro && (
            <div style={{ padding: '14px 18px 0' }}>
              <div className="card" style={{ padding: 13, display: 'flex', alignItems: 'center', gap: 11, background: 'var(--aqua-50)', borderColor: 'var(--aqua-100)' }}>
                <Dewy size={40} mood="happy" />
                <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-700)', lineHeight: 1.45 }}>{c.name.split(' ')[0]} sees this list too — what's installed, how old, and what's under warranty. Trust built in.</div>
              </div>
            </div>
          )}
        </>
      )}

      <EquipAddSheet open={add} onClose={() => setAdd(false)} onSave={addItem} />
    </Screen>
  );
}

/* ─── Add / edit equipment form (sheet) ─────────────────────────────── */
function EquipAddSheet({ open, onClose, onSave, initial }) {
  const [type, setType] = React.useState(initial ? initial.type : 'pump');
  const [make, setMake] = React.useState(initial ? initial.make : '');
  const [model, setModel] = React.useState(initial ? initial.model : '');
  const [installed, setInstalled] = React.useState(initial ? initial.installed : '');
  const [wlen, setWlen] = React.useState(initial ? null : '2 yr');
  const [photo, setPhoto] = React.useState(!!initial);
  const [notes, setNotes] = React.useState(initial ? (initial.notes || '') : '');
  const ready = make.trim() && model.trim() && installed.trim();
  const save = () => {
    const covered = wlen !== 'None';
    onSave({ type, make: make.trim(), model: model.trim(), installed: installed.trim(), notes: notes.trim(), scene: 'pool',
      warranty: { until: covered ? '2027' : installed, covered }, age: `installed ${installed}` });
  };
  return (
    <Sheet open={open} onClose={onClose} title={initial ? 'Edit equipment' : 'Add equipment'}>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 8 }}>Type</div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
        {Object.keys(EQUIP_TYPES).map(k => {
          const on = type === k;
          return (
            <button key={k} onClick={() => setType(k)} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, padding: '9px 8px', width: 'calc(20% - 7px)', borderRadius: 12, border: on ? '2px solid var(--aqua-500)' : '1.5px solid var(--ink-100)', background: on ? 'var(--aqua-50)' : '#fff', cursor: 'pointer' }}>
              <EquipPaper type={k} size={34} />
              <span style={{ fontSize: 9.5, fontWeight: 700, color: on ? 'var(--aqua-700)' : 'var(--ink-600,#6E6B60)', textAlign: 'center', lineHeight: 1.1 }}>{EQUIP_TYPES[k].label}</span>
            </button>
          );
        })}
      </div>
      <div style={{ display: 'grid', gap: 10, marginBottom: 14 }}>
        <input className="input" placeholder="Make — e.g. Pentair" value={make} onChange={e => setMake(e.target.value)} style={{ padding: '12px 13px', fontSize: 14 }} />
        <input className="input" placeholder="Model — e.g. IntelliFlo VSF" value={model} onChange={e => setModel(e.target.value)} style={{ padding: '12px 13px', fontSize: 14 }} />
        <input className="input" placeholder="Installed — e.g. Mar 2025" value={installed} onChange={e => setInstalled(e.target.value)} style={{ padding: '12px 13px', fontSize: 14 }} />
      </div>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 8 }}>Warranty length</div>
      <div style={{ display: 'flex', gap: 7, marginBottom: 14, flexWrap: 'wrap' }}>
        {['1 yr', '2 yr', '3 yr', '5 yr', 'None'].map(w => (
          <button key={w} onClick={() => setWlen(w)} style={{ padding: '8px 13px', borderRadius: 11, border: wlen === w ? '2px solid var(--green-500)' : '1.5px solid var(--ink-200)', background: wlen === w ? 'var(--green-50)' : '#fff', color: wlen === w ? 'var(--green-800)' : 'var(--ink-700)', fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>{w}</button>
        ))}
      </div>
      <button onClick={() => setPhoto(true)} className="btn btn-secondary btn-block" style={{ marginBottom: 14 }}><Icon name="camera" size={18} />{photo ? 'Photo attached ✓' : 'Add a photo'}</button>
      <textarea className="input" rows={2} placeholder="Notes (optional) — e.g. variable-speed, runs 8 hrs/day" value={notes} onChange={e => setNotes(e.target.value)} style={{ resize: 'none', lineHeight: 1.5, marginBottom: 14 }} />
      <button onClick={save} disabled={!ready} className="btn btn-primary btn-block" style={{ minHeight: 48 }}><Icon name="check-circle" size={19} />{initial ? 'Save changes' : 'Add to the record'}</button>
    </Sheet>
  );
}

/* ============================================================================
   OWNER / PRO — Equipment detail (history + the repair loop)
   ========================================================================= */
function EquipDetail({ go, params, toast, pro }) {
  const cid = (params && params.id) || 'c2';
  const eq = equipFor(cid).find(x => x.id === (params && params.eq)) || equipFor(cid)[0];
  const t = EQUIP_TYPES[eq.type];
  const c = (window.CUSTOMERS || []).find(x => x.id === cid) || { name: 'Emma Walsh', label: 'Crestline Ave' };
  const [edit, setEdit] = React.useState(false);
  const linkedWork = eq.work ? (window.WORKITEMS || []).find(w => w.id === eq.work) : null;

  return (
    <Screen padBottom={26} footer={
      <ActionBar>
        <button onClick={() => setEdit(true)} className="btn btn-secondary" style={{ flex: 1 }}><Icon name="flask" size={17} />Edit</button>
        <button onClick={() => go(pro ? 'pro_visit' : 'o_schedule_work', pro ? { id: 's2' } : { id: cid, equip: eq.id })} className="btn btn-primary" style={{ flex: 1.4 }}><Icon name="filter" size={17} />{pro ? 'Flag for repair' : 'Schedule work'}</button>
      </ActionBar>}>
      <TopBar title={`${t.label} · ${eq.make}`} subtitle={eq.model} onBack={() => go(pro ? 'pro_equipment' : 'o_equipment', { id: cid })} />

      {/* hero */}
      <div style={{ padding: '4px 18px 0' }}>
        <div className="card" style={{ padding: 16, borderColor: 'var(--aqua-100)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <span style={{ width: 76, height: 76, borderRadius: 18, background: 'var(--aqua-50)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><EquipPaper type={eq.type} size={56} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 19, letterSpacing: '-0.02em' }}>{eq.make} {t.label.toLowerCase()}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 2 }}>{eq.model}</div>
              <div style={{ marginTop: 9 }}><WarrantyChip warranty={eq.warranty} size="lg" /></div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 14 }}>
            <div style={{ background: 'var(--paper)', border: '1px solid var(--ink-100)', borderRadius: 12, padding: '10px 12px' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.06em', color: 'var(--ink-500)' }}>INSTALLED</div>
              <div style={{ fontWeight: 700, fontSize: 14, marginTop: 2 }}>{eq.installed}</div>
            </div>
            <div style={{ background: 'var(--paper)', border: '1px solid var(--ink-100)', borderRadius: 12, padding: '10px 12px' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.06em', color: 'var(--ink-500)' }}>TYPICAL LIFE</div>
              <div style={{ fontWeight: 700, fontSize: 14, marginTop: 2 }}>{t.life}</div>
            </div>
          </div>
        </div>
      </div>

      {/* gentle age nudge */}
      {eq.nudge && (
        <div style={{ padding: '14px 18px 0' }}>
          <div className="card" style={{ padding: 13, display: 'flex', alignItems: 'flex-start', gap: 11, background: 'var(--yellow-50)', borderColor: 'var(--yellow-100)' }}>
            <span style={{ width: 36, height: 36, borderRadius: 10, background: '#fff', border: '1px solid var(--yellow-100)', display: 'grid', placeItems: 'center', color: 'var(--yellow-700)', flexShrink: 0 }}><Icon name="clock" size={18} /></span>
            <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-700)', lineHeight: 1.5 }}>{eq.nudge}</div>
          </div>
        </div>
      )}

      {/* the repair loop, made visible */}
      {linkedWork && (
        <div style={{ padding: '16px 18px 0' }}>
          <SectionHead tone="aqua" icon="filter" style={{ marginBottom: 12 }}>Repair on the way</SectionHead>
          <div className="card" style={{ padding: 16 }}>
            <EquipRepairChain stage={1} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginTop: 14, paddingTop: 13, borderTop: '1px solid var(--ink-100)' }}>
              <IconBadge icon="filter" tone="aqua" size={38} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 13.5 }}>{linkedWork.label} · {fmtMoney(linkedWork.cost)}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>{linkedWork.date} · waiting on {c.name.split(' ')[0]}'s OK</div>
              </div>
              <Mono tone="ink" icon="clock">SENT</Mono>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-500)', marginTop: 11, lineHeight: 1.45 }}>When it's done it appends to this item's history below — equipment, repair, price and proof, all on one record.</div>
          </div>
        </div>
      )}

      {/* service history tied to THIS item */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="green" icon="ledger" style={{ marginBottom: 12 }} meta={`${eq.history.length} on record`}>Service history</SectionHead>
        {eq.history.length === 0 ? (
          <div className="card" style={{ padding: '20px 14px', textAlign: 'center' }}>
            <Dewy size={62} mood="happy" />
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15, marginTop: 6 }}>Brand new — nothing to service yet</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 3 }}>Every clean, repair or part lands here automatically.</div>
          </div>
        ) : (
          <div style={{ position: 'relative', paddingLeft: 4 }}>
            <div style={{ position: 'absolute', left: 21, top: 8, bottom: 8, width: 2, background: 'var(--ink-100)' }} />
            <div style={{ display: 'grid', gap: 12 }}>
              {eq.history.map((h, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, position: 'relative' }}>
                  <span style={{ width: 34, height: 34, borderRadius: '50%', background: h.cents ? 'var(--aqua-500)' : 'var(--green-500)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0, zIndex: 1, border: '3px solid var(--paper)' }}><Icon name={h.cents ? 'filter' : 'check'} size={15} strokeWidth={2.4} /></span>
                  <div className="card" style={{ flex: 1, minWidth: 0, padding: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ flex: 1, minWidth: 0, fontWeight: 700, fontSize: 13.5 }}>{h.label}</div>
                      {h.cents ? <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13, color: 'var(--ink-900)' }}>{fmtMoney(h.cents)}</span> : null}
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-500)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>{h.date}{h.by ? ` · ${h.by}` : ''}{h.cents ? <Mono tone="blue" icon="shield">ON INVOICE</Mono> : <Mono tone="blue" icon="shield">VERIFIED</Mono>}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      <EquipAddSheet open={edit} onClose={() => setEdit(false)} onSave={() => { setEdit(false); toast && toast('Equipment updated', 'green'); }} initial={eq} />
    </Screen>
  );
}

/* ============================================================================
   HOMEOWNER — Your equipment (calm, proud, never a hard upsell)
   ========================================================================= */
function HomeEquip({ go }) {
  const list = equipFor('c2');
  const covered = list.filter(e => e.warranty.covered).length;
  return (
    <Screen padBottom={26} footer={<TabBar role="homeowner" active="h_chem" go={go} onFab={() => go('h_request')} />}>
      <div style={{ padding: '8px 18px 6px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--aqua-500)', display: 'grid', placeItems: 'center', color: '#fff' }}><Icon name="flask" size={21} /></span>
        <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 equipment</div>
        </div>
        <Dewy size={42} mood="happy" />
      </div>

      {/* proud summary */}
      <div style={{ padding: '6px 18px 0' }}>
        <div className="card card-feature" style={{ padding: 16, borderColor: 'var(--aqua-100)', background: 'var(--aqua-50)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
            <Sprout size={56} mood="happy" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, letterSpacing: '-0.02em' }}>{list.length} pieces, on the record</div>
              <div style={{ fontSize: 13, color: 'var(--ink-700)', marginTop: 3, lineHeight: 1.45 }}>{covered} under warranty. Your pro tracks every part's age — so a repair is never a surprise.</div>
            </div>
          </div>
        </div>
      </div>

      {/* the list */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="aqua" icon="ledger" style={{ marginBottom: 10 }} meta="tap for history">What's installed</SectionHead>
        <div className="card" style={{ overflow: 'hidden' }}>
          {list.map((eq, i) => (
            <div key={eq.id} style={{ borderTop: i ? '1px solid var(--ink-100)' : 'none' }}>
              <EquipRow eq={eq} homeowner onClick={() => go('h_equip_detail', { eq: eq.id })} />
              {eq.nudge && (
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, margin: '0 14px 13px', padding: '9px 11px', background: 'var(--yellow-50)', border: '1px solid var(--yellow-100)', borderRadius: 11 }}>
                  <Icon name="clock" size={14} style={{ color: 'var(--yellow-700)', flexShrink: 0, marginTop: 1 }} />
                  <span style={{ fontSize: 11.5, color: 'var(--ink-700)', lineHeight: 1.45 }}>{eq.nudge}</span>
                </div>
              )}
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, padding: '11px 13px', background: 'var(--aqua-50)', borderRadius: 12 }}>
          <Icon name="shield" size={16} style={{ color: 'var(--aqua-700)', flexShrink: 0 }} />
          <span style={{ fontSize: 12, color: 'var(--ink-700)', lineHeight: 1.45 }}>Every part, on the record — added by your pro on a verified visit. Tap any item for its full service history.</span>
        </div>
      </div>
    </Screen>
  );
}

/* HOMEOWNER — per-item detail (history-first, warm) */
function HomeEquipDetail({ go, params }) {
  const eq = equipFor('c2').find(x => x.id === (params && params.eq)) || equipFor('c2')[0];
  const t = EQUIP_TYPES[eq.type];
  return (
    <Screen padBottom={26} footer={<TabBar role="homeowner" active="h_chem" go={go} onFab={() => go('h_request')} />}>
      <TopBar title={`${t.label}`} subtitle={`${eq.make} · ${eq.model}`} onBack={() => go('h_equipment')} />
      <div style={{ padding: '4px 18px 0' }}>
        <div className="card" style={{ padding: 16, borderColor: 'var(--aqua-100)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <span style={{ width: 72, height: 72, borderRadius: 18, background: 'var(--aqua-50)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><EquipPaper type={eq.type} size={54} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, letterSpacing: '-0.02em' }}>{eq.make} {t.label.toLowerCase()}</div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 2 }}>{eq.age}</div>
              <div style={{ marginTop: 9 }}><WarrantyChip warranty={eq.warranty} size="lg" /></div>
            </div>
          </div>
        </div>
      </div>
      {eq.nudge && (
        <div style={{ padding: '14px 18px 0' }}>
          <div className="card" style={{ padding: 13, display: 'flex', alignItems: 'flex-start', gap: 11, background: 'var(--yellow-50)', borderColor: 'var(--yellow-100)' }}>
            <Dewy size={40} mood="wink" />
            <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-700)', lineHeight: 1.5 }}>{eq.nudge}</div>
          </div>
        </div>
      )}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHead tone="green" icon="ledger" style={{ marginBottom: 12 }}>Service history</SectionHead>
        {eq.history.length === 0 ? (
          <div className="card" style={{ padding: '20px 14px', textAlign: 'center' }}>
            <Dewy size={62} mood="happy" />
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15, marginTop: 6 }}>Nothing needed yet</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 3 }}>It's new — when your pro services it, you'll see it here.</div>
          </div>
        ) : (
          <div className="card" style={{ overflow: 'hidden' }}>
            {eq.history.map((h, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderTop: i ? '1px solid var(--ink-100)' : 'none' }}>
                <span style={{ width: 36, height: 36, borderRadius: 10, background: h.cents ? 'var(--aqua-50)' : 'var(--green-50)', display: 'grid', placeItems: 'center', color: h.cents ? 'var(--aqua-700)' : 'var(--green-700)', flexShrink: 0 }}><Icon name={h.cents ? 'filter' : 'check-circle'} size={18} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13.5 }}>{h.label}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>{h.date}{h.by ? ` · ${h.by}` : ''}</div>
                </div>
                {h.cents ? <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14 }}>{fmtMoney(h.cents)}</span> : <Mono tone="blue" icon="shield">VERIFIED</Mono>}
              </div>
            ))}
          </div>
        )}
      </div>
    </Screen>
  );
}

Object.assign(window, {
  EQUIP_TYPES, EQUIPMENT, equipFor, EquipPaper, WarrantyChip, EquipRepairChain, EquipRow, EquipAddSheet,
  OwnerEquipList, EquipDetail, HomeEquip, HomeEquipDetail,
});
