/* ============================================================
   UNSTOPPABLES — New Client Intake (Flow B wizard)
   Category-gated steps · required enforcement · inline "Other →
   specify" · device-persistent draft · review summary →
   hands off to Flow A with the new client pre-filled.
   Exports: IntakeWizard
   ============================================================ */

const INTAKE_DRAFT_KEY = 'trellis_intake_draft_v1';

function wizardSteps(cat, optInImmigration) {
  const S = window.TRELLIS_SCHEMA;
  const ids = ['identity', 'contact', 'background', 'household'];
  if (cat === 'Settlement' || optInImmigration) ids.push('immigration');
  ids.push('services');
  if (cat === 'Domestic Violence') ids.push('dv');
  ids.push('health', 'consent');
  return ids.map(id => S.SECTIONS.find(s => s.id === id));
}

function stepValid(section, draft) {
  const S = window.TRELLIS_SCHEMA;
  let phoneOk = true, ok = true;
  section.fields.forEach(f => {
    if (f.req === true) {
      if (f.type === 'toggle') { if (draft[f.k] !== true) ok = false; }
      else if (!S.filled(draft[f.k])) ok = false;
    }
  });
  if (section.id === 'contact') phoneOk = S.filled(draft.cell) || S.filled(draft.homePhone);
  return ok && phoneOk;
}

/* live-bound field for the wizard */
function WizardField({ field, draft, set }) {
  const v = draft[field.k];
  const [signing, setSigning] = React.useState(false);
  if (field.k === 'clientSignature') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <label style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-soft)', display: 'flex', alignItems: 'center', gap: 6 }}>
          {field.label}<span style={{ color: 'var(--coral)' }}>*</span>
          <Icon name="lock" size={10} node={false} style={{ opacity: 0.6 }} />
        </label>
        {v && String(v).startsWith('data:image') ? (
          <img src={v} alt="Client signature" onClick={() => setSigning(true)} title="Click to re-sign"
            style={{ height: 72, width: 'auto', maxWidth: 300, background: '#fff', borderRadius: 12, border: '1px solid var(--hairline-strong)', cursor: 'pointer', display: 'block' }} />
        ) : (
          <button onClick={() => setSigning(true)} style={{
            alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 8, padding: '12px 20px',
            borderRadius: 13, fontSize: 13.5, fontWeight: 700, background: 'var(--accent)', color: 'var(--accent-ink)', minHeight: 46
          }}><Icon name="plus" size={14} stroke={2.4} node={false} /> Collect client signature</button>
        )}
        {signing && (
          <SignatureModal
            onClose={() => setSigning(false)}
            onDone={url => {
              setSigning(false);
              set(field.k, url);
              set('consentAck', true);
              set('consentDate', new Date().toISOString().slice(0, 10));
            }} />
        )}
      </div>
    );
  }
  const needsSpecify = field.other && (v === 'Other' || (Array.isArray(v) && v.includes('Other')));
  const inputStyle = {
    width: '100%', padding: '12px 14px', borderRadius: 12, border: '1px solid var(--hairline-strong)',
    background: 'var(--glass-input)', fontSize: 14.5, outline: 'none', boxSizing: 'border-box', fontFamily: 'var(--font-body)'
  };
  const chipStyle = on => ({
    padding: '10px 16px', borderRadius: 99, fontSize: 13, fontWeight: 700, minHeight: 42,
    background: on ? 'var(--accent)' : 'var(--hover)', color: on ? 'var(--accent-ink)' : 'var(--ink-soft)',
    border: '1px solid ' + (on ? 'transparent' : 'var(--hairline)'), transition: 'all .15s'
  });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <label style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-soft)', display: 'flex', alignItems: 'center', gap: 6 }}>
        {field.label}{field.req === true && <span style={{ color: 'var(--coral)' }}>*</span>}
        {field.req === 'phone' && <span className="t-faint" style={{ fontWeight: 600, textTransform: 'none', letterSpacing: 0 }}>(one phone required)</span>}
        {field.pii && <Icon name="lock" size={10} node={false} style={{ opacity: 0.6 }} title="Masked once saved" />}
      </label>
      {field.type === 'text' && <input value={v || ''} onChange={e => set(field.k, e.target.value)} placeholder={field.label} style={inputStyle} />}
      {field.type === 'date' && <input type="date" value={v || ''} onChange={e => set(field.k, e.target.value)} style={inputStyle} />}
      {field.type === 'select' && (field.options.length > 7 ? (
        <select value={v || ''} onChange={e => set(field.k, e.target.value)} style={{ ...inputStyle, appearance: 'none' }}>
          <option value="">Choose…</option>
          {field.options.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
          {field.options.map(o => <button key={o} onClick={() => set(field.k, v === o ? '' : o)} style={chipStyle(v === o)}>{v === o ? '✓ ' : ''}{o}</button>)}
        </div>
      ))}
      {field.type === 'multi' && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
          {field.options.map(o => {
            const on = (v || []).includes(o);
            return <button key={o} onClick={() => set(field.k, on ? v.filter(x => x !== o) : [...(v || []), o])} style={chipStyle(on)}>{on ? '✓ ' : ''}{o}</button>;
          })}
        </div>
      )}
      {field.type === 'toggle' && (
        <div style={{ display: 'flex', gap: 7 }}>
          {[[true, 'Yes'], [false, 'No']].map(([val, l]) => <button key={l} onClick={() => set(field.k, val)} style={chipStyle(v === val)}>{l}</button>)}
        </div>
      )}
      {needsSpecify && <input value={draft[field.k + 'Specify'] || ''} onChange={e => set(field.k + 'Specify', e.target.value)} placeholder="Please specify…" style={{ ...inputStyle, borderColor: 'var(--gold-deep)' }} />}
    </div>
  );
}

