// ─────────────────────────────────────────────────────────────
// Section 4 - Insurance & Health
// Insurer-grade depth with progressive disclosure.
//
// Design intent: a healthy client with no history sees ~12 macro
// questions and finishes in minutes. A client with disclosures
// expands naturally as they tick relevant items, with each ticked
// condition opening a 12-question medical questionnaire (the
// universal block insurers use).
//
// Sourced from the merged superset of TAL Accelerated Protection
// Data Capture v12/2025 + NEOS Protection Data Capture F003_0325.
// ─────────────────────────────────────────────────────────────

// ─── Reference data ─────────────────────────────────────────
const COVER_TYPES = [
  { id: 'life',   label: 'Life Cover' },
  { id: 'tpd',    label: 'Total & Permanent Disability (TPD)' },
  { id: 'trauma', label: 'Trauma / Critical Illness' },
  { id: 'ip',     label: 'Income Protection' },
];

const PURSUIT_OPTIONS = [
  { id: 'aviation',  label: 'Private aviation / piloting' },
  { id: 'diving',    label: 'Scuba / underwater diving' },
  { id: 'motor',     label: 'Motor sport (car / motorbike / boat)' },
  { id: 'climbing',  label: 'Rock or mountain climbing' },
  { id: 'football',  label: 'Football (any code)' },
  { id: 'parachute', label: 'Parachuting / skydiving / BASE jumping' },
  { id: 'horse',     label: 'Equestrian / horse racing / polo' },
  { id: 'martial',   label: 'Martial arts / combat sports' },
  { id: 'sailing',   label: 'Ocean sailing / powerboat racing' },
  { id: 'extreme',   label: 'Other extreme sport (caving, abseiling, base jumping)' },
];

// Family history list - drawn from TAL S16 + NEOS S8 superset.
// `relativeOptions` is what shows in the per-relative checkbox grid: most items
// map 1:1 to their label, but `breast` splits out into three sub-conditions so a
// relative can be marked with the specific one(s) they had.
const FAMILY_CONDITIONS = [
  // The top-level chip stays as the broad grouping (it's how insurers word
  // the question), but the per-relative grid splits it out so the client can
  // say WHICH cardiovascular event the relative actually had - "father had
  // angina at 55" underwrites very differently to "father had a stroke at 55".
  // "Unsure which" mirrors the Diabetes item for clients who only know it was
  // something cardiac.
  { id: 'heart',     label: 'Heart disease, heart attack, angina or stroke',
    relativeOptions: ['Heart disease','Heart attack','Angina','Stroke','Unsure which'] },
  { id: 'cardio',    label: 'Cardiomyopathy',
    relativeOptions: ['Cardiomyopathy'] },
  { id: 'breast',    label: 'Breast, cervical or ovarian cancer',
    relativeOptions: ['Breast cancer','Cervical cancer','Ovarian cancer'] },
  { id: 'bowel',     label: 'Bowel cancer or polyposis of the colon',
    relativeOptions: ['Bowel cancer or polyposis of the colon'] },
  { id: 'cancer',    label: 'Any other type of cancer',
    relativeOptions: ['Any other type of cancer'] },
  { id: 'diabetes',  label: 'Diabetes',
    relativeOptions: ['Type 1 diabetes','Type 2 diabetes','Unsure'] },
  { id: 'kidney',    label: 'Polycystic kidney disease',
    relativeOptions: ['Polycystic kidney disease'] },
  { id: 'alz',       label: 'Alzheimer\u2019s disease',
    relativeOptions: ['Alzheimer\u2019s disease'] },
  { id: 'ms',        label: 'Multiple sclerosis',
    relativeOptions: ['Multiple sclerosis'] },
  { id: 'neuro',     label: 'Motor neurone disease, Parkinson\u2019s, Huntington\u2019s or other inherited / neurological disorder',
    relativeOptions: ['Motor neurone disease, Parkinson\u2019s, Huntington\u2019s or other inherited / neurological disorder'] },
  { id: 'muscular',  label: 'Muscular dystrophy',
    relativeOptions: ['Muscular dystrophy'] },
];

// Medical history - grouped by body-system category for clarity.
// Order: 5 YEARS first → EVER (with anything covered in 5y omitted).
// Each item carries an `examples` list used to populate the deep-dive dropdown.
//
// The lists themselves live in factfind/med-catalogue.js because the
// validator needs them too and it also runs server-side, where JSX can't
// be parsed. That file MUST be loaded before this one.
const MED_CATALOGUE = (typeof globalThis !== 'undefined' ? globalThis : window).MED_CATALOGUE;
const MED_CATEGORIES = MED_CATALOGUE.MED_CATEGORIES;
const MED_CATEGORIES_EVER = MED_CATALOGUE.MED_CATEGORIES_EVER;
const MED_RECENT = MED_CATALOGUE.MED_RECENT;
const MED_NONE_KEYS = MED_CATALOGUE.MED_NONE_KEYS;
const MED_NONE_KEY_OF_ITEM = MED_CATALOGUE.MED_NONE_KEY_OF_ITEM;
const RECENT_NONE_KEY = MED_CATALOGUE.RECENT_NONE_KEY;

// The last-2-years group is a single flat question rather than a set of
// categories, so it borrows the category shape to reuse the same
// "None of the above" machinery. Its key is `recent.all`.
const RECENT_AS_CATEGORY = { id: 'all', items: MED_RECENT };

// Items in the EVER list that are already implicitly covered by an item in the
// 5-year list - used to skip them so we don't double-ask.
// (Only applies when the 5-year version was actually ticked.)
const EVER_DEDUP = {
  // No exact overlaps right now - the 5y list covers softer presentations,
  // the ever list covers serious / acute events. Reserved for future tuning.
};

// Items that should NOT show the per-condition tests/x-ray + hospitalisation
// follow-ups (they don't logically apply to mental-health items).
const MENTAL_HEALTH_IDS = new Set(['mental_common','mental_severe','mental_susi']);

// 3-month "very recent" symptom checklist (NEOS S9.9)
const RECENT_SYMPTOMS = [
  'Persistent cough lasting more than 3 weeks',
  'Symptoms of COVID-19 which are current / ongoing',
  'Onset of fits or seizures',
  'A mole or skin lesion that has changed in appearance',
  'Bleeding from the bowels or change in bowel habits',
  'A lump, growth, swelling or hardening of any kind',
  'Unexplained weight loss',
  'Other new or unexplained symptom',
];

// Countries - full alphabetical list. AU and NZ are kept pinned at the
// top because the question is "are you travelling outside Australia /
// NZ?" and those are the most-clicked options - everything below them
// is in strict A-Z order so the client can find any destination fast.
const COUNTRY_LIST = (() => {
  const pinned = ['Australia', 'New Zealand'];
  const rest = [
    'Afghanistan','Albania','Algeria','Andorra','Angola','Antigua and Barbuda','Argentina','Armenia',
    'Austria','Azerbaijan','Bahamas','Bahrain','Bangladesh','Barbados','Belarus','Belgium',
    'Belize','Benin','Bhutan','Bolivia','Bosnia and Herzegovina','Botswana','Brazil','Brunei',
    'Bulgaria','Burkina Faso','Burundi','Cabo Verde','Cambodia','Cameroon','Canada','Central African Republic',
    'Chad','Chile','China','Colombia','Comoros','Congo (Brazzaville)','Congo (Kinshasa)','Costa Rica',
    'Croatia','Cuba','Cyprus','Czech Republic','Denmark','Djibouti','Dominica','Dominican Republic',
    'Ecuador','Egypt','El Salvador','Equatorial Guinea','Eritrea','Estonia','Eswatini','Ethiopia',
    'Fiji','Finland','France','Gabon','Gambia','Georgia','Germany','Ghana','Greece','Grenada',
    'Guatemala','Guinea','Guinea-Bissau','Guyana','Haiti','Honduras','Hong Kong','Hungary','Iceland',
    'India','Indonesia','Iran','Iraq','Ireland','Israel','Italy','Ivory Coast','Jamaica','Japan',
    'Jordan','Kazakhstan','Kenya','Kiribati','Kosovo','Kuwait','Kyrgyzstan','Laos','Latvia','Lebanon',
    'Lesotho','Liberia','Libya','Liechtenstein','Lithuania','Luxembourg','Madagascar','Malawi','Malaysia',
    'Maldives','Mali','Malta','Marshall Islands','Mauritania','Mauritius','Mexico','Micronesia',
    'Moldova','Monaco','Mongolia','Montenegro','Morocco','Mozambique','Myanmar','Namibia','Nauru',
    'Nepal','Netherlands','Nicaragua','Niger','Nigeria','North Macedonia','Norway','Oman','Pakistan',
    'Palau','Panama','Papua New Guinea','Paraguay','Peru','Philippines','Poland','Portugal','Qatar',
    'Romania','Russia','Rwanda','Saint Kitts and Nevis','Saint Lucia','Saint Vincent and the Grenadines',
    'Samoa','San Marino','Sao Tome and Principe','Saudi Arabia','Senegal','Serbia','Seychelles',
    'Sierra Leone','Singapore','Slovakia','Slovenia','Solomon Islands','Somalia','South Africa',
    'South Korea','South Sudan','Spain','Sri Lanka','Sudan','Suriname','Sweden','Switzerland','Syria',
    'Taiwan','Tajikistan','Tanzania','Thailand','Timor-Leste','Togo','Tonga','Trinidad and Tobago',
    'Tunisia','Turkey','Turkmenistan','Tuvalu','Uganda','Ukraine','United Arab Emirates',
    'United Kingdom','United States','Uruguay','Uzbekistan','Vanuatu','Vatican City','Venezuela',
    'Vietnam','Yemen','Zambia','Zimbabwe',
  ];
  rest.sort((a, b) => a.localeCompare(b));
  return [...pinned, ...rest];
})();

// Hazardous occupational duties (TAL S5 / NEOS S4.17–18)
const OCC_HAZARDS = [
  'Working at heights 10–20m',
  'Working at heights above 20m',
  'Working underground / confined spaces',
  'Working with explosives',
  'Underwater diving as part of work',
  'Operating heavy machinery',
  'Long-distance driving (>15,000 km/yr)',
  'Handling hazardous materials',
  'Carrying / lifting >20kg regularly',
  'None of the above',
];

// ─── Sub-component: per-condition deep-dive questionnaire ────
// Used for any item ticked across the medical history.
// Renders a dropdown of likely conditions for that item (with an
// "Other / not listed" escape hatch), then the standard insurer
// questionnaire. Mental-health items skip the tests / hospitalisation
// follow-ups (they don't apply logically). The treating-practitioner
// field is collected once in the GP card, not per condition.
function ConditionDetails({ c, examples = [], onChange, isMentalHealth, categoryId }) {
  const u = (patch) => onChange({ ...c, ...patch });
  const isOther = c.name === '__other__' || c.name === 'Other' || c.name === 'Other autoimmune';
  // For musculoskeletal items (back / joints / muscles) the insurer
  // wants to know the underlying cause so they can decide whether to
  // treat it as a once-off injury vs an ongoing wear-and-tear risk.
  const isMsk = categoryId === 'msk';
  // Cancer disclosures need more than the site of the cancer. The dropdown
  // above captures the broad site (breast / bowel / lung); underwriters also
  // need the specific sub-type where the client knows it (e.g. "invasive
  // ductal carcinoma", "AML") and the stage at diagnosis, because those drive
  // the loading or exclusion far more than the site alone does.
  const isCancer = categoryId === 'cancer';
  return (
    <div className="grid-2">
      <Field label="Which condition?" span={2} required>
        <Select value={c.name || ''} onChange={e => u({ name: e.target.value, nameOther: (e.target.value === '__other__' || e.target.value === 'Other' || e.target.value === 'Other autoimmune') ? (c.nameOther || '') : '' })}>
          <option value="">Select the closest match…</option>
          {examples.filter(ex => ex !== 'Other' && ex !== 'Other autoimmune').map(ex => <option key={ex} value={ex}>{ex}</option>)}
          <option value="__other__">Other / not listed - I'll describe it</option>
        </Select>
        {isOther && (
          <Input style={{ marginTop: 8 }} required
            value={c.nameOther || ''}
            onChange={e => u({ nameOther: e.target.value })}
            placeholder="Please describe the condition - e.g. mild lower-back disc bulge, post-viral fatigue" />
        )}
      </Field>
      {isCancer && (
        <>
          <Field label="Do you know the specific type?" span={2}
            hint="The sub-type your specialist named - e.g. invasive ductal carcinoma rather than just &quot;breast cancer&quot;.">
            <YesNo value={c.cancerTypeKnown} onChange={v => u({ cancerTypeKnown: v, cancerTypeDetail: v ? (c.cancerTypeDetail || '') : '' })} />
          </Field>
          {c.cancerTypeKnown === true && (
            <Field label="What type was it?" span={2} required name={`ins.cond_${c.id}.cancerTypeDetail`}>
              <Input value={c.cancerTypeDetail || ''} onChange={e => u({ cancerTypeDetail: e.target.value })}
                placeholder="e.g. Invasive ductal carcinoma" />
            </Field>
          )}
          <Field label="What stage was the cancer?" span={2}
            hint="If you're not sure, or it was never staged, pick the closest option.">
            <Select value={c.cancerStage || ''} onChange={e => u({ cancerStage: e.target.value })}>
              <option value="">Select…</option>
              <option>Stage 0 (in situ)</option>
              <option>Stage 1</option>
              <option>Stage 2</option>
              <option>Stage 3</option>
              <option>Stage 4</option>
              <option>Unsure / not told</option>
              <option>Not staged (benign or under investigation)</option>
            </Select>
          </Field>
        </>
      )}
      <Field label="When did symptoms first occur?" required name={`ins.cond_${c.id}.firstDate`}>
        <Input type="month" value={c.firstDate || ''} onChange={e => u({ firstDate: e.target.value })} />
      </Field>
      <Field label="When did you last have symptoms?" required name={`ins.cond_${c.id}.lastDate`}>
        <Input type="month" value={c.lastDate || ''} onChange={e => u({ lastDate: e.target.value })} />
      </Field>
      <Field label="Have symptoms been continuous?">
        <YesNo value={c.continuous} onChange={v => u({ continuous: v })} />
      </Field>
      {c.continuous === false && (
        <Field label="How many separate episodes have you had?">
          <Input type="number" min="1" value={c.episodes || ''} onChange={e => u({ episodes: e.target.value })} />
        </Field>
      )}
      <Field label="Severity" required>
        <ChipGroup options={['Mild', 'Moderate', 'Severe']} value={c.severity} onChange={v => u({ severity: v })} />
      </Field>
      {isMsk && (
        <Field label="What was the cause of this condition?" span={2}>
          <ChipGroup
            options={['Sporting injury', 'Wear and tear', 'Workplace injury', 'Motor vehicle accident', 'Genetic / congenital', 'Unsure']}
            value={c.cause}
            onChange={v => u({ cause: v })} />
        </Field>
      )}
      <Field label="Are you currently receiving treatment?">
        <YesNo value={c.currentTx} onChange={v => u({ currentTx: v })} />
      </Field>
      {c.currentTx && (
        <Field label="Treatment type & frequency" span={2}>
          <Textarea rows="2" value={c.currentTxDetail || ''} onChange={e => u({ currentTxDetail: e.target.value })}
            placeholder={isMentalHealth ? 'e.g. counselling fortnightly; SSRI medication daily' : 'e.g. Atorvastatin 20mg daily; physio every 2 weeks'} />
        </Field>
      )}
      <Field label="Have you had previous treatment for this condition?">
        <YesNo value={c.priorTx} onChange={v => u({ priorTx: v })} />
      </Field>
      {c.priorTx && (
        <Field label="Previous treatment - type & dates" span={2}>
          <Textarea rows="2" value={c.priorTxDetail || ''} onChange={e => u({ priorTxDetail: e.target.value })} />
        </Field>
      )}
      {!isMentalHealth && (
        <>
          <Field label="Have you had any tests or investigations?" hint="Scans, x-rays, blood tests, BP/cholesterol readings.">
            <YesNo value={c.tests} onChange={v => u({ tests: v })} />
          </Field>
          {c.tests && (
            <Field label="Test type & results" span={2}>
              <Textarea rows="2" value={c.testsDetail || ''} onChange={e => u({ testsDetail: e.target.value })} />
            </Field>
          )}
          <Field label="Have you been hospitalised for this condition?">
            <YesNo value={c.hospitalised} onChange={v => u({ hospitalised: v })} />
          </Field>
          {c.hospitalised && (
            <Field label="When, and how many times" span={2}>
              <Textarea rows="2" value={c.hospitalisedDetail || ''} onChange={e => u({ hospitalisedDetail: e.target.value })} />
            </Field>
          )}
        </>
      )}
      <Field label="Are you awaiting any tests, surgery or results?">
        <YesNo value={c.pending} onChange={v => u({ pending: v })} />
      </Field>
      {c.pending && (
        <Field label="What is pending?" span={2}>
          <Textarea rows="2" value={c.pendingDetail || ''} onChange={e => u({ pendingDetail: e.target.value })} />
        </Field>
      )}
      <Field label="Time off work / unable to perform usual activities">
        <Select value={c.timeOff || ''} onChange={e => u({ timeOff: e.target.value })}>
          <option value="">Select…</option>
          <option>None</option>
          <option>Less than 1 week</option>
          <option>Less than 1 month</option>
          <option>1–3 months</option>
          <option>3–6 months</option>
          <option>More than 6 months</option>
        </Select>
      </Field>
      <Field label="Are you fully recovered?">
        <ChipGroup options={['Yes, fully recovered', 'Partial', 'Ongoing']} value={c.recovery} onChange={v => u({ recovery: v })} />
      </Field>
    </div>
  );
}

