// Site-visit WHS checklist — industry-aware safety form attached to a customer profile.
// Flow: designer fills checklist + signs → send for signature → customer signs online & consents
// → designer adds post-visit notes → finalise & lock (read-only, saved to the profile).

window.whsTemplate = function (preset) {
  const P = (window.PEARLER_TERMS && window.PEARLER_TERMS.current) || {};
  preset = preset || P.preset || 'kitchens';
  const T = window.T || ((k) => k);
  const kitchens = {
    title: T('rep') + ' on-site consultation',
    sections: [
      { id: 'access', title: 'Site access & entry', items: [
        { id: 'present', label: 'Customer (or authorised adult) is present at the property' },
        { id: 'path', label: 'Safe, unobstructed path from entry to work area confirmed' },
        { id: 'pets', label: 'Pets secured or removed from work area' },
        { id: 'children', label: 'Children are not in the immediate work area during the visit', critical: true },
      ]},
      { id: 'hazards', title: 'Household hazards', items: [
        { id: 'trip', label: 'No trip hazards (cords, rugs, clutter) in the work path' },
        { id: 'elec', label: 'No exposed/faulty electrical wiring near the work area' },
        { id: 'floor', label: 'Floors are dry and stable' },
        { id: 'asbestos', label: 'No suspected asbestos in areas being assessed', critical: true },
        { id: 'lighting', label: 'Adequate lighting in the work area' },
      ]},
      { id: 'equipment', title: 'Team member equipment', items: [
        { id: 'ppe', label: 'Appropriate PPE available (closed shoes, hi-vis if needed)' },
        { id: 'tape', label: 'Measuring & assessment tools in safe working order' },
        { id: 'phone', label: 'Charged mobile phone for emergency contact' },
        { id: 'ladder', label: 'Any ladder/step used is stable and rated' },
      ]},
      { id: 'health', title: 'Health & hygiene', items: [
        { id: 'symptoms', label: 'Team member is well (no infectious symptoms)' },
        { id: 'covid', label: 'Customer household has no current infectious-illness concerns' },
        { id: 'smoke', label: 'Work area is smoke-free during the visit' },
        { id: 'air', label: 'Adequate ventilation in the work area' },
      ]},
      { id: 'emergency', title: 'Emergency preparedness', items: [
        { id: 'exit', label: 'Nearest exit identified' },
        { id: 'contact', label: 'Emergency contact details recorded' },
        { id: 'lone', label: 'Lone-worker check-in arranged with the showroom' },
      ]},
    ],
  };
  const trades = JSON.parse(JSON.stringify(kitchens)); trades.title = T('rep') + ' site assessment';
  const realestate = {
    title: 'Property inspection safety check',
    sections: [
      { id: 'access', title: 'Property access & entry', items: [
        { id: 'present', label: 'Owner/occupant aware of and consents to the inspection' },
        { id: 'path', label: 'Safe access to all areas to be inspected' },
        { id: 'pets', label: 'Pets secured' },
        { id: 'vacant', label: 'If vacant, property is secure and structurally safe to enter', critical: true },
      ]},
      { id: 'hazards', title: 'Property hazards', items: [
        { id: 'trip', label: 'No significant trip/slip hazards' },
        { id: 'struct', label: 'No obvious structural or ceiling concerns', critical: true },
        { id: 'elec', label: 'No exposed electrical hazards' },
        { id: 'mould', label: 'No hazardous mould/damp in inspection areas' },
      ]},
      { id: 'lone', title: 'Lone worker & emergency', items: [
        { id: 'checkin', label: 'Office aware of inspection location & expected finish time' },
        { id: 'phone', label: 'Charged phone carried' },
        { id: 'exit', label: 'Exits identified' },
      ]},
    ],
  };
  const health = {
    title: 'Home visit safety check',
    sections: [
      { id: 'access', title: 'Access & consent', items: [
        { id: 'present', label: 'Client (or carer) is present and consents to the visit' },
        { id: 'path', label: 'Safe access path to the consultation area' },
        { id: 'pets', label: 'Pets secured' },
        { id: 'infection', label: 'No uncontrolled infection-control risk', critical: true },
      ]},
      { id: 'hazards', title: 'Environment', items: [
        { id: 'trip', label: 'No trip hazards' },
        { id: 'hygiene', label: 'Hand-hygiene facilities available' },
        { id: 'space', label: 'Adequate clean space for the consultation' },
      ]},
      { id: 'emergency', title: 'Emergency & lone worker', items: [
        { id: 'exit', label: 'Nearest exit identified' },
        { id: 'checkin', label: 'Lone-worker check-in arranged' },
        { id: 'contact', label: 'Emergency contact recorded' },
      ]},
    ],
  };
  const generic = {
    title: 'On-site visit safety check',
    sections: [
      { id: 'access', title: 'Site access & entry', items: [
        { id: 'present', label: 'Customer (or authorised adult) is present' },
        { id: 'path', label: 'Safe, unobstructed access to the work area' },
        { id: 'pets', label: 'Pets secured or removed from work area' },
        { id: 'children', label: 'Children not in the immediate work area', critical: true },
      ]},
      { id: 'hazards', title: 'Hazards', items: [
        { id: 'trip', label: 'No trip/slip hazards' },
        { id: 'elec', label: 'No exposed electrical hazards' },
        { id: 'floor', label: 'Floors dry and stable' },
      ]},
      { id: 'emergency', title: 'Emergency preparedness', items: [
        { id: 'exit', label: 'Nearest exit identified' },
        { id: 'contact', label: 'Emergency contact recorded' },
        { id: 'lone', label: 'Lone-worker check-in arranged' },
      ]},
    ],
  };
  return { kitchens, trades, realestate, health, retail: generic, auto: generic, services: generic, generic }[preset] || generic;
};