function IntakeWizard({ push, onComplete, onCancel }) {
  const S = window.TRELLIS_SCHEMA;
  // DV-safety rule: client data never touches localStorage/sessionStorage.
  // Draft lives in memory only — survives step navigation, not a reload.
  const [draft, setDraft] = React.useState(() => window.__EHCW_INTAKE_DRAFT || {});
  const [step, setStep] = React.useState(draft.formCategory ? 1 : 0); // 0 = category gate
  const [optIn, setOptIn] = React.useState(!!draft._optInImmigration);
  const hadDraft = React.useRef(Object.keys(draft).length > 0);
  const [saving, setSaving] = React.useState(false);

  // in-memory draft survives tab switches within the session (not reloads)
  React.useEffect(() => {
    window.__EHCW_INTAKE_DRAFT = { ...draft, _optInImmigration: optIn };
  }, [draft, optIn]);

  const set = (k, val) => setDraft(d => ({ ...d, [k]: val }));
  const cat = draft.formCategory;
  const steps = cat ? wizardSteps(cat, optIn) : [];
  const total = steps.length + 2; // category + sections + review
  const onReview = step === steps.length + 1;
  const active = !onReview && step > 0 ? steps[step - 1] : null;

  const reqMissing = () => {
    const missing = [];
    steps.forEach(sec => { if (!stepValid(sec, draft)) missing.push(sec.label); });
    return missing;
  };

  const submit = async () => {
    setSaving(true);
    const code = 'EH-' + (1900 + Math.floor(Math.random() * 9000));
    const newClient = {
      id: code,
      firstName: draft.firstName, lastName: draft.lastName,
      initials: (draft.firstName[0] + draft.lastName[0]).toUpperCase(),
      displayName: `${draft.firstName} ${draft.lastName[0]}.`,
      category: cat
    };
    // Persist the FULL draft (all schema keys + Specify variants) to Firestore
    if (window.EHCW_DB) {
      try {
        const { _optInImmigration, ...record } = draft;
        const docId = await window.EHCW_DB.saveClient({
          ...record,
          clientCode: code,
          formCategory: cat,
          fullName: `${draft.firstName} ${draft.lastName}`.trim()
        });
        newClient._docId = docId;
      } catch (e) {
        console.error('[EHCW] saveClient failed:', e.code || e.message);
        push('Could not save to database — check connection and retry');
        setSaving(false);
        return;
      }
    }
    window.__EHCW_INTAKE_DRAFT = null;
    push(`${newClient.displayName} registered ✓ ${newClient.id} — PII masked automatically`);
    setSaving(false);
    onComplete(newClient);
  };

  const discard = () => { window.__EHCW_INTAKE_DRAFT = null; setDraft({}); setOptIn(false); setStep(0); };

  const navBtn = (primary, disabled) => ({
    padding: '13px 22px', borderRadius: 14, fontSize: 14, fontWeight: 700, fontFamily: 'var(--font-display)', minHeight: 48,
    background: disabled ? 'var(--hover)' : primary ? 'var(--accent)' : 'var(--hover)',
    color: disabled ? 'var(--ink-faint)' : primary ? 'var(--accent-ink)' : 'var(--ink-soft)',
    border: primary ? 'none' : '1px solid var(--hairline)',
    cursor: disabled ? 'not-allowed' : 'pointer'
  });

  return (
    <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 'clamp(20px, 3vw, 30px)', boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* progress */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 140, height: 6, borderRadius: 99, background: 'var(--hover)', overflow: 'hidden' }}>
          <div style={{ width: `${((step + 1) / total) * 100}%`, height: '100%', borderRadius: 99, background: 'linear-gradient(90deg, var(--accent), oklch(0.78 0.15 88))', transition: 'width .4s var(--ease-spring)' }}></div>
        </div>
        <span className="mono t-faint" style={{ fontSize: 12 }}>Step {step + 1} of {total}</span>
        {hadDraft.current && step > 0 && <Badge tone="gold">Draft restored</Badge>}
        <button onClick={discard} className="t-faint" style={{ fontSize: 12, fontWeight: 700 }}>Discard draft</button>
      </div>

      {/* step 0 — category gate */}
      {step === 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <h3 style={{ fontSize: 18, fontWeight: 700 }}>Form Category <span style={{ color: 'var(--coral)' }}>*</span></h3>
            <p className="t-soft" style={{ fontSize: 13.5, margin: '6px 0 0', lineHeight: 1.55 }}>This gates the rest of intake — only relevant steps will appear. It is required (270 of 391 legacy records were missing it).</p>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 12 }}>
            {S.FORM_CATEGORIES.map(c => {
              const on = cat === c;
              const desc = { 'Food': 'Food bank & day-to-day support', 'Domestic Violence': 'Confidential DV support intake', 'Settlement': 'Newcomer settlement & immigration' }[c];
              return (
                <button key={c} onClick={() => set('formCategory', c)} style={{
                  padding: '18px 16px', borderRadius: 16, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 6,
                  background: on ? 'var(--accent-soft)' : 'var(--hover)',
                  border: on ? '1.5px solid var(--accent)' : '1px solid var(--hairline)', transition: 'all .2s'
                }}>
                  <span style={{ fontSize: 15, fontWeight: 700, color: on ? 'var(--accent)' : 'var(--ink)' }}>{on ? '✓ ' : ''}{c}</span>
                  <span className="t-faint" style={{ fontSize: 12, lineHeight: 1.45 }}>{desc}</span>
                </button>
              );
            })}
          </div>
          {cat === 'Food' && (
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
              <input type="checkbox" checked={optIn} onChange={e => setOptIn(e.target.checked)} style={{ width: 18, height: 18, accentColor: 'var(--accent)' }} />
              Also capture Immigration &amp; Settlement details (optional for Food intakes)
            </label>
          )}
        </div>
      )}

      {/* section steps */}
      {active && (
        <div key={active.id} style={{ display: 'flex', flexDirection: 'column', gap: 18, animation: 'trellis-rise .3s ease' }}>
          <div>
            <h3 style={{ fontSize: 18, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8 }}>
              {active.confidential && <Icon name="shield" size={16} node={false} style={{ color: 'var(--coral)' }} />}{active.label}
            </h3>
            {active.confidential && <p style={{ fontSize: 12.5, margin: '6px 0 0', color: 'var(--coral)', fontWeight: 600 }}>Confidential — visible only inside this record, never in exports.</p>}
            {active.phipa && <p className="t-soft" style={{ fontSize: 12.5, margin: '6px 0 0' }}>PHIPA — health card details get the strongest masking.</p>}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(250px, 100%), 1fr))', gap: 18 }}>
            {active.fields.map(f => <WizardField key={f.k} field={f} draft={draft} set={set} />)}
          </div>
          {!stepValid(active, draft) && (
            <div style={{ padding: '10px 14px', borderRadius: 12, background: 'var(--gold-soft)', fontSize: 12.5, fontWeight: 600 }}>
              Required fields missing on this step — Next unlocks when they&rsquo;re filled.
            </div>
          )}
        </div>
      )}

      {/* review */}
      {onReview && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, animation: 'trellis-rise .3s ease' }}>
          <div>
            <h3 style={{ fontSize: 18, fontWeight: 700 }}>Review &amp; submit</h3>
            <p className="t-soft" style={{ fontSize: 13.5, margin: '6px 0 0' }}>Grouped by section. PII will be masked the moment this is saved.</p>
          </div>
          {steps.map(sec => {
            const fields = sec.fields.filter(f => S.filled(draft[f.k]) || f.req === true);
            const valid = stepValid(sec, draft);
            return (
              <div key={sec.id} className="glass" style={{ borderRadius: 14, padding: '14px 18px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <h4 style={{ fontSize: 13.5, fontWeight: 700 }}>{sec.label}</h4>
                  {!valid && <Badge tone="coral">Missing required</Badge>}
                  <button onClick={() => setStep(steps.indexOf(sec) + 1)} className="t-faint" style={{ marginLeft: 'auto', fontSize: 12, fontWeight: 700 }}>Edit</button>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(220px, 100%), 1fr))', gap: '8px 20px' }}>
                  {fields.map(f => {
                    const v = draft[f.k];
                    return (
                      <div key={f.k} style={{ fontSize: 12.5, display: 'flex', gap: 8, alignItems: 'baseline' }}>
                        <span className="t-faint" style={{ fontWeight: 700, flexShrink: 0 }}>{f.label}:</span>
                        <span style={{ fontWeight: 600, color: S.filled(v) ? 'var(--ink)' : 'var(--coral)' }}>
                          {S.filled(v) ? (Array.isArray(v) ? v.join(', ') : typeof v === 'boolean' ? 'Yes' : String(v).startsWith('data:image') ? '✍ Signed' : String(v)) : '— required'}
                          {draft[f.k + 'Specify'] ? ` → ${draft[f.k + 'Specify']}` : ''}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* nav */}
      <div style={{ display: 'flex', gap: 10, justifyContent: 'space-between', flexWrap: 'wrap' }}>
        <button onClick={() => step === 0 ? onCancel() : setStep(s => s - 1)} style={navBtn(false, false)}>
          {step === 0 ? 'Cancel' : '← Back'}
        </button>
        {onReview ? (
          <button onClick={submit} disabled={reqMissing().length > 0} style={navBtn(true, reqMissing().length > 0)}>
            {reqMissing().length > 0 ? `Missing: ${reqMissing().join(', ')}` : 'Register client → first check-in'}
          </button>
        ) : (
          <button
            onClick={() => setStep(s => s + 1)}
            disabled={step === 0 ? !cat : !stepValid(active, draft)}
            style={navBtn(true, step === 0 ? !cat : !stepValid(active, draft))}>
            Next →
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { IntakeWizard });