// PercentInput is now defined in primitives.jsx and exposed globally as
// window.PercentInput - leaving this stub comment so future readers don't
// look for it here. (It used to live here, but the rest-destructuring
// `{ value, onChange, ...rest }` pattern was emitting a global
// `var _excluded = ["value", "onChange"]` that clobbered primitives.jsx's
// Select destructuring helper. See primitives.jsx for the explanation.)

// ─── Confirm dialog ────────────────────────────────────────
function ConfirmDialog({ title, message, confirmLabel = 'Remove', cancelLabel = 'Keep', onConfirm, onCancel }) {
  return (
    <div className="ff-modal-backdrop" onClick={onCancel}>
      <div className="ff-modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 460 }}>
        <button type="button" className="ff-modal-close" onClick={onCancel} aria-label="Close">×</button>
        <div className="modal-title">{title}</div>
        <p className="modal-body">{message}</p>
        <div className="modal-actions">
          <button type="button" className="btn-secondary" onClick={onCancel}>{cancelLabel}</button>
          <button type="button" className="btn-primary btn-danger" onClick={onConfirm}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

// MoneyInput is now defined in primitives.jsx and exposed globally as
// window.MoneyInput - leaving this stub comment so future readers don't
// look for it here. (See PercentInput comment above for the why.)

// ─── Lightweight modal ─────────────────────────────────────
function Modal({ children, onClose }) {
  return (
    <div className="ff-modal-backdrop" onClick={onClose}>
      <div className="ff-modal" onClick={(e) => e.stopPropagation()}>
        <button type="button" className="ff-modal-close" onClick={onClose} aria-label="Close">×</button>
        {children}
      </div>
    </div>
  );
}

// ─── Section ────────────────────────────────────────────────
function SectionInsurance({ data, set, saveCode, ensureSaveCode }) {
  // When advice is being given as a couple, the insurance + health
  // questionnaire is run TWICE - once for the primary client and once for
  // the partner. We render a Primary / Partner tab switcher at the top
  // and pivot `d` + `update` based on the active tab. The rest of the
  // file reads/writes through `d` and `update`, so swapping their
  // destination is enough to give us a clean per-person questionnaire
  // without forking the whole component.
  const isCouple = ['Married','De facto'].includes(data?.personal?.primary?.relStatus);
  const partnerActive = isCouple && data?.personal?.primary?.coupleAdvice === true;
  const insurance = data.insurance || {};
  const [activeTab, setActiveTab] = React.useState('primary');
  // If couple-advice is later turned off, force back to primary.
  const tab = partnerActive ? activeTab : 'primary';
  const d = tab === 'partner' ? (insurance.partner || {}) : insurance;
  const update = (patch) => {
    if (tab === 'partner') {
      set({ ...data, insurance: { ...insurance, partner: { ...(insurance.partner || {}), ...patch } } });
    } else {
      // Primary writes preserve the partner branch as-is.
      set({ ...data, insurance: { ...insurance, ...patch } });
    }
  };
  const isFemale = (() => {
    if (tab === 'partner') return (data?.personal?.partner?.gender || '').toLowerCase() === 'female';
    return (data?.personal?.primary?.gender || '').toLowerCase() === 'female';
  })();

  // Names of insured parties - used to suggest owner on existing policies
  const primaryName = (() => {
    const p = data?.personal?.primary || {};
    const n = [p.preferredName || p.firstName, p.lastName].filter(Boolean).join(' ').trim();
    return n || 'You';
  })();
  const hasPartner = ['Married','De facto'].includes(data?.personal?.primary?.relStatus) || data?.personal?.includePartner;
  const partnerName = (() => {
    if (!hasPartner) return null;
    const p = data?.personal?.partner || {};
    const n = [p.preferredName || p.firstName, p.lastName].filter(Boolean).join(' ').trim();
    return n || 'Partner';
  })();
  const ownerOptions = [primaryName, ...(partnerName ? [partnerName, 'Joint'] : [])];
  // Tab label for the partner - use their first / preferred name so the
  // client sees "Liam's insurance & health" rather than a generic label.
  const partnerFirst = (data?.personal?.partner?.preferredName || data?.personal?.partner?.firstName || '').trim();
  const partnerTabLabel = partnerFirst ? `${partnerFirst}'s insurance & health` : "Partner's insurance & health";

  // Cover types - kept in data shape but no longer asked up-front.
  // Default to showing every conditional block; users skip by leaving blank.
  const coverTypes = d.coverTypes || ['life', 'tpd', 'trauma', 'ip'];
  const wantsIP    = true;
  const wantsTPD   = true;
  const wantsLife  = true;

  // Existing policies (repeat)
  const policies = d.policies || [];
  const updatePolicy = (i, patch) => {
    const next = [...policies]; next[i] = { ...next[i], ...patch };
    update({ policies: next });
  };

  // Pursuits (repeat keyed by id)
  const pursuits = d.pursuitsList || [];
  const togglePursuit = (id) => {
    const exists = pursuits.find(p => p.id === id);
    if (exists) update({ pursuitsList: pursuits.filter(p => p.id !== id), pursuitsNone: false });
    else update({ pursuitsList: [...pursuits, { id }], pursuitsNone: false });
  };
  const updatePursuit = (id, patch) => {
    update({ pursuitsList: pursuits.map(p => p.id === id ? { ...p, ...patch } : p) });
  };
  const noPursuits = (d.pursuitsNone === true) && pursuits.length === 0;

  // Family history (repeat)
  const familyConditionsTicked = d.familyConditionsTicked || [];
  const familyNone = (d.familyNone === true) && familyConditionsTicked.length === 0;
  const family = d.family || [];
  const updateFamily = (i, patch) => {
    const next = [...family]; next[i] = { ...next[i], ...patch };
    update({ family: next });
  };
  const toggleFamilyCondition = (id) => {
    const arr = familyConditionsTicked.includes(id)
      ? familyConditionsTicked.filter(x => x !== id)
      : [...familyConditionsTicked, id];
    update({ familyConditionsTicked: arr, familyNone: false });
  };

  // Medical conditions ticked across all groups → expand into questionnaires
  const conditionsList = d.conditionsList || [];
  const conditionsRetained = d.conditionsRetained || {};
  const [pendingRemoveId, setPendingRemoveId] = React.useState(null);
  const updateCondition = (id, patch) => {
    update({ conditionsList: conditionsList.map(c => c.id === id ? { ...c, ...patch } : c) });
  };
  // ─── Per-question "None of the above" ──────────────────────────
  // Every medical-history question carries its own "None of the above"
  // tick, stored in `insurance.catNone` keyed `${groupId}.${catId}`.
  // The last-2-years group is one flat question, so its key is
  // `recent.all` (RECENT_NONE_KEY).
  //
  // This replaced a single banner at the foot of the card - "I confirm
  // none of the conditions above apply to me". Clients were ticking that
  // even after disclosing conditions above it, which is exactly the
  // disclosure failure it was meant to prevent. `conditionsNone` is now
  // read for backwards compatibility only and never written true.
  const catNoneMap = d.catNone || {};
  const catKey = (groupId, catId) => `${groupId}.${catId}`;
  // Records saved under the old banner carry `conditionsNone: true` with
  // an empty list, which meant "none of ANY of them". Treat every
  // question they never answered individually as None, so a client who
  // already finished doesn't reopen their form to 20 unanswered questions.
  const legacyNone = d.conditionsNone === true && conditionsList.length === 0;
  const isCatNone = (groupId, catId) => {
    const k = catKey(groupId, catId);
    if (catNoneMap[k] !== undefined) return catNoneMap[k] === true;
    return legacyNone;
  };
  const recentNone = isCatNone('recent', RECENT_AS_CATEGORY.id);
  // Any write into the medical history retires the legacy banner, so bake
  // the derived Nones into real `catNone` keys first - otherwise ticking
  // one condition would silently un-answer every other question.
  // `exceptKey` is the question being answered right now.
  const settleCatNone = (exceptKey) => {
    const next = { ...catNoneMap };
    if (legacyNone) MED_NONE_KEYS.forEach(k => { if (next[k] === undefined) next[k] = true; });
    if (exceptKey) delete next[exceptKey];
    return next;
  };
  // The patch every "a condition was ticked" path has to apply: clear the
  // None on the question that condition belongs to, keep the rest.
  const answerPatch = (groupId, itemId) => ({
    catNone: settleCatNone(MED_NONE_KEY_OF_ITEM[`${groupId}.${itemId}`]),
    conditionsNone: false,
  });

  // Tick / untick a condition. On untick, ask for confirmation but stash the
  // existing answers in `conditionsRetained` so re-ticking restores them.
  const toggleConditionWithRetain = (groupId, item) => {
    const id = `${groupId}.${item.id}`;
    // Untick removes the primary row AND any "Add another" siblings
    // (`${id}#N`) the client may have created under this item.
    const primary = conditionsList.find(c => c.id === id);
    const hasSiblings = conditionsList.some(c => (c.id || '').startsWith(`${id}#`));
    if (primary || hasSiblings) {
      const anyHasContent = conditionsList.some(c =>
        (c.id === id || (c.id || '').startsWith(`${id}#`)) &&
        !!(c.name || c.firstDate || c.lastDate || c.severity || c.currentTx != null || c.priorTx != null || c.recentNote)
      );
      if (anyHasContent) {
        setPendingRemoveId(id);
      } else {
        update({
          conditionsList: conditionsList.filter(c => c.id !== id && !(c.id || '').startsWith(`${id}#`)),
        });
      }
    } else {
      // Re-tick: restore retained answers if we have them
      const restored = conditionsRetained[id] || { id, group: groupId, item: item.id, suggested: item.label };
      update({
        conditionsList: [...conditionsList, restored],
        ...answerPatch(groupId, item.id),
      });
    }
  };
  const isTicked = (groupId, itemId) => conditionsList.some(c =>
    c.id === `${groupId}.${itemId}` || (c.id || '').startsWith(`${groupId}.${itemId}#`)
  );

  // Helper for item-level multi-condition support. The primary tick
  // creates one row keyed `${groupId}.${itemId}`. "Add another" creates
  // siblings keyed `${groupId}.${itemId}#N`. Returns the primary +
  // siblings in stable insertion order so the UI can render them in
  // the order the user added them.
  const siblingConditionsFor = (groupId, itemId) => {
    const base = `${groupId}.${itemId}`;
    return conditionsList.filter(c => c.id === base || (c.id || '').startsWith(`${base}#`));
  };
  const addSiblingCondition = (groupId, item) => {
    const base = `${groupId}.${item.id}`;
    let n = 1;
    while (conditionsList.some(c => c.id === `${base}#${n}`)) n++;
    const id = `${base}#${n}`;
    update({
      conditionsList: [...conditionsList, { id, group: groupId, item: item.id, suggested: item.label }],
      ...answerPatch(groupId, item.id),
    });
  };
  const removeSiblingCondition = (id) => {
    update({ conditionsList: conditionsList.filter(c => c.id !== id) });
  };

  // Tick / untick one question's "None of the above". `cat` is a category
  // from MED_CATEGORIES / MED_CATEGORIES_EVER, or the synthetic
  // { id: 'all', items: MED_RECENT } used for the last-2-years question.
  const toggleCatNone = (groupId, cat) => {
    const k = catKey(groupId, cat.id);
    const turningOn = !isCatNone(groupId, cat.id);
    if (turningOn) {
      // Untick every item in this question - the client is confirming none
      // of them apply. Use the retain map so re-untick brings them back.
      // Match on the id STEM so "Add another" siblings (`…#2`) go too,
      // rather than being left behind as rows with no visible editor.
      const idsInCat = cat.items.map(it => `${groupId}.${it.id}`);
      const inCat = (c) => idsInCat.includes(String(c.id || '').split('#')[0]);
      const retainAdds = {};
      conditionsList.forEach(c => { if (inCat(c)) retainAdds[c.id] = c; });
      update({
        conditionsList: conditionsList.filter(c => !inCat(c)),
        catNone: { ...settleCatNone(), [k]: true },
        conditionsRetained: { ...(d.conditionsRetained || {}), ...retainAdds },
        conditionsNone: false,
      });
    } else {
      // Write an explicit false rather than dropping the key, so a legacy
      // record's derived "None" doesn't immediately reappear.
      update({ catNone: { ...settleCatNone(), [k]: false } });
    }
  };

  // Prior modified/declined apps (repeat)
  const priorApps = d.priorApps || [];
  const updatePriorApp = (i, patch) => {
    const next = [...priorApps]; next[i] = { ...next[i], ...patch };
    update({ priorApps: next });
  };

  // Previous insurance claims (repeat)
  const claims = d.claims || [];
  const updateClaim = (i, patch) => {
    const next = [...claims]; next[i] = { ...next[i], ...patch };
    update({ claims: next });
  };

  // Couples-flow gate for the partner tab. Same picker pattern as the
  // Personal section: primary either completes the partner's insurance
  // questionnaire themselves, or fires off a reminder so the partner
  // signs in to their OWN invite and completes their half. When the
  // primary picks 'remind' (or hasn't picked yet), we render the picker
  // in place of the partner questionnaire and skip partner-scope
  // validation/data entry entirely.
  const partnerCompletion = insurance.partnerCompletion || '';
  const onPickPartnerCompletion = (v) => {
    set({ ...data, insurance: { ...insurance, partnerCompletion: v } });
  };

  // Early-return path: partner tab selected but completion isn't 'self'.
  // Render the tab switcher and the gate picker only - the heavy
  // questionnaire body below is skipped to avoid asking partner-scope
  // questions the primary doesn't intend to answer themselves.
  if (partnerActive && tab === 'partner' && partnerCompletion !== 'self') {
    return (
      <div className="section-body">
        <div className="person-tabs" style={{ marginBottom: 18 }}>
          <button type="button"
            className={cx('ptab', tab === 'primary' && 'on')}
            onClick={() => setActiveTab('primary')}>
            Your insurance & health
          </button>
          <button type="button"
            className={cx('ptab', tab === 'partner' && 'on')}
            onClick={() => setActiveTab('partner')}>
            {partnerTabLabel}
          </button>
        </div>
        <PartnerCompletionGate
          partner={data?.personal?.partner || {}}
          partnerCompletion={partnerCompletion}
          saveCode={saveCode}
          ensureSaveCode={ensureSaveCode}
          onPick={onPickPartnerCompletion}>
          {null}
        </PartnerCompletionGate>
      </div>
    );
  }

  return (
    <div className="section-body">
      {/* Primary / Partner tabs - only when advice is being given as a
          couple. Reuses the same `.person-tabs` / `.ptab` classes the
          Personal section uses so clients see the same "switch person"
          pattern they're already used to. */}
      {partnerActive && (
        <div className="person-tabs" style={{ marginBottom: 18 }}>
          <button type="button"
            className={cx('ptab', tab === 'primary' && 'on')}
            onClick={() => setActiveTab('primary')}>
            Your insurance & health
          </button>
          <button type="button"
            className={cx('ptab', tab === 'partner' && 'on')}
            onClick={() => setActiveTab('partner')}>
            {partnerTabLabel}
          </button>
        </div>
      )}

      {/* When the primary picks "I'll complete this on their behalf" we
          want the picker to stay visible at the top of the partner tab
          (so they can switch back to "remind" if they change their
          mind). The full questionnaire then renders below. */}
      {tab === 'partner' && partnerCompletion === 'self' && (
        <PartnerCompletionGate
          partner={data?.personal?.partner || {}}
          partnerCompletion={partnerCompletion}
          saveCode={saveCode}
          ensureSaveCode={ensureSaveCode}
          onPick={onPickPartnerCompletion}>
          {null}
        </PartnerCompletionGate>
      )}

      {/* ═══════════════════════════════════════════════════════════
          0. INTRO - disclosure warning + what to have ready
          ═══════════════════════════════════════════════════════════ */}
      <div className="ff-disclosure-banner">
        <div className="ff-disclosure-icon">!</div>
        <div className="ff-disclosure-body">
          <div className="ff-disclosure-title">Please read before you start</div>
          <p>
            The answers you provide in this section will be <strong>disclosed directly to insurers</strong> as part of your application. Under the Insurance Contracts Act, you have a <strong>duty to take reasonable care not to make a misrepresentation</strong> - every answer must be truthful, accurate and complete.
          </p>
          <p>
            Non-disclosure (or inaccurate disclosure) is the single most common reason claims are declined or policies are cancelled - even years after a policy was issued. If you're unsure whether something is relevant, <strong>include it</strong> - your adviser can clarify with you before anything is submitted.
          </p>
        </div>
      </div>

      <div className="ff-prep-card">
        <div className="ff-prep-title">Before you begin - have these handy</div>
        <p className="ff-prep-intro">
          Most clients find this section much faster (and more accurate) if they spend 5 minutes pulling the following together first:
        </p>
        <div className="ff-prep-grid">
          <div className="ff-prep-item">
            <div className="ff-prep-h">Existing policies</div>
            <ul>
              <li>Your latest annual statement or super dashboard</li>
              <li>Insurer name, policy number, sum insured and premium type</li>
            </ul>
          </div>
          <div className="ff-prep-item">
            <div className="ff-prep-h">Medical conditions</div>
            <ul>
              <li>Approximate <strong>start and end dates</strong> for each condition (month / year)</li>
              <li>Any tests, scans or specialist referrals - dates and results if known</li>
              <li>Hospitalisations - when, how long, what for</li>
            </ul>
          </div>
          <div className="ff-prep-item">
            <div className="ff-prep-h">Current medications</div>
            <ul>
              <li>Medication name, <strong>dose (mg)</strong> and how often you take it</li>
              <li>Approximate date you started each one</li>
            </ul>
          </div>
          <div className="ff-prep-item">
            <div className="ff-prep-h">Family history</div>
            <ul>
              <li>Conditions diagnosed in parents and siblings</li>
              <li>Their age at diagnosis (and age at death if applicable)</li>
            </ul>
          </div>
          <div className="ff-prep-item">
            <div className="ff-prep-h">Your GP</div>
            <ul>
              <li>Practice name, address and phone</li>
              <li>Roughly when you last attended</li>
            </ul>
          </div>
          <div className="ff-prep-item">
            <div className="ff-prep-h">Other</div>
            <ul>
              <li>Height (cm) and weight (kg)</li>
              <li>Definite overseas travel plans in the next 12 months</li>
              <li>Any prior insurance application that was declined, loaded or excluded</li>
            </ul>
          </div>
        </div>
        <p className="ff-prep-foot">
          Don't have something to hand? You can save and come back - your progress is kept against your save code.
        </p>
      </div>

      {/* ═══════════════════════════════════════════════════════════
          0.5 OCCUPATION CONFIRMATION
          Summarises occupation + industry + employment + tenure from the
          Personal stage and asks the client to confirm. If they say no,
          we reveal editable fields and write the corrections back to the
          Personal stage so both sections stay in sync.
          ═══════════════════════════════════════════════════════════ */}
      {(() => {
        // Pull occupation details from whichever person is being viewed.
        // On the Partner tab we read from data.personal.partner so the
        // summary doesn't show the primary's occupation under the
        // partner's questionnaire, and any edits write back to the
        // correct person's Personal panel.
        const isPartner = tab === 'partner';
        const p = (isPartner ? data?.personal?.partner : data?.personal?.primary) || {};
        const updatePersonal = (patch) => set({
          ...data,
          personal: {
            ...(data.personal || {}),
            [isPartner ? 'partner' : 'primary']: { ...p, ...patch },
          },
        });
        const occ      = p.occupation || '';
        const ind      = p.industry || '';
        const empBasis = p.empBasis || '';
        const tenure   = p.tenure || '';
        const empPhrase = (() => {
          const e = (empBasis || '').toLowerCase();
          if (!e) return '';
          if (e.includes('full-time employee'))  return 'working full time as an employee';
          if (e.includes('part-time employee'))  return 'working part time as an employee';
          if (e.includes('casual'))              return 'working on a casual basis';
          if (e.includes('fixed term'))          return 'on a fixed-term contract';
          if (e.includes('self-employed'))       return 'working as a self-employed person';
          if (e.includes('business owner'))      return 'a business owner';
          if (e.includes('contractor'))          return 'working as a contractor';
          if (e.includes('redundant'))           return 'recently made redundant';
          if (e.includes('retired'))             return 'retired';
          if (e.includes('not currently'))       return 'not currently working';
          return empBasis.toLowerCase();
        })();
        const tenurePhrase = tenure ? (
          tenure.toLowerCase().startsWith('less')
            ? 'in your current role for less than 1 year'
            : `in your current role for ${tenure.replace(/\u2013/g, '-').toLowerCase()}`
        ) : '';
        const indPhrase = ind ? ` in the ${ind} industry` : '';
        const subject = isPartner ? 'Your partner is' : 'You are';
        const possessive = isPartner ? "your partner's" : 'your';
        const summary = (occ || empPhrase || tenurePhrase) ? (
          <>
            {subject} a <strong>{occ || '(occupation not provided)'}</strong>
            {indPhrase ? <> {indPhrase}</> : null}
            {empPhrase ? <>, <strong>{empPhrase}</strong></> : null}
            {tenurePhrase ? <>, and {isPartner ? 'has' : 'have'} been <strong>{tenurePhrase}</strong></> : null}
            .
          </>
        ) : (
          <em>We don't have any {isPartner ? "partner " : ''}occupation details from the Personal section yet - please add them below.</em>
        );
        const confirmed = d.occConfirmed; // true / false / undefined
        const needsEdit = confirmed === false || !(occ || empBasis || tenure);
        return (
          <div className="card" data-ff-name="ins.occConfirm">
            <div className="card-title">Confirm {possessive} occupation details</div>
            <Callout kind="info">
              Please confirm the occupation details below - they came from the <strong>Personal</strong> section{isPartner ? " (partner tab)" : ''}. Insurance pricing and underwriting rely heavily on this, so it's worth a quick double-check.
            </Callout>
            <div className="ff-occ-summary" style={{
              marginTop: 12, padding: '14px 16px', borderRadius: 10,
              background: 'var(--ff-surface-2, #f6f7f9)',
              border: '1px solid var(--ff-border, #e3e6ec)',
              fontSize: 15, lineHeight: 1.55,
            }}>
              {summary}
            </div>
            <Field label="Please confirm: is the description above correct?" style={{ marginTop: 14 }}>
              <YesNo value={confirmed} onChange={v => update({ occConfirmed: v })} />
            </Field>
            {needsEdit && (
              <>
                <Callout kind="warn">
                  {confirmed === false
                    ? <>No problem - please correct anything below. We'll update your <strong>Personal</strong> section to match.</>
                    : <>Please add your occupation details below - we'll save them to your <strong>Personal</strong> section.</>}
                </Callout>
                <div className="grid-2" style={{ marginTop: 14 }}>
                  <Field label="Current occupation / job title" required>
                    <Input value={occ} onChange={e => updatePersonal({ occupation: e.target.value })}
                      placeholder="e.g. Registered Nurse, Civil Engineer" />
                  </Field>
                  <Field label="Industry">
                    <Input value={ind} onChange={e => updatePersonal({ industry: e.target.value })}
                      placeholder="e.g. Healthcare, Mining, Finance" />
                  </Field>
                  <Field label="Employment type">
                    <Select value={empBasis} onChange={e => updatePersonal({ empBasis: e.target.value })}>
                      <option value="">Select…</option>
                      {['Full-time employee','Part-time employee','Casual employee','Fixed term contract','Self-employed','Business owner','Contractor','Recently made redundant','Retired','Not currently working'].map(o => <option key={o}>{o}</option>)}
                    </Select>
                  </Field>
                  <Field label="Time in current role">
                    <Select value={tenure} onChange={e => updatePersonal({ tenure: e.target.value })}>
                      <option value="">Select…</option>
                      {['Less than 1 year','1–2 years','2–5 years','5–10 years','10+ years'].map(o => <option key={o}>{o}</option>)}
                    </Select>
                  </Field>
                </div>
              </>
            )}
          </div>
        );
      })()}

      {/* ═══════════════════════════════════════════════════════════
          1. EXISTING COVER
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Existing insurance you already hold</div>
        <Field label="Do you currently hold any life, TPD, trauma or income-protection insurance?" required hint="Including cover held inside a super fund or via your employer.">
          <YesNo value={d.hasExisting} onChange={v => update({ hasExisting: v })} />
        </Field>
        {d.hasExisting && (
          <>
            <Callout kind="info">
              The most accurate way to fill this in is from your latest annual statement or super dashboard. If you can't find it, tick "I have cover but I'm not sure how much" - we'll request the details from your insurer with your written authority.
            </Callout>
            {policies.length === 0 && (
              <div className="empty-hint" style={{ marginTop: 12 }}>Add each policy you currently hold.</div>
            )}
            {policies.map((p, i) => {
              const types = p.types || [];
              const toggleType = (t) => {
                const next = types.includes(t) ? types.filter(x => x !== t) : [...types, t];
                updatePolicy(i, { types: next });
              };
              const hasIP = types.includes('Income Protection');
              return (
              <RepeatItem key={i} title={`Policy ${i+1}`}
                onRemove={() => { const n = [...policies]; n.splice(i,1); update({ policies: n }); }}>
                <div className="grid-2">
                  <Field label="Insurer" required>
                    <Input value={p.insurer || ''} onChange={e => updatePolicy(i, { insurer: e.target.value })} />
                  </Field>
                  <Field label="Policy number" hint="On your annual statement or super dashboard.">
                    <Input value={p.policyNumber || ''} onChange={e => updatePolicy(i, { policyNumber: e.target.value })}
                      placeholder="e.g. POL-12345678" />
                  </Field>
                  <Field label="Life insured" required
                    hint="The person whose life is insured under this policy.">
                    <Select value={p.owner || ''} onChange={e => updatePolicy(i, { owner: e.target.value })}>
                      <option value="">Select…</option>
                      {ownerOptions.map(o => <option key={o}>{o}</option>)}
                    </Select>
                  </Field>
                  <Field label="Where is this policy held?" required>
                    <Select value={p.heldVia || ''} onChange={e => updatePolicy(i, { heldVia: e.target.value })}>
                      <option value="">Select…</option>
                      <option>Inside super (default cover in fund)</option>
                      <option>Inside super (adviser-arranged)</option>
                      <option>Outside super (retail / direct)</option>
                      <option>Through my employer</option>
                      <option>Not sure</option>
                    </Select>
                  </Field>
                  <Field label="Cover types on this policy" span={2} required hint="Select all that apply - most bundled policies include several.">
                    <ChipGroup multi
                      options={['Life', 'TPD', 'Trauma / Critical Illness', 'Income Protection']}
                      value={types}
                      onChange={(vals) => updatePolicy(i, { types: vals })} />
                  </Field>

                  {/* Per-cover sum insured */}
                  {types.filter(t => t !== 'Income Protection').map(t => (
                    <Field key={t} label={`${t} - sum insured`} required={!p[`sum_${t}_unsure`]}>
                      {p[`sum_${t}_unsure`] ? (
                        <Input value="Cover held - amount unknown" disabled />
                      ) : (
                        <MoneyInput value={p[`sum_${t}`] || ''}
                          onChange={e => updatePolicy(i, { [`sum_${t}`]: e.target.value })}
                          placeholder="$0" />
                      )}
                      <label className="muted-checkbox" style={{ marginTop: 6 }}>
                        <input type="checkbox"
                          checked={!!p[`sum_${t}_unsure`]}
                          onChange={e => updatePolicy(i, { [`sum_${t}_unsure`]: e.target.checked, [`sum_${t}`]: e.target.checked ? '' : p[`sum_${t}`] })} />
                        <span>I have cover but I'm not sure how much</span>
                      </label>
                    </Field>
                  ))}

                  {hasIP && (
                    <>
                      <Field label="Income Protection - monthly benefit" required={!p.monthlyBenefit_unsure}>
                        {p.monthlyBenefit_unsure ? (
                          <Input value="Cover held - amount unknown" disabled />
                        ) : (
                          <MoneyInput value={p.monthlyBenefit || ''}
                            onChange={e => updatePolicy(i, { monthlyBenefit: e.target.value })}
                            placeholder="$0 / month" />
                        )}
                        <label className="muted-checkbox" style={{ marginTop: 6 }}>
                          <input type="checkbox"
                            checked={!!p.monthlyBenefit_unsure}
                            onChange={e => updatePolicy(i, { monthlyBenefit_unsure: e.target.checked, monthlyBenefit: e.target.checked ? '' : p.monthlyBenefit })} />
                          <span>I have cover but I'm not sure how much</span>
                        </label>
                      </Field>
                      <Field label="Waiting period">
                        <Select value={p.waiting || ''} onChange={e => updatePolicy(i, { waiting: e.target.value })}>
                          <option value="">Select…</option>
                          <option>14 days</option><option>30 days</option><option>60 days</option><option>90 days</option><option>180 days</option><option>1 year</option><option>2 years</option><option>Not sure</option>
                        </Select>
                      </Field>
                      <Field label="Benefit period">
                        <Select value={p.benefitPeriod || ''} onChange={e => updatePolicy(i, { benefitPeriod: e.target.value })}>
                          <option value="">Select…</option>
                          <option>2 years</option><option>5 years</option><option>To age 65</option><option>To age 70</option><option>Not sure</option>
                        </Select>
                      </Field>
                    </>
                  )}

                  {/* Loadings / exclusions acknowledgement. When the
                      client is aware of any premium loading or excluded
                      condition on the policy, we capture the details
                      verbatim - insurers and the new adviser both need
                      to see them when restructuring or replacing
                      cover. */}
                  <Field span={2}>
                    <label className="muted-checkbox">
                      <input type="checkbox"
                        checked={!!p.hasLoadings}
                        onChange={e => updatePolicy(i, {
                          hasLoadings: e.target.checked,
                          loadingsDetail: e.target.checked ? (p.loadingsDetail || '') : '',
                        })} />
                      <span>I am aware of any loadings or exclusions on this policy</span>
                    </label>
                  </Field>
                  {p.hasLoadings && (
                    <Field label="Please describe the loadings or exclusions" required
                      name={`ins.policy${i}.loadingsDetail`}
                      hint="e.g. 25% premium loading for high blood pressure, asthma excluded from IP cover, etc."
                      span={2}>
                      <Textarea rows="2" value={p.loadingsDetail || ''}
                        onChange={e => updatePolicy(i, { loadingsDetail: e.target.value })} />
                    </Field>
                  )}
                </div>
              </RepeatItem>
              );
            })}
            <AddBtn onClick={() => update({ policies: [...policies, {}] })}>Add policy</AddBtn>
          </>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          2. RESIDENCY & TRAVEL
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Residency & travel</div>
        <Field label="Are you an Australian citizen, permanent resident, or NZ citizen residing in Australia?" required>
          <YesNo value={d.residency} onChange={v => update({ residency: v })} />
        </Field>
        {d.residency === false && (
          <div className="grid-2">
            <Field label="What type of visa do you hold?" required>
              <Input value={d.visaType || ''} onChange={e => update({ visaType: e.target.value })} placeholder="e.g. Subclass 482, Subclass 186" />
            </Field>
            <Field label="When does it expire?" required>
              <Input type="month" value={d.visaExpiry || ''} onChange={e => update({ visaExpiry: e.target.value })} />
            </Field>
            <Field label="How long have you lived in Australia?" required hint="Years and months.">
              <Input value={d.timeInAus || ''} onChange={e => update({ timeInAus: e.target.value })} placeholder="e.g. 3 yrs 4 mo" />
            </Field>
            <Field label="Country of birth" required>
              <Select value={d.countryBirth || ''} onChange={e => update({ countryBirth: e.target.value })}>
                <option value="">Select country…</option>
                {COUNTRY_LIST.map(c => <option key={c} value={c}>{c}</option>)}
              </Select>
            </Field>
            <Field label="Permanent residency status" required>
              <Select value={d.prStatus || ''} onChange={e => update({ prStatus: e.target.value })}>
                <option value="">Select…</option>
                <option>PR application already lodged</option>
                <option>Eligible - planning to apply within 12 months</option>
                <option>Eligible - planning to apply later</option>
                <option>Not yet eligible</option>
                <option>Not seeking PR</option>
              </Select>
            </Field>
            <Field label="If known, expected year of PR grant">
              <Input type="number" min="2024" max="2050" value={d.prYear || ''}
                onChange={e => update({ prYear: e.target.value })} placeholder="e.g. 2027" />
            </Field>
          </div>
        )}
        <hr className="divider" />
        <Field label={
          <span>In the next 12 months, do you have any <span className="label-emph">definite</span> plans to travel or live outside Australia / New Zealand?</span>
        } required>
          <YesNo value={d.travel} onChange={v => {
            if (v === true) update({ travel: true, travelAcked: false });
            else update({ travel: v, travelAcked: false });
          }} />
        </Field>
        {d.travel === true && !d.travelAcked && (
          <Modal onClose={() => update({ travel: null, travelAcked: false })}>
            <div className="ff-confirm-eyebrow">
              <span className="ff-confirm-eyebrow-dot" />
              Heads up before you continue
            </div>
            <div className="modal-title" style={{ marginTop: 6 }}>
              Only <span style={{ color: 'var(--brand)' }}>definite</span> travel plans, please
            </div>
            <div className="modal-body" style={{ marginTop: 10 }}>
              <p style={{ margin: '0 0 10px' }}>
                Please only include travel that is <strong>definite</strong> - i.e. <strong>booked</strong>, with dates set, or otherwise locked-in. Tentative or "maybe" plans don't need to be disclosed here, and disclosing them may unnecessarily affect your application.
              </p>
              <p style={{ margin: 0 }}>
                If anything you're about to enter isn't yet definite, choose <strong>Change my answer</strong> and answer No instead.
              </p>
            </div>
            <div className="modal-actions">
              <button type="button" className="btn-secondary"
                onClick={() => update({ travel: null, travelAcked: false })}>
                Change my answer
              </button>
              <button type="button" className="btn-primary"
                onClick={() => update({ travelAcked: true })}>
                I understand - these plans are definite
              </button>
            </div>
          </Modal>
        )}
        {d.travel && d.travelAcked && (
          <>
            {(d.travelTrips || []).length === 0 && (
              <div className="empty-hint" style={{ marginTop: 12 }}>Add the first definite trip below.</div>
            )}
            {(d.travelTrips || []).map((t, i) => (
              <RepeatItem key={i} title={`Trip ${i+1}`}
                onRemove={() => {
                  const n = [...(d.travelTrips || [])]; n.splice(i,1);
                  update({ travelTrips: n });
                }}>
                <div className="grid-2">
                  <Field label="Country / region" required>
                    <Select value={t.country || ''} onChange={e => {
                      const n = [...(d.travelTrips || [])]; n[i] = { ...n[i], country: e.target.value };
                      update({ travelTrips: n });
                    }}>
                      <option value="">Select country…</option>
                      {COUNTRY_LIST.map(c => <option key={c} value={c}>{c}</option>)}
                    </Select>
                  </Field>
                  <Field label="Purpose">
                    <Select value={t.purpose || ''} onChange={e => {
                      const n = [...(d.travelTrips || [])]; n[i] = { ...n[i], purpose: e.target.value, purposeOther: e.target.value === 'Other' ? (n[i].purposeOther || '') : '' };
                      update({ travelTrips: n });
                    }}>
                      <option value="">Select…</option>
                      <option>Leisure / holiday</option>
                      <option>Business</option>
                      <option>Visiting family</option>
                      <option>Volunteer / aid work</option>
                      <option>Other</option>
                    </Select>
                    {t.purpose === 'Other' && (
                      <Input style={{ marginTop: 8 }} required
                        value={t.purposeOther || ''}
                        onChange={e => {
                          const n = [...(d.travelTrips || [])]; n[i] = { ...n[i], purposeOther: e.target.value };
                          update({ travelTrips: n });
                        }}
                        placeholder="Please describe the purpose" />
                    )}
                  </Field>
                  <Field label="Departure month" required>
                    <Input type="month" value={t.from || ''} onChange={e => {
                      const n = [...(d.travelTrips || [])]; n[i] = { ...n[i], from: e.target.value };
                      update({ travelTrips: n });
                    }} />
                  </Field>
                  <Field label="Return month" required>
                    <Input type="month" value={t.to || ''} onChange={e => {
                      const n = [...(d.travelTrips || [])]; n[i] = { ...n[i], to: e.target.value };
                      update({ travelTrips: n });
                    }} />
                  </Field>
                  <Field label="Total days away" span={2}>
                    <Input type="number" min="1" value={t.days || ''} onChange={e => {
                      const n = [...(d.travelTrips || [])]; n[i] = { ...n[i], days: e.target.value };
                      update({ travelTrips: n });
                    }} placeholder="e.g. 21" />
                  </Field>
                </div>
              </RepeatItem>
            ))}
            <AddBtn onClick={() => update({ travelTrips: [...(d.travelTrips || []), {}] })}>Add trip</AddBtn>
          </>
        )}
        <Field label="Are you planning to live overseas in the next 3 years?" required>
          <YesNo value={d.overseas} onChange={v => update({ overseas: v })} />
        </Field>
        {d.overseas && (
          <div className="grid-2">
            <Field label="Where" required>
              <Select value={d.overseasWhere || ''} onChange={e => update({ overseasWhere: e.target.value })}>
                <option value="">Select country…</option>
                {COUNTRY_LIST.map(c => <option key={c} value={c}>{c}</option>)}
              </Select>
            </Field>
            <Field label="When" required>
              <Input type="month" value={d.overseasWhen || ''} onChange={e => update({ overseasWhen: e.target.value })} />
            </Field>
            <Field label="For how long" span={2} required>
              <Input value={d.overseasHowLong || ''} onChange={e => update({ overseasHowLong: e.target.value })}
                placeholder="e.g. 18 months" />
            </Field>
          </div>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          4. OCCUPATIONAL DUTIES
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Occupational duties<span className="req">*</span></div>
        <Callout kind="info">
          Insurance pricing is heavily occupation-rated. Your occupation title is in the Personal section - these questions help us match you to the right occupation class.
        </Callout>
        <div className="grid-2" style={{ marginTop: 14 }}>
          <Field label="Approx. time at a desk / office (%)">
            <PercentInput value={d.occDesk || ''} onChange={e => update({ occDesk: e.target.value })} placeholder="0%" />
          </Field>
          <Field label="Approx. time on-site or in the field (%)">
            <PercentInput value={d.occField || ''} onChange={e => update({ occField: e.target.value })} placeholder="0%" />
          </Field>
          <Field label="Approx. time doing manual / physical work (%)">
            <PercentInput value={d.occManual || ''} onChange={e => update({ occManual: e.target.value })} placeholder="0%" />
          </Field>
          <Field label="Approx. time driving for work (%)" hint="Driving as part of your duties - does NOT include your daily commute to and from work.">
            <PercentInput value={d.occDriving || ''} onChange={e => update({ occDriving: e.target.value })} placeholder="0%" />
          </Field>
        </div>
        {(Number(d.occField) || 0) > 0 && (
          <Field label="Please describe the type of work you do on-site or in the field" required name="ins.occFieldDetail"
            hint="For example: the type of site (construction, mine, farm, client premises), what your duties there involve, and whether you supervise or carry out the work yourself.">
            <Textarea rows="3" value={d.occFieldDetail || ''} onChange={e => update({ occFieldDetail: e.target.value })} />
          </Field>
        )}
        {(Number(d.occManual) || 0) > 0 && (
          <Field label="Please summarise the types of manual / physical work you do" required name="ins.occManualDetail"
            hint="For example: lifting and carrying, working with tools or machinery, standing or repetitive tasks, etc.">
            <Textarea rows="3" value={d.occManualDetail || ''} onChange={e => update({ occManualDetail: e.target.value })} />
          </Field>
        )}
        {(() => {
          const occTotal = Math.round((Number(d.occDesk) || 0) + (Number(d.occField) || 0) + (Number(d.occManual) || 0) + (Number(d.occDriving) || 0));
          return occTotal === 100 ? (
            <div style={{ marginTop: 8, color: '#176B38', fontSize: 13, fontWeight: 600 }}>Your duties total 100%.</div>
          ) : (
            <div data-ff-name="ins.occSplit" style={{ marginTop: 8, color: '#A6412F', fontSize: 13, fontWeight: 600 }}>
              These add up to {occTotal}%. Your duties need to total 100% before you can continue.
            </div>
          );
        })()}
        <hr className="divider" />
        <Field label="Does your role involve any of the following?" required hint="Select all that apply.">
          <ChipGroup multi options={OCC_HAZARDS} value={d.occHazards} onChange={v => update({ occHazards: v })} />
        </Field>
        {d.occHazards && d.occHazards.includes('Working at heights 10–20m') && (
          <Field label="At heights 10–20m - hours per week and duties" required hint="Please also note whether work is on a fixed structure.">
            <Textarea rows="2" value={d.heights1020Detail || ''} onChange={e => update({ heights1020Detail: e.target.value })} />
          </Field>
        )}
        {d.occHazards && d.occHazards.includes('Working at heights above 20m') && (
          <Field label="At heights above 20m - hours per week, max height and duties" required>
            <Textarea rows="2" value={d.heights20pDetail || ''} onChange={e => update({ heights20pDetail: e.target.value })} />
          </Field>
        )}
        {d.occHazards && d.occHazards.includes('Working underground / confined spaces') && (
          <Field label="% of weekly hours underground, and the duties involved" required>
            <Textarea rows="2" value={d.undergroundDetail || ''} onChange={e => update({ undergroundDetail: e.target.value })} />
          </Field>
        )}
        {d.occHazards && d.occHazards.includes('Working with explosives') && (
          <Field label="% of weekly hours with explosives, duties, and safety measures" required>
            <Textarea rows="2" value={d.explosivesDetail || ''} onChange={e => update({ explosivesDetail: e.target.value })} />
          </Field>
        )}
        {d.occHazards && d.occHazards.includes('Underwater diving as part of work') && (
          <Field label="Underwater diving - average and max depth, duties, frequency" required>
            <Textarea rows="2" value={d.workDivingDetail || ''} onChange={e => update({ workDivingDetail: e.target.value })} />
          </Field>
        )}

        <hr className="divider" />
        <Field label="Are you self-employed or a business owner?" required>
          <YesNo value={d.selfEmployed} onChange={v => update({ selfEmployed: v })} />
        </Field>
        {d.selfEmployed && (
          <div className="grid-2">
            <Field label="Years in current business" required>
              <Input type="number" value={d.businessYears || ''} onChange={e => update({ businessYears: e.target.value })} />
            </Field>
            <Field label="Your % ownership / share of business" required>
              <PercentInput value={d.businessShare || ''} onChange={e => update({ businessShare: e.target.value })} />
            </Field>
            <Field label="Number of other owners / shareholders">
              <Input type="number" value={d.businessOtherOwners || ''} onChange={e => update({ businessOtherOwners: e.target.value })} />
            </Field>
            <Field label="Number of employees (incl. contractors)">
              <Input type="number" value={d.businessEmployees || ''} onChange={e => update({ businessEmployees: e.target.value })} />
            </Field>
            <Field label="% of business revenue dependent on you personally" required>
              <PercentInput value={d.businessKeyperson || ''} onChange={e => update({ businessKeyperson: e.target.value })} />
            </Field>
            {wantsIP && (
              <>
                <Field label="If you couldn't work, would the business continue >90 days?">
                  <ChipGroup options={['Yes', 'No', 'Unsure']} value={d.businessContinuity} onChange={v => update({ businessContinuity: v })} />
                </Field>
                <Field label="Would you continue to receive ≥30% of regular income if disabled?">
                  <ChipGroup options={['Yes', 'No', 'Unsure']} value={d.businessOngoingIncome} onChange={v => update({ businessOngoingIncome: v })} />
                </Field>
              </>
            )}
          </div>
        )}

        {/* IP-only employment specifics */}
        {wantsIP && (
          <>
            <hr className="divider" />
            <SubSectionHeading>For Income Protection - work pattern</SubSectionHeading>
            <div className="grid-2">
              <Field label="Hours worked in a typical week" required>
                <Input type="number" value={d.hoursPerWeek || ''} onChange={e => update({ hoursPerWeek: e.target.value })} />
              </Field>
              <Field label="Days worked per week" required>
                <Input type="number" min="1" max="7" value={d.daysPerWeek || ''} onChange={e => update({ daysPerWeek: e.target.value })} />
              </Field>
              <Field label="Have you been continuously working in this occupation for the last 2 years?" required>
                <YesNo value={d.continuous2y} onChange={v => update({ continuous2y: v })} />
              </Field>
              <Field label="Are you currently off work, on reduced hours, or on altered duties due to illness or injury?" required>
                <YesNo value={d.currentlyOffWork} onChange={v => update({ currentlyOffWork: v })} />
              </Field>
            </div>
            {d.continuous2y === false && (
              <div className="grid-2">
                <Field label="Reason for the break / change" required>
                  <Select value={d.continuous2yReason || ''} onChange={e => update({ continuous2yReason: e.target.value, continuous2yReasonOther: e.target.value === 'Other' ? (d.continuous2yReasonOther || '') : '' })}>
                    <option value="">Select…</option>
                    <option>Studying</option>
                    <option>Parental leave</option>
                    <option>Travel</option>
                    <option>Carer / family responsibilities</option>
                    <option>Illness or injury</option>
                    <option>Redundancy / unemployment</option>
                    <option>Career change</option>
                    <option>Other</option>
                  </Select>
                  {d.continuous2yReason === 'Other' && (
                    <Input style={{ marginTop: 8 }} required
                      value={d.continuous2yReasonOther || ''}
                      onChange={e => update({ continuous2yReasonOther: e.target.value })}
                      placeholder="Please describe the reason" />
                  )}
                </Field>
                <Field label="Previous occupation">
                  <Input value={d.continuous2yPrevOcc || ''}
                    onChange={e => update({ continuous2yPrevOcc: e.target.value })}
                    placeholder="Your role before this one" />
                </Field>
                <Field label="When did the previous role end?">
                  <Input type="month" value={d.continuous2yPrevEnd || ''}
                    onChange={e => update({ continuous2yPrevEnd: e.target.value })} />
                </Field>
                <Field label="When did the current role start?">
                  <Input type="month" value={d.continuous2yCurrentStart || ''}
                    onChange={e => update({ continuous2yCurrentStart: e.target.value })} />
                </Field>
              </div>
            )}
            {d.currentlyOffWork && (
              <div className="grid-2">
                <Field label="Reason" required>
                  <Select value={d.currentlyOffWorkReason || ''} onChange={e => update({ currentlyOffWorkReason: e.target.value, currentlyOffWorkReasonOther: e.target.value === 'Other' ? (d.currentlyOffWorkReasonOther || '') : '' })}>
                    <option value="">Select…</option>
                    <option>Illness</option>
                    <option>Injury</option>
                    <option>Mental health</option>
                    <option>Surgery / recovery</option>
                    <option>Other</option>
                  </Select>
                  {d.currentlyOffWorkReason === 'Other' && (
                    <Input style={{ marginTop: 8 }} required
                      value={d.currentlyOffWorkReasonOther || ''}
                      onChange={e => update({ currentlyOffWorkReasonOther: e.target.value })}
                      placeholder="Please describe the reason" />
                  )}
                </Field>
                <Field label="When did you stop / reduce?" required>
                  <Input type="month" value={d.currentlyOffWorkSince || ''} onChange={e => update({ currentlyOffWorkSince: e.target.value })} />
                </Field>
                <Field label="Current status" required>
                  <Select value={d.currentlyOffWorkStatus || ''} onChange={e => update({ currentlyOffWorkStatus: e.target.value })}>
                    <option value="">Select…</option>
                    <option>Off work entirely</option>
                    <option>Working reduced hours</option>
                    <option>On altered / lighter duties</option>
                    <option>Returning to full duties soon</option>
                  </Select>
                </Field>
                <Field label="Expected return to full duties">
                  <Input type="month" value={d.currentlyOffWorkReturn || ''} onChange={e => update({ currentlyOffWorkReturn: e.target.value })} />
                </Field>
                <Field label="Anything else we should know?" span={2}>
                  <Textarea rows="2" value={d.currentlyOffWorkDetail || ''} onChange={e => update({ currentlyOffWorkDetail: e.target.value })} />
                </Field>
              </div>
            )}
          </>
        )}

        <hr className="divider" />
        <Field label="Any planned changes to your work in the next 12 months?" required hint="e.g. starting a business, parental leave, redundancy, change of duties, retirement.">
          <YesNo value={d.workChanges} onChange={v => update({ workChanges: v })} />
        </Field>
        {d.workChanges && (
          <div className="grid-2">
            <Field label="Type of change" required>
              <Select value={d.workChangesType || ''} onChange={e => update({ workChangesType: e.target.value, workChangesTypeOther: e.target.value === 'Other' ? (d.workChangesTypeOther || '') : '' })}>
                <option value="">Select…</option>
                <option>Starting a new business</option>
                <option>Changing employer</option>
                <option>Change of duties / role</option>
                <option>Parental leave</option>
                <option>Long-term leave (e.g. carer, sabbatical)</option>
                <option>Redundancy / role ending</option>
                <option>Reducing to part-time</option>
                <option>Retirement</option>
                <option>Other</option>
              </Select>
              {d.workChangesType === 'Other' && (
                <Input style={{ marginTop: 8 }} required
                  value={d.workChangesTypeOther || ''}
                  onChange={e => update({ workChangesTypeOther: e.target.value })}
                  placeholder="Please describe the change" />
              )}
            </Field>
            <Field label="Approximate start date" required>
              <Input type="month" value={d.workChangesDate || ''} onChange={e => update({ workChangesDate: e.target.value })} />
            </Field>
            <Field label="Anything else we should know?" span={2}>
              <Textarea rows="2" value={d.workChangesDetail || ''} onChange={e => update({ workChangesDetail: e.target.value })}
                placeholder="Optional - e.g. new occupation will be …" />
            </Field>
          </div>
        )}

        <Field label="Do you have a second occupation?" required>
          <YesNo value={d.secondOcc} onChange={v => update({ secondOcc: v })} />
        </Field>
        {d.secondOcc && (
          <div className="grid-2">
            <Field label="Second occupation" required>
              <Input value={d.secondOccTitle || ''} onChange={e => update({ secondOccTitle: e.target.value })} />
            </Field>
            <Field label="Hours per week in second occupation" required>
              <Input type="number" value={d.secondOccHours || ''} onChange={e => update({ secondOccHours: e.target.value })} />
            </Field>
            <Field label="Annual income from second occupation">
              <MoneyInput value={d.secondOccIncome || ''} onChange={e => update({ secondOccIncome: e.target.value })}
                placeholder="$0" />
            </Field>
          </div>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          5. INSOLVENCY & FINANCIAL CONDUCT
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Bankruptcy & insolvency history</div>
        <Field label="In the last 5 years, have you been declared bankrupt, entered any form of personal insolvency, or has any business you owned been placed into administration / liquidation / receivership?" required>
          <YesNo value={d.insolvency} onChange={v => update({ insolvency: v })} />
        </Field>
        {d.insolvency && (
          <>
            <div className="grid-2">
              <Field label="What type of event was it?" required>
                <Select value={d.insolvencyType || ''} onChange={e => update({ insolvencyType: e.target.value, insolvencyTypeOther: e.target.value === 'Other' ? (d.insolvencyTypeOther || '') : '' })}>
                  <option value="">Select…</option>
                  <option>Personal bankruptcy</option>
                  <option>Part IX debt agreement</option>
                  <option>Part X personal insolvency agreement</option>
                  <option>Business - administration</option>
                  <option>Business - liquidation</option>
                  <option>Business - receivership</option>
                  <option>Other</option>
                </Select>
                {d.insolvencyType === 'Other' && (
                  <Input style={{ marginTop: 8 }} required
                    value={d.insolvencyTypeOther || ''}
                    onChange={e => update({ insolvencyTypeOther: e.target.value })}
                    placeholder="Please describe the event" />
                )}
              </Field>
              <Field label="Approximate amount involved">
                <MoneyInput value={d.insolvencyAmount || ''}
                  onChange={e => update({ insolvencyAmount: e.target.value })} placeholder="$0" />
              </Field>
              <Field label="When did it commence?" required>
                <Input type="month" value={d.insolvencyStart || ''} onChange={e => update({ insolvencyStart: e.target.value })} />
              </Field>
              <Field label="Has it been discharged or finalised?" required>
                <YesNo value={d.insolvencyDischarged} onChange={v => update({ insolvencyDischarged: v })} />
              </Field>
              {d.insolvencyDischarged && (
                <Field label="When was it discharged / finalised?" required>
                  <Input type="month" value={d.insolvencyDischargedDate || ''} onChange={e => update({ insolvencyDischargedDate: e.target.value })} />
                </Field>
              )}
              <Field label="Has this happened more than once?" required>
                <YesNo value={d.insolvencyMulti} onChange={v => update({ insolvencyMulti: v })} />
              </Field>
              <Field label="Primary cause" required>
                <Select value={d.insolvencyCause || ''} onChange={e => update({ insolvencyCause: e.target.value, insolvencyCauseOther: e.target.value === 'Other' ? (d.insolvencyCauseOther || '') : '' })}>
                  <option value="">Select…</option>
                  <option>Business downturn</option>
                  <option>Loss of major customer / contract</option>
                  <option>Industry / market disruption (e.g. COVID)</option>
                  <option>Health event</option>
                  <option>Relationship breakdown</option>
                  <option>Personal financial mismanagement</option>
                  <option>Guarantor for a third party</option>
                  <option>Other</option>
                </Select>
                {d.insolvencyCause === 'Other' && (
                  <Input style={{ marginTop: 8 }} required
                    value={d.insolvencyCauseOther || ''}
                    onChange={e => update({ insolvencyCauseOther: e.target.value })}
                    placeholder="Please describe the cause" />
                )}
              </Field>
            </div>
            <Field label="Anything else we should know?">
              <Textarea rows="2" value={d.insolvencyDetail || ''} onChange={e => update({ insolvencyDetail: e.target.value })}
                placeholder="Optional - circumstances, lessons learned, current financial position." />
            </Field>
          </>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          6. PRIOR APPLICATIONS & CLAIMS
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Previous applications & claims</div>
        <Field label="In the last 10 years, has any insurance application of yours been declined, postponed, or accepted with a loading or exclusion?" required hint="Includes life, TPD, trauma, IP, travel and health insurance.">
          <YesNo value={d.priorAppsAny} onChange={v => update({ priorAppsAny: v })} />
        </Field>
        {d.priorAppsAny && (
          <>
            {priorApps.length === 0 && (
              <div className="empty-hint" style={{ marginTop: 12 }} data-ff-name="ins.priorApps">Add the first prior application below.</div>
            )}
            {priorApps.map((p, i) => (
              <RepeatItem key={i} title={`Prior application ${i+1}`}
                onRemove={() => { const n = [...priorApps]; n.splice(i,1); update({ priorApps: n }); }}>
                <div className="grid-2">
                  <Field label="Insurer" required>
                    <Input value={p.insurer || ''} onChange={e => updatePriorApp(i, { insurer: e.target.value })} />
                  </Field>
                  <Field label="Cover type" required>
                    <Select value={p.type || ''} onChange={e => updatePriorApp(i, { type: e.target.value, typeOther: e.target.value === 'Other' ? (p.typeOther || '') : '' })}>
                      <option value="">Select…</option>
                      <option>Life</option><option>TPD</option><option>Trauma</option><option>Income Protection</option>
                      <option>Health</option><option>Travel</option><option>Other</option>
                    </Select>
                    {p.type === 'Other' && (
                      <Input style={{ marginTop: 8 }} required
                        value={p.typeOther || ''}
                        onChange={e => updatePriorApp(i, { typeOther: e.target.value })}
                        placeholder="Please describe the cover type" />
                    )}
                  </Field>
                  <Field label="Year of application" required>
                    <Input type="number" min="1980" max="2099" value={p.year || ''} onChange={e => updatePriorApp(i, { year: e.target.value })} />
                  </Field>
                  <Field label="Outcome" required>
                    <Select value={p.outcome || ''} onChange={e => updatePriorApp(i, { outcome: e.target.value })}>
                      <option value="">Select…</option>
                      <option>Declined</option>
                      <option>Postponed / deferred</option>
                      <option>Accepted with loading / extra premium</option>
                      <option>Accepted with exclusion</option>
                      <option>Benefits reduced</option>
                      <option>Term reduced</option>
                    </Select>
                  </Field>
                  <Field label="Reason given (if known)" span={2}>
                    <ChipGroup multi options={['Medical', 'Occupation', 'Pastime / hobby', 'Other / unknown']} value={p.reasonType} onChange={v => updatePriorApp(i, { reasonType: v })} />
                  </Field>
                  <Field label="Reason detail" span={2}>
                    <Textarea rows="2" value={p.reason || ''} onChange={e => updatePriorApp(i, { reason: e.target.value })} />
                  </Field>
                </div>
              </RepeatItem>
            ))}
            <AddBtn onClick={() => update({ priorApps: [...priorApps, {}] })}>Add prior application</AddBtn>
          </>
        )}

        {(wantsTPD || wantsIP || coverTypes.includes('trauma')) && (
          <>
            <hr className="divider" />
            <Field label="In the last 10 years, have you lodged a claim (or do you intend to claim) for any injury or illness?" required hint="Includes Workers Compensation, sickness benefits, motor accident, public liability, and any income-protection claim.">
              <YesNo value={d.claimsAny} onChange={v => update({ claimsAny: v })} />
            </Field>
            {d.claimsAny && (
              <>
                {claims.length === 0 && (
                  <div className="empty-hint" style={{ marginTop: 12 }}>Add the first claim below.</div>
                )}
                {claims.map((cl, i) => (
                  <RepeatItem key={i} title={`Claim ${i+1}`}
                    onRemove={() => { const n = [...claims]; n.splice(i,1); update({ claims: n }); }}>
                    <div className="grid-2">
                      <Field label="Condition / injury claimed for" span={2} required>
                        <Input value={cl.condition || ''} onChange={e => updateClaim(i, { condition: e.target.value })} />
                      </Field>
                      <Field label="Type of claim" required>
                        <Select value={cl.type || ''} onChange={e => updateClaim(i, { type: e.target.value, typeOther: e.target.value === 'Other' ? (cl.typeOther || '') : '' })}>
                          <option value="">Select…</option>
                          <option>Workers Compensation</option>
                          <option>Income Protection / Salary Continuance</option>
                          <option>TPD</option>
                          <option>Trauma</option>
                          <option>Motor accident</option>
                          <option>Public liability</option>
                          <option>Other</option>
                        </Select>
                        {cl.type === 'Other' && (
                          <Input style={{ marginTop: 8 }} required
                            value={cl.typeOther || ''}
                            onChange={e => updateClaim(i, { typeOther: e.target.value })}
                            placeholder="Please describe the claim type" />
                        )}
                      </Field>
                      <Field label="Year of claim" required>
                        <Input type="number" min="1980" max="2099" value={cl.year || ''} onChange={e => updateClaim(i, { year: e.target.value })} />
                      </Field>
                      <Field label="Time off work">
                        <Select value={cl.timeOff || ''} onChange={e => updateClaim(i, { timeOff: e.target.value })}>
                          <option value="">Select…</option>
                          <option>None</option>
                          <option>Less than 1 week</option>
                          <option>Less than 1 month</option>
                          <option>1–3 months</option>
                          <option>3–6 months</option>
                          <option>More than 6 months</option>
                        </Select>
                      </Field>
                      <Field label="Has the claim been finalised?" required>
                        <YesNo value={cl.finalised} onChange={v => updateClaim(i, { finalised: v })} />
                      </Field>
                      {/* When the claim is still open the insurer needs
                          a description of the current status (under
                          assessment, awaiting payments, dispute, etc.)
                          to be able to underwrite around it. */}
                      {cl.finalised === false && (
                        <Field label="Current status of the claim" required
                          name={`ins.claim${i}.status`}
                          hint="e.g. under assessment, awaiting income protection payments, in dispute, etc."
                          span={2}>
                          <Textarea rows="2" value={cl.statusDetail || ''}
                            onChange={e => updateClaim(i, { statusDetail: e.target.value })} />
                        </Field>
                      )}
                      <Field label="Are you fully recovered?" required>
                        <YesNo value={cl.recovered} onChange={v => updateClaim(i, { recovered: v })} />
                      </Field>
                      {cl.recovered === false && (
                        <Field label="Ongoing impairment / symptoms" span={2}>
                          <Textarea rows="2" value={cl.ongoingDetail || ''} onChange={e => updateClaim(i, { ongoingDetail: e.target.value })} />
                        </Field>
                      )}
                    </div>
                  </RepeatItem>
                ))}
                <AddBtn onClick={() => update({ claims: [...claims, {}] })}>Add claim</AddBtn>
              </>
            )}
          </>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          7. PURSUITS & ACTIVITIES
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Pursuits & high-risk activities<span className="req">*</span></div>
        <Callout kind="info">
          Some recreational activities require additional underwriting. Tick anything you participate in - even casually - and we'll ask a few quick follow-ups.
        </Callout>
        <div style={{ marginTop: 14 }} data-ff-name="ins.pursuits">
          <div className="chip-group">
            {PURSUIT_OPTIONS.map(opt => (
              <button type="button" key={opt.id}
                className={cx('chip', pursuits.find(p => p.id === opt.id) && 'on')}
                onClick={() => togglePursuit(opt.id)}>
                {opt.label}
              </button>
            ))}
            <button type="button"
              className={cx('chip', noPursuits && 'on')}
              onClick={() => update({ pursuitsList: [], pursuitsNone: !d.pursuitsNone })}>
              None of the above
            </button>
          </div>
        </div>

        {pursuits.map((p) => {
          const opt = PURSUIT_OPTIONS.find(o => o.id === p.id);
          if (!opt) return null;
          return (
            <div key={p.id} className="repeat-item" style={{ marginTop: 14 }}>
              <div className="repeat-item-header">
                <div className="repeat-item-title">{opt.label}</div>
              </div>
              <div className="grid-2">
                <Field label="How many times per year do you participate?" required>
                  <Input type="number" min="0" value={p.frequency || ''} onChange={e => updatePursuit(p.id, { frequency: e.target.value })} />
                </Field>
                <Field label="Status" required>
                  <ChipGroup options={['Amateur / social', 'Semi-professional', 'Professional / paid']} value={p.paid} onChange={v => updatePursuit(p.id, { paid: v })} />
                </Field>
                <Field label="Are you licensed or certified?" required>
                  <YesNo value={p.licensed} onChange={v => updatePursuit(p.id, { licensed: v })} />
                </Field>
                {p.licensed && (
                  <Field label="Licence / certification level + number" required>
                    <Input value={p.licenseDetail || ''} onChange={e => updatePursuit(p.id, { licenseDetail: e.target.value })}
                      placeholder="e.g. PADI Open Water #12345" />
                  </Field>
                )}

                {/* activity-specific fields */}
                {p.id === 'aviation' && (
                  <>
                    <Field label="Hours flown per year">
                      <Input type="number" min="0" value={p.hoursPerYear || ''} onChange={e => updatePursuit(p.id, { hoursPerYear: e.target.value })} />
                    </Field>
                    <Field label="Type of flying" hint="e.g. private fixed-wing, microlight, ultralight, hang-glider">
                      <Input value={p.flyingType || ''} onChange={e => updatePursuit(p.id, { flyingType: e.target.value })} />
                    </Field>
                    <Field label="Any aerobatics, agricultural, display or oil-rig flying?">
                      <YesNo value={p.specialRisk} onChange={v => updatePursuit(p.id, { specialRisk: v })} />
                    </Field>
                  </>
                )}
                {p.id === 'diving' && (
                  <>
                    <Field label="Maximum depth (metres)">
                      <Input type="number" min="0" value={p.depth || ''} onChange={e => updatePursuit(p.id, { depth: e.target.value })} />
                    </Field>
                    <Field label="Solo, cave, wreck or night diving?">
                      <YesNo value={p.advancedDive} onChange={v => updatePursuit(p.id, { advancedDive: v })} />
                    </Field>
                    <Field label="Decompression diving or use of explosives?">
                      <YesNo value={p.decoDive} onChange={v => updatePursuit(p.id, { decoDive: v })} />
                    </Field>
                  </>
                )}
                {p.id === 'motor' && (
                  <>
                    <Field label="Type of vehicle and engine size">
                      <Input value={p.vehicleType || ''} onChange={e => updatePursuit(p.id, { vehicleType: e.target.value })} placeholder="e.g. road bike 1000cc" />
                    </Field>
                    <Field label="Maximum speed (km/h)">
                      <Input type="number" min="0" value={p.speed || ''} onChange={e => updatePursuit(p.id, { speed: e.target.value })} />
                    </Field>
                    <Field label="Take part in international events?">
                      <YesNo value={p.intlEvents} onChange={v => updatePursuit(p.id, { intlEvents: v })} />
                    </Field>
                  </>
                )}
                {p.id === 'climbing' && (
                  <Field label="Maximum altitude (metres)">
                    <Input type="number" min="0" value={p.altitude || ''} onChange={e => updatePursuit(p.id, { altitude: e.target.value })} />
                  </Field>
                )}
                {p.id === 'football' && (
                  <Field label="Code (rugby league/union, AFL, soccer, gridiron, touch)">
                    <Input value={p.football || ''} onChange={e => updatePursuit(p.id, { football: e.target.value })} />
                  </Field>
                )}
                {p.id === 'martial' && (
                  <Field label="Discipline and contact level" hint="e.g. BJJ no-strike, MMA full contact, boxing">
                    <Input value={p.martial || ''} onChange={e => updatePursuit(p.id, { martial: e.target.value })} />
                  </Field>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          8. PERSONAL HEALTH - height, weight, smoking, alcohol, drugs
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">About you - basic health</div>
        <div className="grid-2">
          <Field label="Height (cm)" required><Input type="number" value={d.height || ''} onChange={e => update({ height: e.target.value })} /></Field>
          <Field label="Weight (kg)" required><Input type="number" value={d.weight || ''} onChange={e => update({ weight: e.target.value })} /></Field>
        </div>

        <Field label="In the last 12 months, have you lost more than 10 kg?" required>
          <YesNo value={d.weightLoss} onChange={v => update({ weightLoss: v })} />
        </Field>
        {d.weightLoss && (
          <>
            <div className="grid-2">
              <Field label="How many kg did you lose?" required>
                <Input type="number" value={d.weightLossKg || ''} onChange={e => update({ weightLossKg: e.target.value })} />
              </Field>
              <Field label="Did you have weight-loss surgery?" required>
                <YesNo value={d.bariatricSurgery} onChange={v => update({ bariatricSurgery: v })} />
              </Field>
            </div>
            {d.bariatricSurgery && (
              <div className="grid-2">
                <Field label="When was the surgery?" required>
                  <Input type="month" value={d.bariatricDate || ''} onChange={e => update({ bariatricDate: e.target.value })} />
                </Field>
                <Field label="Have you fully recovered without complications?" required>
                  <YesNo value={d.bariatricRecovered} onChange={v => update({ bariatricRecovered: v })} />
                </Field>
                {d.bariatricRecovered === false && (
                  <Field label="Complications, treatment, time off work, current status" span={2}>
                    <Textarea rows="2" value={d.bariatricComplications || ''} onChange={e => update({ bariatricComplications: e.target.value })} />
                  </Field>
                )}
                <Field label="Does your GP have records of this surgery?">
                  <YesNo value={d.bariatricGpRecords} onChange={v => update({ bariatricGpRecords: v })} />
                </Field>
              </div>
            )}
            {!d.bariatricSurgery && (
              <div className="grid-2">
                <Field label="Cause of the weight loss" required>
                  <Select value={d.weightLossCause || ''} onChange={e => update({ weightLossCause: e.target.value, weightLossCauseOther: e.target.value === 'Other' ? (d.weightLossCauseOther || '') : '' })}>
                    <option value="">Select…</option>
                    <option>Intentional - diet & exercise</option>
                    <option>Intentional - weight-loss medication (e.g. Ozempic, Mounjaro)</option>
                    <option>Stress / mental health</option>
                    <option>Illness or medical condition</option>
                    <option>Surgery / hospitalisation</option>
                    <option>Unexplained</option>
                    <option>Other</option>
                  </Select>
                  {d.weightLossCause === 'Other' && (
                    <Input style={{ marginTop: 8 }} required
                      value={d.weightLossCauseOther || ''}
                      onChange={e => update({ weightLossCauseOther: e.target.value })}
                      placeholder="Please describe the cause" />
                  )}
                </Field>
                <Field label="Have you discussed it with a doctor?" required>
                  <YesNo value={d.weightLossSeenDoc} onChange={v => update({ weightLossSeenDoc: v })} />
                </Field>
                <Field label="Anything else we should know?" span={2}>
                  <Textarea rows="2" value={d.weightLossReason || ''} onChange={e => update({ weightLossReason: e.target.value })}
                    placeholder="Optional - e.g. medication name, illness, current status." />
                </Field>
              </div>
            )}
          </>
        )}

        <hr className="divider" />

        {/* Smoking - superset of TAL S8 + NEOS S7 */}
        <Field label="When did you last use tobacco, e-cigarettes or any nicotine product?" required>
          <ChipGroup
            options={['Never', 'More than 12 months ago', 'Currently or in the last 12 months']}
            value={d.smoke}
            onChange={v => update({ smoke: v })}
          />
        </Field>

        {d.smoke === 'Currently or in the last 12 months' && (
          <>
            <Field label="Which products?" span={2} required name="ins.smokeProducts">
              <ChipGroup multi
                options={['Cigarettes', 'Cigars / pipe', 'E-cigarettes / vape', 'Nicotine replacement (patch / gum)', 'Other']}
                value={d.smokeProducts}
                onChange={v => update({ smokeProducts: v })}
              />
            </Field>
            <div className="grid-2">
              <Field label="Quantity per day (cigarettes or equivalent)" required name="ins.smokePerDay">
                <Input type="number" min="0" value={d.smokePerDay || ''} onChange={e => update({ smokePerDay: e.target.value })} />
              </Field>
              <Field label="How many years have you been using nicotine?" required name="ins.smokeYears">
                <Input type="number" min="0" value={d.smokeYears || ''} onChange={e => update({ smokeYears: e.target.value })} />
              </Field>
            </div>
          </>
        )}

        {d.smoke === 'More than 12 months ago' && (
          <div className="grid-2">
            <Field label="When did you have your last cigarette / vape / nicotine product?" required>
              <Input type="month" value={d.smokeStopped || ''} onChange={e => update({ smokeStopped: e.target.value })} />
            </Field>
            <Field label="At your peak, how much per day?" required hint="Cigarettes or equivalent.">
              <Input type="number" min="0" value={d.smokePeakPerDay || ''} onChange={e => update({ smokePeakPerDay: e.target.value })} />
            </Field>
            <Field label="Total years you used nicotine" required>
              <Input type="number" min="0" value={d.smokeTotalYears || ''} onChange={e => update({ smokeTotalYears: e.target.value })} />
            </Field>
          </div>
        )}

        <hr className="divider" />

        {/* Alcohol */}
        <Field label="How many standard drinks do you have in a typical week?" required hint="1 standard drink = 1 glass of wine, 1 mid-strength beer, or 1 nip of spirits.">
          <Select value={d.alcohol || ''} onChange={e => update({ alcohol: e.target.value })}>
            <option value="">Select…</option>
            <option value="None">0 (none)</option>
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
            <option>6</option>
            <option>7</option>
            <option>8</option>
            <option>9</option>
            <option>10</option>
            <option>More than 10</option>
          </Select>
        </Field>

        {d.alcohol && d.alcohol !== 'None' && (
          <>
            <Field label="When you drink, how often do you have 5 or more standard drinks in a single day?" required name="ins.alcoholBinge" hint="A standard drink = 1 glass of wine, 1 mid-strength beer, or 1 nip of spirits.">
              <ChipGroup
                options={['Never', '2–3 times a year', 'No more than once a month', 'Once or twice a fortnight', 'Once or twice a week', '3+ days a week']}
                value={d.alcoholBinge}
                onChange={v => update({ alcoholBinge: v })}
              />
            </Field>
            {(d.alcoholBinge === 'Once or twice a fortnight' || d.alcoholBinge === 'Once or twice a week' || d.alcoholBinge === '3+ days a week') && (
              <Field label="On those occasions, how many standard drinks would you typically have?" required>
                <Input type="number" min="5" value={d.alcoholBingeAmount || ''} onChange={e => update({ alcoholBingeAmount: e.target.value })} />
              </Field>
            )}
          </>
        )}

        <Field label="Have you ever been advised by a medical professional to reduce, stop, or seek support for alcohol use?" required>
          <YesNo value={d.alcoholAdvised} onChange={v => update({ alcoholAdvised: v })} />
        </Field>
        {d.alcoholAdvised && (
          <div className="grid-2">
            <Field label="When was the advice given?" required>
              <Input type="month" value={d.alcoholAdvisedWhen || ''} onChange={e => update({ alcoholAdvisedWhen: e.target.value })} />
            </Field>
            <Field label="Did you act on the advice?" required>
              <Select value={d.alcoholAdvisedActed || ''} onChange={e => update({ alcoholAdvisedActed: e.target.value })}>
                <option value="">Select…</option>
                <option>Yes - abstinent now</option>
                <option>Yes - significantly reduced</option>
                <option>Partially</option>
                <option>No</option>
              </Select>
            </Field>
            <Field label="Anything else we should know?" span={2}>
              <Textarea rows="2" value={d.alcoholAdvisedDetail || ''} onChange={e => update({ alcoholAdvisedDetail: e.target.value })}
                placeholder="Optional - who advised, current consumption pattern." />
            </Field>
          </div>
        )}

        <hr className="divider" />

        {/* Drugs */}
        <Field label="In the last 10 years, have you smoked, injected, or otherwise used recreational or illegal drugs?" required hint="Cannabis, ecstasy, cocaine, ice, heroin, amphetamines, anabolic steroids, etc.">
          <YesNo value={d.drugs} onChange={v => update({ drugs: v })} />
        </Field>
        {d.drugs && (
          <>
            {(d.drugsList || []).length === 0 && (
              <div className="empty-hint" style={{ marginTop: 12 }} data-ff-name="ins.drugsList">Add the first substance below.</div>
            )}
            {(d.drugsList || []).map((dr, i) => (
              <RepeatItem key={i} title={`Substance ${i+1}`}
                onRemove={() => {
                  const n = [...(d.drugsList || [])]; n.splice(i,1);
                  update({ drugsList: n });
                }}>
                <div className="grid-2">
                  <Field label="Substance" required>
                    <Select value={dr.substance || ''} onChange={e => {
                      const n = [...(d.drugsList || [])]; n[i] = { ...n[i], substance: e.target.value, substanceOther: e.target.value === 'Other' ? (n[i].substanceOther || '') : '' };
                      update({ drugsList: n });
                    }}>
                      <option value="">Select…</option>
                      <option>Cannabis / marijuana</option>
                      <option>Cocaine</option>
                      <option>Ecstasy / MDMA</option>
                      <option>Amphetamines / ice / methamphetamine</option>
                      <option>Heroin / opioids</option>
                      <option>Hallucinogens (LSD, mushrooms, ketamine)</option>
                      <option>Anabolic steroids</option>
                      <option>Misuse of prescription medication</option>
                      <option>Other</option>
                    </Select>
                    {dr.substance === 'Other' && (
                      <Input style={{ marginTop: 8 }} required
                        value={dr.substanceOther || ''}
                        onChange={e => {
                          const n = [...(d.drugsList || [])]; n[i] = { ...n[i], substanceOther: e.target.value };
                          update({ drugsList: n });
                        }}
                        placeholder="Please describe the substance" />
                    )}
                  </Field>
                  <Field label="How was it used?" required>
                    <Select value={dr.method || ''} onChange={e => {
                      const n = [...(d.drugsList || [])]; n[i] = { ...n[i], method: e.target.value, methodOther: e.target.value === 'Other' ? (n[i].methodOther || '') : '' };
                      update({ drugsList: n });
                    }}>
                      <option value="">Select…</option>
                      <option>Smoked / inhaled</option>
                      <option>Swallowed</option>
                      <option>Snorted</option>
                      <option>Injected</option>
                      <option>Other</option>
                    </Select>
                    {dr.method === 'Other' && (
                      <Input style={{ marginTop: 8 }} required
                        value={dr.methodOther || ''}
                        onChange={e => {
                          const n = [...(d.drugsList || [])]; n[i] = { ...n[i], methodOther: e.target.value };
                          update({ drugsList: n });
                        }}
                        placeholder="Please describe the method" />
                    )}
                  </Field>
                  <Field label="Frequency" required>
                    <Select value={dr.frequency || ''} onChange={e => {
                      const n = [...(d.drugsList || [])]; n[i] = { ...n[i], frequency: e.target.value };
                      update({ drugsList: n });
                    }}>
                      <option value="">Select…</option>
                      <option>One-off / experimental</option>
                      <option>Less than monthly</option>
                      <option>Monthly</option>
                      <option>Weekly</option>
                      <option>Several times a week</option>
                      <option>Daily</option>
                    </Select>
                  </Field>
                  <Field label="Last used" required>
                    <Input type="month" value={dr.lastUsed || ''} onChange={e => {
                      const n = [...(d.drugsList || [])]; n[i] = { ...n[i], lastUsed: e.target.value };
                      update({ drugsList: n });
                    }} />
                  </Field>
                  <Field label="Are you still using?" span={2} required>
                    <YesNo value={dr.stillUsing} onChange={v => {
                      const n = [...(d.drugsList || [])]; n[i] = { ...n[i], stillUsing: v };
                      update({ drugsList: n });
                    }} />
                  </Field>
                </div>
              </RepeatItem>
            ))}
            <AddBtn onClick={() => update({ drugsList: [...(d.drugsList || []), {}] })}>Add substance</AddBtn>
          </>
        )}

        <Field label="In the last 10 years, have you sought (or been advised to seek) help for any dependency, addiction or substance abuse?" required hint="Including alcohol, prescription drugs, gaming, gambling.">
          <YesNo value={d.dependency} onChange={v => update({ dependency: v })} />
        </Field>
        {d.dependency && (
          <Field label="Please describe" required>
            <Textarea rows="2" value={d.dependencyDetail || ''} onChange={e => update({ dependencyDetail: e.target.value })} />
          </Field>
        )}

        {/* Pregnancy - primary applicant female only */}
        {isFemale && (
          <>
            <hr className="divider" />
            <Field label="Are you currently pregnant or planning a pregnancy in the next 12 months?" required>
              <ChipGroup options={['No', 'Currently pregnant', 'Planning in next 12 months']} value={d.pregnancy} onChange={v => update({ pregnancy: v })} />
            </Field>
            {d.pregnancy === 'Currently pregnant' && (
              <div className="grid-2">
                <Field label="Approximate due date" required>
                  <Input type="date" value={d.pregnancyDue || ''} onChange={e => update({ pregnancyDue: e.target.value })} />
                </Field>
                <Field label="How many weeks?" required>
                  <Input type="number" min="1" max="42" value={d.pregnancyWeeks || ''} onChange={e => update({ pregnancyWeeks: e.target.value })} />
                </Field>
                <Field label="Any complications or non-routine investigations?" span={2} required>
                  <YesNo value={d.pregnancyComplications} onChange={v => update({ pregnancyComplications: v })} />
                </Field>
                {d.pregnancyComplications && (
                  <Field label="Please describe" span={2} required>
                    <Textarea rows="2" value={d.pregnancyComplicationsDetail || ''} onChange={e => update({ pregnancyComplicationsDetail: e.target.value })} />
                  </Field>
                )}
              </div>
            )}
            <Field label="Have you given birth to a child with congenital abnormalities?" required>
              <YesNo value={d.congenital} onChange={v => update({ congenital: v })} />
            </Field>
            {d.congenital && (
              <Field label="Please briefly describe" required>
                <Textarea rows="2" value={d.congenitalDetail || ''} onChange={e => update({ congenitalDetail: e.target.value })} />
              </Field>
            )}
          </>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          9. FAMILY MEDICAL HISTORY
          ═══════════════════════════════════════════════════════════ */}
      <div className="card" data-ff-name="ins.familyHistory">
        <div className="card-title">Family medical history<span className="req">*</span></div>
        <Callout kind="info">
          Has your mother, father, brother or sister (living or deceased) been <strong>diagnosed before age 65</strong> with any of the following? Tick anything that applies, then add a row per affected family member below. Diagnoses at <strong>65 or older</strong> don't need to be disclosed here.
        </Callout>
        <div style={{ marginTop: 14 }}>
          <div className="chip-group">
            {FAMILY_CONDITIONS.map(fc => (
              <button type="button" key={fc.id}
                className={cx('chip', familyConditionsTicked.includes(fc.id) && 'on')}
                onClick={() => toggleFamilyCondition(fc.id)}>
                {fc.label}
              </button>
            ))}
            <button type="button"
              className={cx('chip', familyNone && 'on')}
              onClick={() => update({ familyConditionsTicked: [], family: [], familyNone: !d.familyNone })}>
              None of the above
            </button>
          </div>
        </div>

        {familyConditionsTicked.length > 0 && (
          <>
            <hr className="divider" />
            <SubSectionHeading>Affected relatives</SubSectionHeading>
            {family.length === 0 && (
              <div className="empty-hint">Add a row per affected relative below.</div>
            )}
            {family.map((f, i) => {
              const tickedConds = FAMILY_CONDITIONS.filter(fc => familyConditionsTicked.includes(fc.id));
              const conditionChoices = [];
              tickedConds.forEach(fc => (fc.relativeOptions || [fc.label]).forEach(opt => conditionChoices.push(opt)));
              conditionChoices.push('Other');
              const selectedConditions = Array.isArray(f.conditions) ? f.conditions
                : (f.condition ? [f.condition] : []);
              // A relative saved before a `relativeOptions` list changed (e.g.
              // the old combined "Heart disease, heart attack, angina or
              // stroke" chip, now split into four) would otherwise hold a
              // value with no chip to show it - invisible on screen but still
              // in the data. Surface any such value as its own chip so the
              // client can see it and re-pick.
              selectedConditions.forEach(sel => {
                if (sel && !conditionChoices.includes(sel)) conditionChoices.push(sel);
              });
              // Airtight cancer-type capture: if the ONLY ticked family
              // category is "Any other type of cancer" (id 'cancer'), the
              // cancer is implied for every listed relative even if they
              // didn't tick the per-relative chip - so still show + require
              // the "what type of cancer?" box.
              const impliedOtherCancer = familyConditionsTicked.length === 1
                && familyConditionsTicked[0] === 'cancer'
                && selectedConditions.length === 0;
              const needCancerType = selectedConditions.includes('Any other type of cancer') || impliedOtherCancer;
              const toggleCond = (opt) => {
                const next = selectedConditions.includes(opt)
                  ? selectedConditions.filter(x => x !== opt)
                  : [...selectedConditions, opt];
                updateFamily(i, { conditions: next, condition: undefined });
              };
              return (
              <RepeatItem key={i} title={`Relative ${i+1}`}
                onRemove={() => { const n = [...family]; n.splice(i,1); update({ family: n }); }}>
                <div className="grid-2">
                  <Field label="Relationship" required>
                    <Select value={f.relationship || ''} onChange={e => updateFamily(i, { relationship: e.target.value })}>
                      <option value="">Select…</option>
                      <option>Mother</option><option>Father</option>
                      <option>Sister</option><option>Brother</option>
                      <option>Daughter</option><option>Son</option>
                    </Select>
                  </Field>
                  <Field label="Age when diagnosed" required>
                    <Input type="number" min="0" max="110" value={f.ageDiagnosed || ''} onChange={e => updateFamily(i, { ageDiagnosed: e.target.value })} />
                  </Field>
                  <Field label={`Condition${selectedConditions.length > 1 ? 's' : ''} - tick all that apply to this relative`} span={2}
                    required={familyConditionsTicked.length >= 2}
                    hint="Select multiple if this relative had more than one of the conditions you've ticked above.">
                    <div className="chip-group">
                      {conditionChoices.map(opt => (
                        <button type="button" key={opt}
                          className={cx('chip', selectedConditions.includes(opt) && 'on')}
                          onClick={() => toggleCond(opt)}>
                          {opt}
                        </button>
                      ))}
                    </div>
                  </Field>
                  {selectedConditions.includes('Other') && (
                    <Field label="Please describe the other condition" span={2} required
                      name={`ins.family${i}.conditionOther`}>
                      <Input value={f.conditionOther || ''} onChange={e => updateFamily(i, { conditionOther: e.target.value })}
                        placeholder="e.g. Pulmonary fibrosis at age 58" />
                    </Field>
                  )}
                  {/* "Any other type of cancer" must always be specified
                      so the new adviser / insurer knows which cancer. */}
                  {needCancerType && (
                    <Field label="What type of cancer?" span={2} required
                      name={`ins.family${i}.cancerType`}
                      hint="e.g. pancreatic, liver, kidney, throat, lung, etc.">
                      <Input value={f.cancerType || ''} onChange={e => updateFamily(i, { cancerType: e.target.value })}
                        placeholder="e.g. Pancreatic cancer" />
                    </Field>
                  )}
                  <Field label="Still living?" required>
                    <YesNo value={f.living} onChange={v => updateFamily(i, { living: v })} />
                  </Field>
                  {f.living === false && (
                    <Field label="Age at death" required>
                      <Input type="number" min="0" max="110" value={f.ageDeath || ''} onChange={e => updateFamily(i, { ageDeath: e.target.value })} />
                    </Field>
                  )}
                </div>
              </RepeatItem>
              );
            })}
            <AddBtn onClick={() => update({ family: [...family, {}] })}>Add affected relative</AddBtn>

            {/* Per-ticked-condition hereditary question. Each top-level
                family condition the client picked needs to be tagged as
                hereditary / not hereditary / unsure so the insurer's
                underwriting team can weight it appropriately. */}
            <hr className="divider" />
            <SubSectionHeading>Is the condition hereditary?</SubSectionHeading>
            <div className="field-hint" style={{ marginTop: -4, marginBottom: 14 }}>
              For each condition you've ticked above, tell us whether it tends to run in your family.
            </div>
            {familyConditionsTicked.map(condId => {
              const fc = FAMILY_CONDITIONS.find(x => x.id === condId);
              if (!fc) return null;
              const heredMap = d.familyHereditary || {};
              return (
                <Field key={condId}
                  label={`Is ${fc.label.toLowerCase()} a hereditary condition?`}
                  required name={`ins.family.heredity.${condId}`}>
                  <ChipGroup
                    options={['Yes', 'No', 'Unsure']}
                    value={heredMap[condId] || ''}
                    onChange={v => update({ familyHereditary: { ...heredMap, [condId]: v } })} />
                </Field>
              );
            })}
          </>
        )}

        <hr className="divider" />
        <Field label="Have you had a genetic test?" required hint="Disclosing a favourable (negative) result may improve your application - but you don't have to disclose any genetic test if you don't want to. Tests for pregnancy / IVF are excluded.">
          <ChipGroup
            options={['No', 'Yes - negative result', 'Yes - positive result', 'Prefer not to say']}
            value={d.genetic}
            onChange={v => update({ genetic: v })}
          />
        </Field>
        {(d.genetic === 'Yes - negative result' || d.genetic === 'Yes - positive result') && (
          <Field label="What condition were you tested for?">
            <Input value={d.geneticCondition || ''} onChange={e => update({ geneticCondition: e.target.value })}
              placeholder="e.g. BRCA1, Huntington's, haemochromatosis" />
          </Field>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          10. MEDICAL HISTORY - categorised, with inline deep-dive on tick
          ═══════════════════════════════════════════════════════════ */}
      <div className="card" data-ff-name="ins.medicalHistory">
        <div className="card-title">Your medical history<span className="req">*</span></div>
        <Callout kind="warn">
          <strong>Please read each item carefully.</strong> Insurers can void cover at claim time if a condition wasn't disclosed - even one that seemed minor or fully resolved. Tick anything you've ever been told about, treated for, or investigated for. <strong>If in doubt, tick it</strong> - your adviser can clarify with you before submission.
        </Callout>
        <Callout kind="info">
          Every question below needs an answer. Tick the items that apply, or tick <strong>None of the above</strong> for that question. <strong>None of the above</strong> only ever covers the one question it sits under, so you'll need to answer each question in turn.
        </Callout>

        {/* Group 1 - IN THE LAST 5 YEARS */}
        <div style={{ marginTop: 4 }}>
          <SubSectionHeading>In the last 5 years, have you experienced any of the following?</SubSectionHeading>
          <div className="field-hint" style={{ marginTop: -4, marginBottom: 14 }}>
            Even if managed with medication or now resolved.
          </div>
          {MED_CATEGORIES.map(cat => {
            const catNone = isCatNone('last5', cat.id);
            return (
              <div key={cat.id} className="ff-med-cat" data-ff-name={`ins.medCat.last5.${cat.id}`}>
                <div className="ff-med-cat-title">{cat.title}</div>
                {!catNone && cat.items.map(item => {
                  const ticked = isTicked('last5', item.id);
                  const siblings = ticked ? siblingConditionsFor('last5', item.id) : [];
                  return (
                    <div key={item.id} className={cx('ff-med-item', ticked && 'ff-med-item-active')}>
                      <button type="button"
                        className={cx('ff-med-item-toggle', ticked && 'on')}
                        aria-pressed={ticked}
                        onClick={() => toggleConditionWithRetain('last5', item)}>
                        <span className="ff-med-item-tick">{ticked ? '✓' : ''}</span>
                        <span className="ff-med-item-label">{item.label}</span>
                      </button>
                      {ticked && siblings.length > 0 && (
                        <div className="ff-med-item-body">
                          {siblings.map((cond, sIdx) => (
                            <div key={cond.id} style={{ marginTop: sIdx > 0 ? 18 : 0, paddingTop: sIdx > 0 ? 18 : 0, borderTop: sIdx > 0 ? '1px dashed var(--line)' : 'none' }}>
                              {sIdx > 0 && (
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                                  <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--mute)' }}>Additional {item.label.split(',')[0].toLowerCase()} #{sIdx + 1}</div>
                                  <button type="button" className="add-btn add-btn-danger"
                                    style={{ fontSize: 12 }}
                                    onClick={() => removeSiblingCondition(cond.id)}>Remove</button>
                                </div>
                              )}
                              <ConditionDetails
                                c={cond}
                                examples={item.examples || []}
                                onChange={(patch) => updateCondition(cond.id, patch)}
                                isMentalHealth={MENTAL_HEALTH_IDS.has(item.id)}
                                categoryId={cat.id} />
                            </div>
                          ))}
                          <div style={{ marginTop: 12 }}>
                            <AddBtn onClick={() => addSiblingCondition('last5', item)}>
                              Add another {item.label.split(',')[0].toLowerCase()}
                            </AddBtn>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
                {/* Every question gets its own None toggle - including the
                    single-item ones. There is no master "no medical history"
                    banner any more, so this is the only way to answer a
                    question in the negative, and each answer is scoped to
                    the one question above it. */}
                <button type="button"
                  className={cx('ff-med-item-toggle ff-med-cat-none', catNone && 'on')}
                  style={{ marginTop: 6, fontStyle: 'italic' }}
                  aria-pressed={catNone}
                  onClick={() => toggleCatNone('last5', cat)}>
                  <span className="ff-med-item-tick">{catNone ? '✓' : ''}</span>
                  <span className="ff-med-item-label">None of the above</span>
                </button>
              </div>
            );
          })}
        </div>

        {/* Group 2 - EVER (excluding anything already ticked in 5y) */}
        <div style={{ marginTop: 24 }}>
          <SubSectionHeading>Have you EVER had any of the following?</SubSectionHeading>
          <div className="field-hint" style={{ marginTop: -4, marginBottom: 14 }}>
            Lifetime - even if resolved. (Anything you've already ticked above is hidden here so you don't double-answer.)
          </div>
          {MED_CATEGORIES_EVER.map(cat => {
            const catNone = isCatNone('ever', cat.id);
            return (
              <div key={cat.id} className="ff-med-cat" data-ff-name={`ins.medCat.ever.${cat.id}`}>
                <div className="ff-med-cat-title">{cat.title}</div>
                {!catNone && cat.items.map(item => {
                  const ticked = isTicked('ever', item.id);
                  // Skip if a 5y entry with the same item id is ticked (dedup)
                  if (!ticked && isTicked('last5', item.id)) return null;
                  const siblings = ticked ? siblingConditionsFor('ever', item.id) : [];
                  return (
                    <div key={item.id} className={cx('ff-med-item', ticked && 'ff-med-item-active')}>
                      <button type="button"
                        className={cx('ff-med-item-toggle', ticked && 'on')}
                        aria-pressed={ticked}
                        onClick={() => toggleConditionWithRetain('ever', item)}>
                        <span className="ff-med-item-tick">{ticked ? '✓' : ''}</span>
                        <span className="ff-med-item-label">{item.label}</span>
                      </button>
                      {ticked && siblings.length > 0 && (
                        <div className="ff-med-item-body">
                          {siblings.map((cond, sIdx) => (
                            <div key={cond.id} style={{ marginTop: sIdx > 0 ? 18 : 0, paddingTop: sIdx > 0 ? 18 : 0, borderTop: sIdx > 0 ? '1px dashed var(--line)' : 'none' }}>
                              {sIdx > 0 && (
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                                  <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--mute)' }}>Additional {item.label.split(',')[0].toLowerCase()} #{sIdx + 1}</div>
                                  <button type="button" className="add-btn add-btn-danger"
                                    style={{ fontSize: 12 }}
                                    onClick={() => removeSiblingCondition(cond.id)}>Remove</button>
                                </div>
                              )}
                              <ConditionDetails
                                c={cond}
                                examples={item.examples || []}
                                onChange={(patch) => updateCondition(cond.id, patch)}
                                isMentalHealth={MENTAL_HEALTH_IDS.has(item.id)}
                                categoryId={cat.id} />
                            </div>
                          ))}
                          <div style={{ marginTop: 12 }}>
                            <AddBtn onClick={() => addSiblingCondition('ever', item)}>
                              Add another {item.label.split(',')[0].toLowerCase()}
                            </AddBtn>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
                <button type="button"
                  className={cx('ff-med-item-toggle ff-med-cat-none', catNone && 'on')}
                  style={{ marginTop: 6, fontStyle: 'italic' }}
                  aria-pressed={catNone}
                  onClick={() => toggleCatNone('ever', cat)}>
                  <span className="ff-med-item-tick">{catNone ? '✓' : ''}</span>
                  <span className="ff-med-item-label">None of the above</span>
                </button>
              </div>
            );
          })}
        </div>

        {/* Group 3 - LAST 2 YEARS (general flags - tick + brief textarea, no full deep-dive) */}
        <div style={{ marginTop: 24 }}>
          <SubSectionHeading>In the last 2 years, have any of the following applied?</SubSectionHeading>
          <div className="field-hint" style={{ marginTop: -4, marginBottom: 14 }}>
            Anything not already disclosed above.
          </div>
          <div className="ff-med-cat" data-ff-name={`ins.medCat.${RECENT_NONE_KEY}`}>
            {!recentNone && MED_RECENT.map(item => {
              const id = `recent.${item.id}`;
              const ticked = isTicked('recent', item.id);
              const cond = ticked ? conditionsList.find(c => c.id === id) : null;
              // If this flag has a `triggers` mapping, ticking it should also
              // auto-tick the referenced deep-dive condition so the full
              // questionnaire opens for it.
              const handleToggle = () => {
                if (item.triggers && !ticked) {
                  // tick THIS flag, AND ensure the triggered condition is ticked too
                  const trig = item.triggers;
                  const trigItem = (MED_CATEGORIES.find(g => g.id === trig.group)?.items || []).find(it => it.id === trig.item);
                  // The deep-dive categories render under the 'last5' surface
                  // (isTicked('last5', item.id)), so the auto-opened row MUST
                  // use that id/group or its editor never appears and the
                  // "which condition / severity" fields can never be filled.
                  const trigId = `last5.${trig.item}`;
                  let nextList = [...conditionsList];
                  // tick the recent flag itself, marked as triggered so the
                  // validator doesn't ask for a free-text note we never show
                  // (the detail is captured in the deep-dive it opens).
                  nextList.push({ ...(conditionsRetained[id] || { id, group: 'recent', item: item.id, suggested: item.label }), triggered: true });
                  // ensure the triggered deep-dive is also ticked
                  if (trigItem && !nextList.some(c => c.id === trigId)) {
                    nextList.push(conditionsRetained[trigId] || { id: trigId, group: 'last5', item: trig.item, suggested: trigItem.label });
                  }
                  // This answers TWO questions at once - the last-2-years
                  // flag, and the question the deep-dive it opens sits
                  // under - so clear the "None of the above" on both.
                  const nextNone = settleCatNone(MED_NONE_KEY_OF_ITEM[id]);
                  delete nextNone[MED_NONE_KEY_OF_ITEM[trigId]];
                  update({ conditionsList: nextList, catNone: nextNone, conditionsNone: false });
                } else {
                  toggleConditionWithRetain('recent', item);
                }
              };
              return (
                <div key={item.id} className={cx('ff-med-item', ticked && 'ff-med-item-active')}>
                  <button type="button"
                    className={cx('ff-med-item-toggle', ticked && 'on')}
                    aria-pressed={ticked}
                    onClick={handleToggle}>
                    <span className="ff-med-item-tick">{ticked ? '✓' : ''}</span>
                    <span className="ff-med-item-label">{item.label}</span>
                  </button>
                  {ticked && cond && (
                    <div className="ff-med-item-body">
                      {item.triggers ? (
                        <Callout kind="info">
                          We've also opened the <strong>Mental health & wellbeing</strong> questionnaire above so you can give us a bit more detail about what you saw them for.
                        </Callout>
                      ) : item.id === 'allied' ? (
                        <Field label="Please provide details of the treatment" required span={2}
                          hint="Include the condition or reason for treatment, the number of sessions attended, and approximate dates of treatment.">
                          <Textarea rows="3"
                            value={cond.recentNote || ''}
                            onChange={e => updateCondition(id, { recentNote: e.target.value })}
                            placeholder="e.g. Saw a physiotherapist in 2022 for shoulder tendinopathy, 8 sessions over 3 months." />
                        </Field>
                      ) : (
                        <Field label="Briefly tell us about it" required hint="What it was, when, and the outcome." span={2}>
                          <Textarea rows="3"
                            value={cond.recentNote || ''}
                            onChange={e => updateCondition(id, { recentNote: e.target.value })}
                            placeholder="e.g. Course of physio for shoulder pain (Mar to Apr 2024); fully recovered." />
                        </Field>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
            <button type="button"
              className={cx('ff-med-item-toggle ff-med-cat-none', recentNone && 'on')}
              style={{ marginTop: 6, fontStyle: 'italic' }}
              aria-pressed={recentNone}
              onClick={() => toggleCatNone('recent', RECENT_AS_CATEGORY)}>
              <span className="ff-med-item-tick">{recentNone ? '✓' : ''}</span>
              <span className="ff-med-item-label">None of the above</span>
            </button>
          </div>
        </div>

        {/* Confirm-on-remove dialog (lives at the foot of the card) */}
        {pendingRemoveId && (() => {
          const target = conditionsList.find(c => c.id === pendingRemoveId);
          const labelMap = {};
          [...MED_CATEGORIES, ...MED_CATEGORIES_EVER].forEach(cat => cat.items.forEach(it => { labelMap[it.id] = it.label; }));
          MED_RECENT.forEach(it => { labelMap[it.id] = it.label; });
          const lbl = target ? (labelMap[target.item] || target.suggested || 'this item') : 'this item';
          return (
            <ConfirmDialog
              title="Untick this condition?"
              message={
                `If you untick "${lbl}", it will be hidden from the list. Anything you've already entered will be kept against your save code - re-tick the condition any time to bring it back exactly as it was.`
              }
              confirmLabel="Yes, untick"
              cancelLabel="Keep ticked"
              onConfirm={() => {
                // Untick removes the primary AND every sibling row
                // (`${pendingRemoveId}#N`) so the user's "Add another"
                // entries don't get orphaned. Retained map keeps the
                // primary for re-tick; siblings are not retained
                // because the user can recreate them with Add another.
                const next = conditionsList.filter(c =>
                  c.id !== pendingRemoveId && !(c.id || '').startsWith(`${pendingRemoveId}#`)
                );
                update({
                  conditionsList: next,
                  conditionsRetained: { ...(d.conditionsRetained || {}), [pendingRemoveId]: target },
                });
                setPendingRemoveId(null);
              }}
              onCancel={() => setPendingRemoveId(null)} />
          );
        })()}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          11. CURRENT MEDICATIONS, RECENT SYMPTOMS, PENDING
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Current medications, recent symptoms & anything pending</div>

        {/* Current medications */}
        <SubSectionHeading>Current medications</SubSectionHeading>
        <Field label="Do you currently take any prescribed medication?" required hint="Excluding contraceptives. Include daily inhalers, blood-pressure tablets, antidepressants, statins, etc.">
          <YesNo value={d.meds} onChange={v => update({ meds: v })} />
        </Field>
        {d.meds && (
          <>
            {(d.medsList || []).length === 0 && (
              <div className="empty-hint" style={{ marginTop: 12 }}>Add the first medication below.</div>
            )}
            {(d.medsList || []).map((m, i) => (
              <RepeatItem key={i} title={`Medication ${i+1}`}
                onRemove={() => {
                  const n = [...(d.medsList || [])]; n.splice(i,1);
                  update({ medsList: n });
                }}>
                <div className="grid-2">
                  <Field label="Medication name" required name={`ins.med${i}.name`} span={2}>
                    <Input value={m.name || ''} onChange={e => {
                      const n = [...(d.medsList || [])]; n[i] = { ...n[i], name: e.target.value };
                      update({ medsList: n });
                    }} placeholder="e.g. Atorvastatin" />
                  </Field>
                  <Field label="Dose / measurement" required name={`ins.med${i}.dose`}>
                    <Input value={m.dose || ''} onChange={e => {
                      const n = [...(d.medsList || [])]; n[i] = { ...n[i], dose: e.target.value };
                      update({ medsList: n });
                    }} placeholder="e.g. 20 mg" />
                  </Field>
                  <Field label="How often (frequency)" required name={`ins.med${i}.freq`}>
                    <Input value={m.freq || ''} onChange={e => {
                      const n = [...(d.medsList || [])]; n[i] = { ...n[i], freq: e.target.value };
                      update({ medsList: n });
                    }} placeholder="e.g. Once daily" />
                  </Field>
                  <Field label="What is it for?" required name={`ins.med${i}.reason`} span={2}>
                    <Input value={m.reason || ''} onChange={e => {
                      const n = [...(d.medsList || [])]; n[i] = { ...n[i], reason: e.target.value };
                      update({ medsList: n });
                    }} placeholder="e.g. high cholesterol" />
                  </Field>
                  <Field label="Started taking" required name={`ins.med${i}.started`} span={2}>
                    <Input type="month" value={m.startedAt || ''} onChange={e => {
                      const n = [...(d.medsList || [])]; n[i] = { ...n[i], startedAt: e.target.value };
                      update({ medsList: n });
                    }} />
                  </Field>
                </div>
              </RepeatItem>
            ))}
            <AddBtn onClick={() => update({ medsList: [...(d.medsList || []), {}] })}>Add medication</AddBtn>
          </>
        )}

        <hr className="divider" />

        {/* Recent symptoms - tick any that apply OR confirm "None of the above" */}
        <SubSectionHeading>In the last 3 months</SubSectionHeading>
        <Field label="In the last 3 months, have you experienced any of the following?" span={2}
          required name="ins.recentSymptoms"
          hint='Tick anything that applies, or tick "None of the above" to confirm none do.'>
          <ChipGroup multi options={RECENT_SYMPTOMS} value={d.recentSymptoms}
            onChange={v => update({ recentSymptoms: v, recentSymptomsNone: v.length > 0 ? false : d.recentSymptomsNone })} />
          <div style={{ marginTop: 10 }}>
            <button type="button"
              className={cx('chip', d.recentSymptomsNone && 'on')}
              onClick={() => update({
                recentSymptomsNone: !d.recentSymptomsNone,
                recentSymptoms: !d.recentSymptomsNone ? [] : d.recentSymptoms,
              })}>
              {d.recentSymptomsNone ? '✓ ' : ''}None of the above
            </button>
          </div>
        </Field>
        {(d.recentSymptoms || []).map((sym) => (
          <Field key={sym} label={`Tell us about: "${sym}"`} required>
            <Textarea rows="2"
              value={(d.recentSymptomsByItem || {})[sym] || ''}
              onChange={e => update({
                recentSymptomsByItem: { ...(d.recentSymptomsByItem || {}), [sym]: e.target.value },
              })}
              placeholder="When it started, how often, severity, whether you've seen a doctor." />
          </Field>
        ))}

        <hr className="divider" />

        {/* Pending */}
        <SubSectionHeading>Anything pending or planned</SubSectionHeading>
        <Field label="Are you planning to seek, awaiting, or been advised to undertake any medical advice, tests, surgery or treatment?" required>
          <YesNo value={d.pendingMedical} onChange={v => update({ pendingMedical: v })} />
        </Field>
        {d.pendingMedical && (
          <>
            {(d.pendingMedicalList || []).length === 0 && (
              <div className="empty-hint" style={{ marginTop: 12 }}>Add the first pending item below.</div>
            )}
            {(d.pendingMedicalList || []).map((pm, i) => (
              <RepeatItem key={i} title={`Pending item ${i+1}`}
                onRemove={() => {
                  const n = [...(d.pendingMedicalList || [])]; n.splice(i,1);
                  update({ pendingMedicalList: n });
                }}>
                <div className="grid-2">
                  <Field label="Type" required>
                    <Select value={pm.type || ''} onChange={e => {
                      const n = [...(d.pendingMedicalList || [])]; n[i] = { ...n[i], type: e.target.value, typeOther: e.target.value === 'Other' ? (n[i].typeOther || '') : '' };
                      update({ pendingMedicalList: n });
                    }}>
                      <option value="">Select…</option>
                      <option>Specialist consultation / referral</option>
                      <option>Scan or imaging (MRI, CT, ultrasound, x-ray)</option>
                      <option>Blood test / pathology</option>
                      <option>Surgery or procedure</option>
                      <option>Awaiting results</option>
                      <option>Treatment course (e.g. physio, counselling)</option>
                      <option>Health screening (colonoscopy, mammogram, etc.)</option>
                      <option>Other</option>
                    </Select>
                    {pm.type === 'Other' && (
                      <Input style={{ marginTop: 8 }} required
                        value={pm.typeOther || ''}
                        onChange={e => {
                          const n = [...(d.pendingMedicalList || [])]; n[i] = { ...n[i], typeOther: e.target.value };
                          update({ pendingMedicalList: n });
                        }}
                        placeholder="Please describe the type" />
                    )}
                  </Field>
                  <Field label="What is it for?" required>
                    <Input value={pm.reason || ''} onChange={e => {
                      const n = [...(d.pendingMedicalList || [])]; n[i] = { ...n[i], reason: e.target.value };
                      update({ pendingMedicalList: n });
                    }} placeholder="e.g. shoulder pain, follow-up of high BP" />
                  </Field>
                  <Field label="Date booked / due" required>
                    <Input type="month" value={pm.dueDate || ''} onChange={e => {
                      const n = [...(d.pendingMedicalList || [])]; n[i] = { ...n[i], dueDate: e.target.value };
                      update({ pendingMedicalList: n });
                    }} />
                  </Field>
                  <Field label="Who recommended it?">
                    <Select value={pm.referrer || ''} onChange={e => {
                      const n = [...(d.pendingMedicalList || [])]; n[i] = { ...n[i], referrer: e.target.value };
                      update({ pendingMedicalList: n });
                    }}>
                      <option value="">Select…</option>
                      <option>My GP</option>
                      <option>A specialist</option>
                      <option>Self-initiated</option>
                      <option>Routine screening</option>
                    </Select>
                  </Field>
                </div>
              </RepeatItem>
            ))}
            <AddBtn onClick={() => update({ pendingMedicalList: [...(d.pendingMedicalList || []), {}] })}>Add pending item</AddBtn>
          </>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          12. YOUR CHILDREN (display only - pulled from Personal section)
          ═══════════════════════════════════════════════════════════ */}
      {(() => {
        const deps = (data?.personal?.primary?.deps || []).filter(dep => {
          const r = (dep.relationship || '').toLowerCase();
          return r.includes('child') || r.includes('son') || r.includes('daughter') || r === '' && dep.name;
        });
        // Show all dependants we've captured - let adviser/client decide.
        const allDeps = data?.personal?.primary?.deps || [];
        if (!data?.personal?.primary?.hasDeps || allDeps.length === 0) return null;
        return (
          <div className="card">
            <div className="card-title">Your dependants</div>
            <Callout kind="info">
              Pulled from the Personal section. If anything's wrong, head back to <strong>Personal</strong> to update - your adviser will discuss any cover for dependants with you at your meeting.
            </Callout>
            <div className="ff-deps-list">
              {allDeps.map((dep, i) => {
                const ageBits = [];
                if (dep.dob) {
                  const dob = new Date(dep.dob);
                  if (!isNaN(dob)) {
                    const years = Math.floor((Date.now() - dob) / (365.25 * 24 * 3600 * 1000));
                    if (years >= 0 && years < 120) ageBits.push(`${years} y/o`);
                  }
                }
                if (dep.relationship) ageBits.push(dep.relationship);
                return (
                  <div key={i} className="ff-deps-row">
                    <span className="ff-deps-name">{dep.name || `Dependant ${i+1}`}</span>
                    {ageBits.length > 0 && (
                      <span className="ff-deps-meta">{ageBits.join(' • ')}</span>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        );
      })()}

      {/* ═══════════════════════════════════════════════════════════
          14. GP / MEDICAL PRACTICE
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Your GP / medical practice</div>
        <Field label="Do you have a regular GP or medical practice?" required>
          <YesNo value={d.hasGp} onChange={v => update({ hasGp: v })} />
        </Field>
        {d.hasGp !== false && (
          <div className="grid-2">
            <Field label="GP name" required name="ins.gpName">
              <Input value={d.gpName || ''} onChange={e => update({ gpName: e.target.value })} />
            </Field>
            <Field label="Practice name" required name="ins.gpPractice">
              <Input value={d.gpPractice || ''} onChange={e => update({ gpPractice: e.target.value })} />
            </Field>
            <Field label="Practice address" span={2} required name="ins.gpAddress">
              <AddressInput value={d.gpAddress || ''} onChange={e => update({ gpAddress: e.target.value })}
                placeholder="Start typing - Australian suggestions will appear" />
            </Field>
            <Field label="Practice phone" hint="Optional - handy for our records but you can leave it blank.">
              <PhoneInput value={d.gpPhone || ''} onChange={e => update({ gpPhone: e.target.value })}
                placeholder="(02) 1234 5678" />
            </Field>
            <Field label="Last consultation" required name="ins.gpLastVisit"
              hint="When you most recently saw any doctor at this practice - for any reason.">
              <Select value={d.gpLastVisit || ''} onChange={e => update({ gpLastVisit: e.target.value })}>
                <option value="">Select…</option>
                <option>Less than 6 months ago</option>
                <option>6–12 months ago</option>
                <option>1–2 years ago</option>
                <option>2–5 years ago</option>
                <option>5+ years ago</option>
              </Select>
            </Field>
            <Field label="How long have you been with this practice?" required name="ins.gpYears"
              hint="If you've moved practices recently, use the new one's start date.">
              <Select value={d.gpYears || ''} onChange={e => update({ gpYears: e.target.value })}>
                <option value="">Select…</option>
                <option>Less than 6 months</option>
                <option>6–12 months</option>
                <option>1–2 years</option>
                <option>2–5 years</option>
                <option>5+ years</option>
              </Select>
            </Field>
          </div>
        )}
        {(d.hasGp === false || d.gpYears === 'Less than 6 months') && (
          <>
            <hr className="divider" />
            <SubSectionHeading>Previous GP / practice</SubSectionHeading>
            <div className="field-hint" style={{ marginBottom: 10 }}>
              {d.hasGp === false
                ? "If you don't have a regular GP, please add the details of the practice you've most recently attended."
                : "You've been with this practice less than 6 months - please add the details of the previous practice you attended."}
            </div>
            <div className="grid-2">
              <Field label="Previous GP name"><Input value={d.prevGpName || ''} onChange={e => update({ prevGpName: e.target.value })} /></Field>
              <Field label="Previous practice"><Input value={d.prevGpPractice || ''} onChange={e => update({ prevGpPractice: e.target.value })} /></Field>
              <Field label="Practice address" span={2}><Input value={d.prevGpAddress || ''} onChange={e => update({ prevGpAddress: e.target.value })} /></Field>
              <Field label="Practice phone"><Input type="tel" value={d.prevGpPhone || ''} onChange={e => update({ prevGpPhone: e.target.value })} /></Field>
            </div>
          </>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          14b. BANK / PAYMENT DETAILS
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Bank details for premium payments</div>
        <Callout kind="info">
          If your application is accepted, premiums will be debited from the account below. You can change or update these details with your adviser before any policy is set live.
        </Callout>
        <Field label="How would you like premiums paid?">
          <ChipGroup
            options={['Direct debit (bank account)', 'Credit card', 'Discuss with adviser']}
            value={d.paymentMethod}
            onChange={v => update({ paymentMethod: v })} />
        </Field>

        {d.paymentMethod === 'Direct debit (bank account)' && (
          <div className="grid-2">
            <Field label="Account name" span={2} required hint="Name as it appears on the account">
              <Input value={d.bankAccountName || ''} onChange={e => update({ bankAccountName: e.target.value })} />
            </Field>
            <Field label="Bank / institution" required>
              <Input value={d.bankName || ''} onChange={e => update({ bankName: e.target.value })} placeholder="e.g. Commonwealth Bank" />
            </Field>
            <Field label="BSB" required hint="6 digits">
              <Input value={d.bankBsb || ''} onChange={e => update({ bankBsb: e.target.value })}
                inputMode="numeric" maxLength="7" placeholder="000-000" />
            </Field>
            <Field label="Account number" required>
              <Input value={d.bankAccountNumber || ''} onChange={e => update({ bankAccountNumber: e.target.value })}
                inputMode="numeric" placeholder="9-digit account number" />
            </Field>
            <Field label="Payment frequency" required>
              <Select value={d.paymentFrequency || ''} onChange={e => update({ paymentFrequency: e.target.value })}>
                <option value="">Select…</option>
                <option>Monthly</option>
                <option>Quarterly</option>
                <option>Half-yearly</option>
                <option>Yearly</option>
              </Select>
            </Field>
          </div>
        )}

        {d.paymentMethod === 'Credit card' && (
          <Callout kind="info">
            For security, please <strong>don't enter your card number here.</strong> Your adviser will collect card details over a secure channel before any policy is set live.
          </Callout>
        )}
      </div>

      {/* ═══════════════════════════════════════════════════════════
          15. DUTY OF DISCLOSURE
          ═══════════════════════════════════════════════════════════ */}
      <div className="card">
        <div className="card-title">Final acknowledgement</div>
        <Callout kind="warn">
          <strong>Duty of disclosure.</strong> When applying for life insurance, you have a legal duty to take reasonable care not to make a misrepresentation. Answer every question truthfully, accurately, and completely. If you're unsure whether something is relevant, include it. Failure to disclose can result in a claim being declined or your cover being cancelled.
        </Callout>
        <Field label="I confirm I understand my duty of disclosure, and the answers I've provided are true, accurate and complete to the best of my knowledge." required>
          <YesNo value={d.declaration} onChange={v => update({ declaration: v })} yesLabel="I confirm" noLabel="Need to discuss with adviser" />
        </Field>
      </div>
    </div>
  );
}

Object.assign(window, { SectionInsurance });