function SignaturePad({ value, onChange, label, disabled }) {
  const canvasRef = React.useRef(null);
  const drawing = React.useRef(false);
  React.useEffect(() => {
    const c = canvasRef.current; if (!c) return;
    const ctx = c.getContext('2d');
    ctx.lineWidth = 2; ctx.lineCap = 'round'; ctx.strokeStyle = '#1a1a1a';
    if (value) { const img = new Image(); img.onload = () => ctx.drawImage(img, 0, 0, c.width, c.height); img.src = value; }
  }, []);
  if (disabled && value) {
    return <div style={{ border: '1px solid var(--border)', borderRadius: 6, background: 'white', height: 120, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><img src={value} alt="signature" style={{ maxHeight: 110, maxWidth: '95%' }}/></div>;
  }
  const pos = (e) => { const c = canvasRef.current; const r = c.getBoundingClientRect(); const t = e.touches ? e.touches[0] : e; return { x: (t.clientX - r.left) * (c.width / r.width), y: (t.clientY - r.top) * (c.height / r.height) }; };
  const start = (e) => { if (disabled) return; e.preventDefault(); drawing.current = true; const ctx = canvasRef.current.getContext('2d'); const p = pos(e); ctx.beginPath(); ctx.moveTo(p.x, p.y); };
  const move = (e) => { if (!drawing.current || disabled) return; e.preventDefault(); const ctx = canvasRef.current.getContext('2d'); const p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); };
  const end = () => { if (!drawing.current) return; drawing.current = false; onChange && onChange(canvasRef.current.toDataURL()); };
  const clear = () => { const c = canvasRef.current; c.getContext('2d').clearRect(0, 0, c.width, c.height); onChange && onChange(''); };
  return (
    <div>
      <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 4 }}>{label}</div>
      <div style={{ position: 'relative', border: '1px solid var(--border-strong)', borderRadius: 6, background: 'white' }}>
        <canvas ref={canvasRef} width={320} height={120} style={{ width: '100%', height: 120, touchAction: 'none', cursor: disabled ? 'default' : 'crosshair' }}
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end}/>
        {!disabled && <button className="btn sm" style={{ position: 'absolute', bottom: 6, left: 6 }} onClick={clear}><Icon name="close" size={10}/> Clear</button>}
      </div>
    </div>
  );
}

function SiteVisitForm({ contact, currentUser, existing, mode, onClose, onSave }) {
  const tmpl = React.useMemo(() => window.whsTemplate(), []);
  const isCustomerMode = mode === 'customer';
  const [v, setV] = React.useState(() => existing || {
    id: 'whs_' + Date.now(), contactId: contact.id, status: 'draft', industry: (window.PEARLER_TERMS && window.PEARLER_TERMS.current && window.PEARLER_TERMS.current.preset) || 'kitchens',
    title: tmpl.title, jobNumber: '', address: contact.address || contact.suburb || '', dateTime: new Date().toISOString().slice(0, 16),
    checks: {}, observations: '', risk: '', teamName: currentUser ? currentUser.name : '', teamSig: '', custName: contact.name || '', custSig: '', custConsent: false,
    finalNotes: '', createdBy: currentUser ? currentUser.name : '', createdAt: new Date().toISOString(),
  });
  const locked = v.status === 'locked';
  const set = (patch) => setV(p => ({ ...p, ...patch }));
  const toggle = (sid, iid) => { if (locked || isCustomerMode) return; const k = sid + '.' + iid; set({ checks: { ...v.checks, [k]: !v.checks[k] } }); };

  const allItems = tmpl.sections.flatMap(s => s.items.map(i => ({ sid: s.id, ...i })));
  const checkedCount = allItems.filter(i => v.checks[i.sid + '.' + i.id]).length;
  const criticalUnmet = allItems.filter(i => i.critical && !v.checks[i.sid + '.' + i.id]);
  const teamReady = v.teamName.trim() && v.teamSig;
  const canSend = checkedCount >= allItems.length - criticalUnmet.length && criticalUnmet.length === 0 && teamReady;

  const sendForSignature = () => { onSave({ ...v, status: 'sent', sentAt: new Date().toISOString() }); };
  const submitCustomer = () => { onSave({ ...v, status: 'signed', signedAt: new Date().toISOString() }); };
  const finaliseLock = () => { onSave({ ...v, status: 'locked', lockedAt: new Date().toISOString() }); };

  const STATUS = { draft: { label: 'Draft', c: 'var(--ink-3)' }, sent: { label: 'Awaiting customer signature', c: 'var(--warn)' }, signed: { label: 'Signed — pending finalise', c: 'var(--info)' }, locked: { label: 'Finalised & locked', c: 'var(--won)' } };
  const st = STATUS[v.status] || STATUS.draft;
  const inputStyle = { width: '100%' };

  return (
    <div>
      <div className="detail-overlay" onClick={onClose} style={{ zIndex: 58 }}/>
      <div className="invite-modal" style={{ zIndex: 59, width: 640, maxWidth: 'calc(100vw - 28px)' }}>
        <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--accent-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={16} color="var(--accent-ink)"/></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 600 }}>{isCustomerMode ? 'Review & sign — safety checklist' : v.title}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{contact.name} · <span style={{ color: st.c, fontWeight: 600 }}>{st.label}</span></div>
          </div>
          <button className="detail-close" onClick={onClose}><Icon name="close" size={16}/></button>
        </div>

        <div style={{ padding: '16px 22px', maxHeight: '70vh', overflowY: 'auto' }}>
          {isCustomerMode && (
            <div style={{ background: 'var(--info-soft)', border: '1px solid color-mix(in oklch, var(--info) 25%, transparent)', borderRadius: 'var(--r-md)', padding: '10px 13px', marginBottom: 14, fontSize: 12, color: 'oklch(0.38 0.09 240)' }}>
              {v.teamName} from {(window.PEARLER_TERMS && window.PEARLER_TERMS.current && 'your provider') || 'us'} has completed a safety checklist for the upcoming visit. Please review, then add your name, signature and consent below.
            </div>
          )}

          {/* Header fields */}
          {!isCustomerMode && (
            <div className="detail-grid" style={{ marginBottom: 16 }}>
              <div className="detail-field"><span className="lbl">Team member</span><input value={v.teamName} onChange={(e) => set({ teamName: e.target.value })} disabled={locked} style={inputStyle}/></div>
              <div className="detail-field"><span className="lbl">Date & time</span><input type="datetime-local" value={v.dateTime} onChange={(e) => set({ dateTime: e.target.value })} disabled={locked} style={inputStyle}/></div>
              <div className="detail-field"><span className="lbl">Job / quote number</span><input value={v.jobNumber} onChange={(e) => set({ jobNumber: e.target.value })} placeholder="e.g. KD-2026-0412" disabled={locked} style={inputStyle}/></div>
              <div className="detail-field"><span className="lbl">Customer address</span><input value={v.address} onChange={(e) => set({ address: e.target.value })} placeholder="Street, suburb, state" disabled={locked} style={inputStyle}/></div>
            </div>
          )}

          {/* Checklist */}
          {tmpl.sections.map(sec => {
            const done = sec.items.filter(i => v.checks[sec.id + '.' + i.id]).length;
            return (
              <div key={sec.id} className="card" style={{ marginBottom: 10 }}>
                <div className="card-hd" style={{ padding: '10px 14px' }}>
                  <div className="card-title" style={{ fontSize: 12.5 }}>{sec.title}</div>
                  <span className="num" style={{ fontSize: 11.5, color: done === sec.items.length ? 'var(--won)' : 'var(--ink-3)' }}>{done}/{sec.items.length}</span>
                </div>
                <div style={{ padding: '4px 0' }}>
                  {sec.items.map(it => {
                    const on = !!v.checks[sec.id + '.' + it.id];
                    return (
                      <label key={it.id} onClick={() => toggle(sec.id, it.id)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 14px', cursor: (locked || isCustomerMode) ? 'default' : 'pointer', fontSize: 12.5 }}>
                        <span className={`checkbox ${on ? 'on' : ''}`}>{on && <Icon name="check" size={10} color="white"/>}</span>
                        <span style={{ flex: 1 }}>{it.label}</span>
                        {it.critical && <span className="pill" style={{ background: 'var(--lost-soft)', color: 'oklch(0.42 0.12 28)', fontSize: 9.5 }}>Critical</span>}
                      </label>
                    );
                  })}
                </div>
              </div>
            );
          })}

          {/* Observations */}
          <div className="detail-field" style={{ marginBottom: 14 }}>
            <span className="lbl">Observations &amp; notes</span>
            <textarea value={v.observations} onChange={(e) => set({ observations: e.target.value })} disabled={locked || isCustomerMode} rows="2" placeholder="Anything noted on site…" style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--border)', borderRadius: 6, fontFamily: 'inherit', fontSize: 12.5, resize: 'vertical' }}/>
          </div>

          {/* Risk */}
          {!isCustomerMode && (
            <div style={{ marginBottom: 16 }}>
              <span className="lbl" style={{ fontSize: 11, color: 'var(--ink-3)' }}>Overall risk rating</span>
              <div style={{ display: 'flex', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
                {[{ k: 'low', l: 'Low risk' }, { k: 'medium', l: 'Medium risk' }, { k: 'high', l: 'High risk — supervisor approval needed' }].map(r => (
                  <button key={r.k} className={`filter-chip ${v.risk === r.k ? 'active' : ''}`} disabled={locked} onClick={() => set({ risk: r.k })}>{r.l}</button>
                ))}
              </div>
              {criticalUnmet.length > 0 && <div style={{ fontSize: 11.5, color: 'var(--lost)', marginTop: 8, display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="alert" size={12}/> {criticalUnmet.length} critical item(s) not met — resolve before proceeding.</div>}
            </div>
          )}

          {/* Declarations & signatures */}
          <div className="card card-pad">
            <div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 4 }}>Declarations &amp; signatures</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 12 }}>Both the team member and customer sign. Signatures are saved to the customer profile.</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <input value={v.teamName} onChange={(e) => set({ teamName: e.target.value })} placeholder="Team member full name" disabled={locked || isCustomerMode} style={{ width: '100%', marginBottom: 8 }}/>
                <SignaturePad label="Team member signature" value={v.teamSig} onChange={(s) => set({ teamSig: s })} disabled={locked || isCustomerMode}/>
              </div>
              <div>
                <input value={v.custName} onChange={(e) => set({ custName: e.target.value })} placeholder="Customer full name" disabled={locked || (!isCustomerMode && v.status !== 'draft')} style={{ width: '100%', marginBottom: 8 }}/>
                <SignaturePad label="Customer signature & consent" value={v.custSig} onChange={(s) => set({ custSig: s })} disabled={locked || (!isCustomerMode && v.status === 'draft')}/>
              </div>
            </div>
            <label style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginTop: 12, fontSize: 11.5, color: 'var(--ink-2)', cursor: (locked) ? 'default' : 'pointer' }} onClick={() => { if (!locked && (isCustomerMode || v.status !== 'sent')) set({ custConsent: !v.custConsent }); }}>
              <span className={`checkbox ${v.custConsent ? 'on' : ''}`} style={{ marginTop: 1 }}>{v.custConsent && <Icon name="check" size={10} color="white"/>}</span>
              <span>By signing, the customer confirms they have been informed of the visit purpose, consent to the team member entering the premises, and acknowledge the hazards identified above. The team member confirms this checklist is accurate.</span>
            </label>
          </div>
        </div>

        {/* Footer actions */}
        <div style={{ padding: '13px 22px', borderTop: '1px solid var(--border)', background: 'var(--surface-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{checkedCount} of {allItems.length} checked</span>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            {isCustomerMode ? (
              <button className="btn primary" disabled={!(v.custName.trim() && v.custSig && v.custConsent)} style={{ opacity: (v.custName.trim() && v.custSig && v.custConsent) ? 1 : 0.5 }} onClick={submitCustomer}><Icon name="check" size={12}/> Submit signed form</button>
            ) : locked ? (
              <span style={{ fontSize: 12, color: 'var(--won)', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="lock" size={12}/> Locked {v.lockedAt ? '· ' + fmt.shortDate(v.lockedAt.slice(0, 10)) : ''}</span>
            ) : v.status === 'draft' ? (
              <React.Fragment>
                <button className="btn" onClick={() => onSave({ ...v })}>Save draft</button>
                <button className="btn primary" disabled={!canSend} style={{ opacity: canSend ? 1 : 0.5 }} onClick={sendForSignature}><Icon name="mail" size={12}/> Submit &amp; send for signature</button>
              </React.Fragment>
            ) : v.status === 'sent' ? (
              <span style={{ fontSize: 12, color: 'var(--warn)' }}>Waiting for the customer to sign online…</span>
            ) : v.status === 'signed' ? (
              <button className="btn primary" onClick={finaliseLock}><Icon name="lock" size={12}/> Finalise &amp; lock</button>
            ) : null}
          </div>
        </div>
      </div>
    </div>
  );
}

window.SiteVisitForm = SiteVisitForm;
