File size: 23,682 Bytes
dfca5e5
 
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
dfca5e5
 
 
cea694d
dfca5e5
 
 
cea694d
dfca5e5
 
 
cea694d
dfca5e5
 
cea694d
dfca5e5
 
 
 
cea694d
dfca5e5
 
 
cea694d
dfca5e5
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
 
dfca5e5
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
 
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cea694d
 
dfca5e5
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
cea694d
dfca5e5
 
 
 
cea694d
dfca5e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// src/lib/mechanics.js
// ============================================================================
// LEVEL EVOLUTION β€” MECHANICS ENGINE (Pure JavaScript ES Module)
// ============================================================================

// ─── composition ─────────────────────────────────────────────────
export const COMPOSITION_ORDER = [ 'ANIMALIA', 'CHITINARIA', 'PLANTAE', 'CNIDARIA', 'MYCELIUM', 'MINERALIS' ];

export const COMPOSITION_META = {
  ANIMALIA:  { label: 'Animalia',  blurb: 'Balanced baseline β€” no free strengths, no hard weaknesses.', accent: '#94a3b8', glow: '#64748b' },
  CHITINARIA:{ label: 'Chitinaria', blurb: 'Free ARMOR at β‰₯30%. Periodic molt window drops defense briefly.', freeStructure: 'ARMOR', accent: '#d97706', glow: '#f59e0b' },
  PLANTAE:   { label: 'Plantae',   blurb: 'Passive energy regen in light; free ACID resistance. Neural capped at 4.', accent: '#22c55e', glow: '#4ade80' },
  CNIDARIA:  { label: 'Cnidaria',  blurb: 'Free SOFT structure; toxin Features cost less. CONDUCTIVE β€” vulnerable to Electric.', freeStructure: 'SOFT', accent: '#06b6d4', glow: '#22d3ee' },
  MYCELIUM:  { label: 'Mycelium',  blurb: 'Free REGEN; halves DOT damage. Speed capped at 4. Fragile HP.', accent: '#a855f7', glow: '#c084fc' },
  MINERALIS: { label: 'Mineralis', blurb: 'Free BRITTLE; zero food need. Immune to TOXIN/ACID. Cannot regenerate.', freeStructure: 'BRITTLE', accent: '#e2e8f0', glow: '#f1f5f9' },
};

export function dominantComposition(c) {
  const e = COMPOSITION_ORDER.map(k => [k, c[k]]).filter(([, v]) => v >= 30).sort((a, b) => b[1] - a[1]);
  return e.length ? e[0][0] : null;
}

export function setCompositionLinked(comps, key, value) {
  const clamped = Math.max(0, Math.min(100, Math.round(value)));
  const others = COMPOSITION_ORDER.filter(k => k !== key);
  const oldSum = others.reduce((s, k) => s + comps[k], 0);
  const residual = 100 - clamped;
  const next = { ...comps, [key]: clamped };

  if (oldSum === 0) {
    const each = Math.floor(residual / others.length);
    others.forEach((k, i) => { next[k] = i === 0 ? residual - each * (others.length - 1) : each; });
  } else {
    let assigned = 0;
    others.forEach((k, i) => {
      const share = i === others.length - 1 ? residual - assigned : Math.round((comps[k] / oldSum) * residual);
      next[k] = Math.max(0, share);
      assigned += next[k];
    });
  }
  const total = COMPOSITION_ORDER.reduce((s, k) => s + next[k], 0);
  if (total !== 100) next[key] = Math.max(0, next[key] + (100 - total));
  return next;
}

// ─── attribute caps ─────────────────────────────────────────────
export function attributeCap(attr, comps) {
  const plant = comps.PLANTAE >= 30;
  const mycel = comps.MYCELIUM >= 30;
  const mineral = comps.MINERALIS >= 30;
  const chitin = comps.CHITINARIA >= 30;

  if (attr === 'NEURAL_COMPLEXITY') { if (plant) return 4; if (mycel) return 3; if (mineral) return 2; }
  if (attr === 'METABOLIC_RATE')    { if (mycel) return 4; if (mineral) return 0; }
  if (attr === 'REGENERATION')      { if (mineral) return 0; }
  if (attr === 'MUSCLE_DENSITY')    { if (mineral) return 2; }
  if (attr === 'BUOYANCY')          { if (mineral) return 1; }
  if (attr === 'WATER_RETENTION')   { if (chitin) return 6; }
  return 10;
}

// ─── features ────────────────────────────────────────────────────
export const FEATURE_META = [
  { type:'TOXIN_GLANDS', label:'Toxin Glands', category:'Offense', tags:['TOXIN'], baseCost:10, costMult:{CNIDARIA:0.5}, blurb:'DOT injection on hit. ARMOR resists; NUMB immune.' },
  { type:'PIERCING_MOUTHPARTS', label:'Piercing Mouthparts', category:'Offense', tags:['PIERCE'], baseCost:10, blurb:'Burst damage; bypasses between-fight REGEN. ARMOR resists.' },
  { type:'CRUSHING_MANDIBLES', label:'Crushing Mandibles', category:'Offense', tags:['CRUSH'], baseCost:10, blurb:'Bonus vs hard structures. SOFT absorbs; BRITTLE shatters (Γ—2.5).' },
  { type:'SLASHING_BLADES', label:'Slashing Blades', category:'Offense', tags:['SLASH'], baseCost:10, blurb:'Strong vs unarmored. ARMOR resists.' },
  { type:'ACID_SPRAY', label:'Acid Spray', category:'Offense', tags:['ACID'], baseCost:12, requires:{CNIDARIA:20}, blurb:'Ranged; ignores GRAPPLE range. REGEN out-heals; Mineralis immune.' },
  { type:'ELECTRIC_DISCHARGE', label:'Electric Discharge', category:'Offense', tags:['ELECTRIC'], baseCost:15, requires:{ANIMALIA:20}, blurb:'Ignores ARMOR. INSULATED resists; CONDUCTIVE extra-vulnerable.' },
  { type:'SONIC_SHRIEK', label:'Sonic Shriek', category:'Offense', tags:['SONIC'], baseCost:14, requires:{ANIMALIA:25}, blurb:'Ranged; uncounterable by Camouflage. Shatter (Γ—2.5) vs BRITTLE. SOFT absorbs.' },
  { type:'GRAPPLE_TENDRILS', label:'Grapple Tendrils', category:'Offense', tags:['GRAPPLE'], baseCost:11, requires:{CNIDARIA:20}, blurb:'Locks target; negates Speed evasion. ARMOR and SLIME slip free.' },
  { type:'SNAKE_FANGS', label:'Snake Fangs', category:'Offense', tags:['TOXIN','PIERCE'], baseCost:12, requires:{ANIMALIA:20}, blurb:'Toxin + pierce hybrid burst. Good vs most things except ARMOR.' },
  { type:'SCORPION_TAIL', label:'Scorpion Tail', category:'Offense', tags:['TOXIN','PIERCE'], baseCost:13, requires:{CHITINARIA:20}, blurb:'Stinger with toxin. Reaches over armor joints.' },
  { type:'BOMBADIER_SPRAY', label:'Bombardier Spray', category:'Offense', tags:['ACID'], baseCost:13, requires:{CHITINARIA:25}, blurb:'Boiling chemical acid. Bonus vs ARMOR; Mineralis immune.' },
  { type:'DESERT_WORM_MAW', label:'Desert Worm Maw', category:'Offense', tags:['CRUSH','PIERCE'], baseCost:14, requires:{ANIMALIA:30}, blurb:'Ring of inward-curling teeth. Crush+pierce; terrifying vs FLESH and SOFT.' },
  { type:'HARD_SHELL', label:'Hard Shell', category:'Defense', tags:[], baseCost:10, costMult:{CHITINARIA:0}, blurb:'Forces ARMOR. CRUSH and ACID are its weaknesses.' },
  { type:'GELATINOUS_BODY', label:'Gelatinous Body', category:'Defense', tags:[], baseCost:10, costMult:{CNIDARIA:0}, blurb:'Forces SOFT. Absorbs CRUSH/SONIC; PIERCE/SLASH/TOXIN punish it.' },
  { type:'SLIME_COATING', label:'Slime Coating', category:'Defense', tags:[], baseCost:8, requires:{CNIDARIA:15}, blurb:'SLIME modifier β€” escape chance vs GRAPPLE; small general dodge.' },
  { type:'DUST_COATING', label:'Dust Coating', category:'Defense', tags:[], baseCost:9, blurb:'One guaranteed dodge per encounter. Skipped if attacker out-speeds; cleared by SONIC/ACID.' },
  { type:'REGENERATIVE_FLESH', label:'Regenerative Flesh', category:'Defense', tags:[], baseCost:11, requires:{MYCELIUM:15}, blurb:'REGEN modifier β€” halves toxin/acid DOT. Useless vs single burst hits.' },
  { type:'BIOLUMINESCENT_DETERRENT', label:'Bioluminescent Deterrent', category:'Defense', tags:[], baseCost:9, requires:{CNIDARIA:20}, blurb:'Flinch chance to interrupt attacker. Ignored by high Neural Complexity.' },
  { type:'SPINY_RIDGE', label:'Spiny Ridge', category:'Defense', tags:[], baseCost:8, requires:{CHITINARIA:20}, blurb:'Reflects chunk of melee CRUSH/SLASH back. Piercing/ranged ignore it.' },
  { type:'CAMOUFLAGE_PATTERNS', label:'Camouflage Patterns', category:'Defense', tags:[], baseCost:9, blurb:'Shrinks detection radius; dodge chance vs low-Neural attackers. Costs offense.' },
  { type:'DRAGONFLY_WINGS', label:'Dragonfly Wings', category:'Mobility', tags:[], baseCost:15, requires:{ANIMALIA:30}, blurb:'AERIAL β€” immune to ground-only non-ranged attackers. Other fliers/ranged still hit.' },
  { type:'MOTH_DUST_WINGS', label:'Moth Dust Wings', category:'Mobility', tags:[], baseCost:14, requires:{ANIMALIA:25}, blurb:'AERIAL + dust evasion. Softer than dragonfly wings but harder to lock onto.' },
  { type:'BURROWING_CLAWS', label:'Burrowing Claws', category:'Mobility', tags:[], baseCost:10, blurb:'BURROWING β€” skip one encounter per phase. -Speed on open ground.' },
  { type:'WEBBED_LIMBS', label:'Webbed Limbs', category:'Mobility', tags:[], baseCost:8, blurb:'AQUATIC β€” +speed in water; -speed on land/desert.' },
  { type:'CILIA_PROPULSION', label:'Cilia Propulsion', category:'Mobility', tags:[], baseCost:6, requires:{CNIDARIA:20}, blurb:'AQUATIC-only microswimmer; useless on land.' },
  { type:'JET_PROPULSION', label:'Jet Propulsion', category:'Mobility', tags:[], baseCost:11, requires:{CNIDARIA:30}, blurb:'AQUATIC burst-dash; brief high-speed with cooldown.' },
  { type:'FLOWER_HEAD_LURE', label:'Flower Head Lure', category:'Sensory', tags:[], baseCost:10, requires:{PLANTAE:30}, blurb:'LURE β€” act first regardless of Speed, once per encounter. High-Neural attackers ignore it.' },
  { type:'ECHINATION_PALPS', label:'Echination Palps', category:'Sensory', tags:[], baseCost:7, blurb:'Sees through Camouflage; +1 effective Neural Complexity for detection only.' },
  { type:'THERMAL_PITS', label:'Thermal Pits', category:'Sensory', tags:[], baseCost:8, requires:{ANIMALIA:20}, blurb:'Detect warm-blooded prey in any visibility. Nullifies Camouflage vs warm targets.' },
  { type:'VOMERO_NASAL_ORGAN', label:'Vomero-Nasal Organ', category:'Sensory', tags:[], baseCost:7, requires:{ANIMALIA:15}, blurb:'Scent-tracking; +detection radius. Mating gas detection.' },
];

export const FEATURE_LOOKUP = Object.fromEntries(FEATURE_META.map(m => [m.type, m]));

export function featureGateReason(feat, comps) {
  const meta = FEATURE_LOOKUP[feat];
  if (!meta) return 'Unknown feature';
  if (meta.requires) {
    for (const [k, v] of Object.entries(meta.requires)) {
      if ((comps[k] ?? 0) < v) return `Requires ${k} β‰₯ ${v}`;
    }
  }
  if (meta.forbids) {
    for (const [k, v] of Object.entries(meta.forbids)) {
      if ((comps[k] ?? 0) >= v) return `Forbidden by ${k} β‰₯ ${v}`;
    }
  }
  return null;
}

export function featureCost(feat, comps) {
  const meta = FEATURE_LOOKUP[feat];
  let cost = meta.baseCost;
  if (meta.costMult) {
    for (const [k, mult] of Object.entries(meta.costMult)) {
      if ((comps[k] ?? 0) >= 30) cost *= mult;
    }
  }
  return Math.round(cost);
}

// ─── structural type & modifiers ────────────────────────────────
export function determineStructuralType(state) {
  if (state.features.includes('HARD_SHELL')) return 'ARMOR';
  if (state.features.includes('GELATINOUS_BODY')) return 'SOFT';
  const dom = dominantComposition(state.compositions);
  if (dom) {
    const free = COMPOSITION_META[dom].freeStructure;
    if (free) return free;
  }
  return 'FLESH';
}

export function activeModifiers(state) {
  const mods = new Set();
  if (state.attributes.TOXIN_RESISTANCE >= 5) mods.add('NUMB');
  if (state.attributes.INSULATION >= 5) mods.add('INSULATED');
  if (state.compositions.CNIDARIA >= 30) mods.add('CONDUCTIVE');
  if (state.compositions.MYCELIUM >= 30 || state.features.includes('REGENERATIVE_FLESH')) mods.add('REGEN');
  if (state.features.includes('SLIME_COATING')) mods.add('SLIME');
  if (state.features.includes('DRAGONFLY_WINGS') || state.features.includes('MOTH_DUST_WINGS')) mods.add('AERIAL');
  if (state.features.includes('BURROWING_CLAWS')) mods.add('BURROWING');
  if (state.features.includes('WEBBED_LIMBS') || state.features.includes('CILIA_PROPULSION') || state.features.includes('JET_PROPULSION')) mods.add('AQUATIC');
  if (state.features.includes('FLOWER_HEAD_LURE')) mods.add('LURE');
  return mods;
}

// ─── evolution points ───────────────────────────────────────────
export function getEvolutionPoints(state) {
  let used = 0;
  for (const [attrStr, val] of Object.entries(state.attributes)) {
    const attr = attrStr;
    const cap = attributeCap(attr, state.compositions);
    const effectiveVal = Math.min(val, cap);
    let costMult = 1;
    if (state.compositions.PLANTAE >= 30 && attr === 'REGENERATION') costMult = 0.5;
    if (state.compositions.MINERALIS >= 30 && attr === 'BONE_DENSITY') costMult = 0.5;
    if (state.compositions.CHITINARIA >= 30 && attr === 'WATER_RETENTION') costMult = 0.8;
    if (state.compositions.ANIMALIA >= 30 && attr === 'NEURAL_COMPLEXITY') costMult = 0.8;
    if (state.compositions.CNIDARIA >= 30 && attr === 'BUOYANCY') costMult = 0.5;
    if (state.compositions.MYCELIUM >= 30 && attr === 'REGENERATION') costMult = 0.5;
    used += effectiveVal * 2 * costMult;
  }
  for (const f of state.features) { used += featureCost(f, state.compositions); }
  let max = 100;
  const dom = dominantComposition(state.compositions);
  if (dom) max += Math.round((state.compositions[dom] - 30) * 0.5);
  return { used: Math.round(used), max };
}

// ─── derived stats β€” with environment effects ─────────────────
export function getDerivedStats(state, biome) {
  let offense = 10, defense = 10, speed = 20, hp = 100;
  let weight = 20, energyDemand = 10, detection = 80, matingSpeed = 1.0;
  let desiccationRate = 1.0, heatTolerance = 50, coldTolerance = 50;

  const A = state.attributes;
  offense += A.MUSCLE_DENSITY * 2;
  weight += A.MUSCLE_DENSITY * 2;
  energyDemand += A.MUSCLE_DENSITY * 1.5;

  defense += A.BONE_DENSITY * 2;
  weight += A.BONE_DENSITY * 2.5;
  speed -= A.BONE_DENSITY * 1.5;

  speed += A.METABOLIC_RATE * 2;
  energyDemand += A.METABOLIC_RATE * 2;
  heatTolerance += A.METABOLIC_RATE * 3;

  hp += A.FAT_RESERVES * 5;
  weight += A.FAT_RESERVES * 1.5;
  speed -= A.FAT_RESERVES * 0.5;

  energyDemand += A.NEURAL_COMPLEXITY * 1.5;
  matingSpeed -= A.NEURAL_COMPLEXITY * 0.04;
  detection += A.NEURAL_COMPLEXITY * 6;

  energyDemand += A.REGENERATION * 2;
  hp -= A.REGENERATION * 1;

  coldTolerance += A.INSULATION * 5;
  heatTolerance -= A.INSULATION * 2;
  energyDemand += A.INSULATION;
  speed -= A.INSULATION * 0.3;

  weight += A.WATER_RETENTION * 0.5;
  speed -= A.WATER_RETENTION * 0.2;
  desiccationRate -= A.WATER_RETENTION * 0.08;

  energyDemand += A.THERMAL_REGULATION * 0.8;
  heatTolerance += A.THERMAL_REGULATION * 3;
  coldTolerance += A.THERMAL_REGULATION * 3;

  offense -= A.CAMOUFLAGE * 0.5;
  detection -= A.CAMOUFLAGE * 4;
  defense -= A.BUOYANCY * 0.4;

  // composition
  if (state.compositions.PLANTAE >= 30) hp += 20;
  if (state.compositions.MYCELIUM >= 30) { hp -= 10; matingSpeed += 0.5; }
  if (state.compositions.MINERALIS >= 30) { energyDemand = 0; weight += 30; speed -= 10; }

  const mods = activeModifiers(state);
  const isAerial = mods.has('AERIAL');
  const isAquatic = mods.has('AQUATIC');

  // biome effects
  if (biome === 'UNDERWATER') {
    speed += A.BUOYANCY * 2;
    if (isAquatic) speed += 15;
    if (isAerial) speed -= 15;
    if (!isAquatic && state.compositions.CNIDARIA < 30 && A.BUOYANCY < 3) { hp -= 30; desiccationRate += 2; }
    coldTolerance += 10;
  } else {
    if (isAquatic && !isAerial) speed -= 5;
    if (isAerial) speed += 10;
    if (biome === 'DESERT') {
      if (A.WATER_RETENTION < 5) hp -= 20;
      if (mods.has('SLIME')) { hp -= 15; desiccationRate += 0.5; }
      if (state.compositions.CNIDARIA >= 30 && A.WATER_RETENTION < 5) { hp -= 40; desiccationRate += 1; }
      heatTolerance += 10; coldTolerance -= 20;
    }
    if (biome === 'RAINFOREST') {
      if (state.compositions.PLANTAE >= 30) hp += 20;
      coldTolerance += 5;
    }
  }

  if (weight > 50) {
    speed -= (weight - 50) * 0.5;
    energyDemand += (weight - 50) * 0.5;
  }

  const struct = determineStructuralType(state);
  if (struct === 'ARMOR') { defense += 25; weight += 15; matingSpeed -= 0.1; }
  if (struct === 'SOFT') { hp += 20; defense -= 5; }
  if (struct === 'BRITTLE') { defense += 30; hp -= 10; }

  if (energyDemand > 40 && state.compositions.PLANTAE < 30) {
    hp -= (energyDemand - 40) * 2;
  }

  return {
    offense: Math.round(offense), defense: Math.round(defense),
    speed: Math.max(2, Math.round(speed)),
    hp: Math.max(1, Math.round(hp)), weight: Math.round(weight),
    energyDemand: Math.round(energyDemand), detection: Math.max(20, Math.round(detection)),
    matingSpeed: Math.max(0.1, Math.round(matingSpeed * 100) / 100),
    aquatic: isAquatic, aerial: isAerial,
    desiccationRate: Math.max(0, Math.round(desiccationRate * 100) / 100),
    heatTolerance: Math.round(heatTolerance), coldTolerance: Math.round(coldTolerance),
  };
}

// ─── counter chart ──────────────────────────────────────────────
const COUNTER_CHART = {
  TOXIN:    { ARMOR: 0.4, SOFT: 1.6, BRITTLE: 1.0, FLESH: 1.0 },
  PIERCE:   { ARMOR: 0.4, SOFT: 1.6, BRITTLE: 1.0, FLESH: 1.0 },
  CRUSH:    { ARMOR: 1.6, SOFT: 0.4, BRITTLE: 2.5, FLESH: 1.0 },
  SLASH:    { ARMOR: 0.4, SOFT: 1.6, BRITTLE: 1.0, FLESH: 1.0 },
  ACID:     { ARMOR: 1.6, SOFT: 1.0, BRITTLE: 1.0, FLESH: 1.0 },
  ELECTRIC: { ARMOR: 1.0, SOFT: 1.0, BRITTLE: 1.0, FLESH: 1.0 },
  SONIC:    { ARMOR: 1.0, SOFT: 0.4, BRITTLE: 2.5, FLESH: 1.0 },
  GRAPPLE:  { ARMOR: 0.4, SOFT: 1.0, BRITTLE: 0.4, FLESH: 1.6 },
};

// ─── combat resolution ─────────────────────────────────────────
export function resolveCombat(attacker, defender, biome, rng = Math.random) {
  const att = getDerivedStats(attacker, biome);
  const def = getDerivedStats(defender, biome);
  const defStruct = determineStructuralType(defender);
  const defMods = activeModifiers(defender);
  const attMods = activeModifiers(attacker);
  const notes = [];

  let attackerFirst = true;
  if (defMods.has('LURE') && attacker.attributes.NEURAL_COMPLEXITY < 5) {
    attackerFirst = false; notes.push('Defender LURE overrides Speed');
  } else if (def.speed > att.speed) {
    attackerFirst = false;
  }

  const speedDiff = def.speed - att.speed;
  let evasionChance = Math.max(0, Math.min(0.35, speedDiff / 40));
  const attIsGroundOnly = !attMods.has('AERIAL');
  const attHasRanged = attacker.features.some(f => {
    const t = FEATURE_LOOKUP[f]?.tags ?? [];
    return t.includes('SONIC') || t.includes('ACID') || t.includes('GRAPPLE');
  });

  if (defMods.has('AERIAL') && attIsGroundOnly && !attHasRanged) {
    evasionChance = 1.0; notes.push('Defender AERIAL β€” ground attacker cannot reach');
  }
  if (defender.features.includes('DUST_COATING') && speedDiff > -10) {
    evasionChance = Math.max(evasionChance, 0.9); notes.push('Dust coating pre-deployed');
  } else if (defender.features.includes('DUST_COATING')) {
    notes.push('Dust coating skipped β€” attacker too fast');
  }

  const evaded = rng() < evasionChance;
  if (evaded) {
    return {
      won: false,
      breakdown: {
        attackerFirst, evasionChance, evaded,
        effectiveOffense: 0, effectiveDefense: 0,
        winProbability: 0, roll: 0, attackerWon: false,
        tagsUsed: [], notes: [...notes, 'Evaded before contact'],
        primaryTag: null, isShatter: false
      },
    };
  }

  const tagsUsed = [];
  for (const f of attacker.features) {
    const meta = FEATURE_LOOKUP[f];
    if (meta?.tags.length) tagsUsed.push(...meta.tags);
  }
  const uniqueTags = Array.from(new Set(tagsUsed));

  let bestEffOffense = att.offense;
  let bestTag = null;
  let bestMult = 1;

  for (const tag of uniqueTags) {
    let mult = COUNTER_CHART[tag][defStruct];
    if (tag === 'TOXIN') {
      if (defender.compositions.MINERALIS >= 30) { mult = 0; notes.push('Mineralis immune to Toxin'); }
      else if (defMods.has('NUMB')) { mult = 0; notes.push('Defender NUMB β€” Toxin negated'); }
      else if (defMods.has('REGEN')) { mult *= 0.5; notes.push('Defender REGEN halves Toxin'); }
    }
    if (tag === 'ELECTRIC') {
      if (defMods.has('INSULATED')) { mult *= 0.4; notes.push('Defender INSULATED resists Electric'); }
      else if (defMods.has('CONDUCTIVE')) { mult *= 1.6; notes.push('Defender CONDUCTIVE vulnerable to Electric'); }
    }
    if (tag === 'ACID') {
      if (defender.compositions.MINERALIS >= 30) { mult = 0; notes.push('Mineralis immune to Acid'); }
      else if (defMods.has('REGEN')) { mult *= 0.5; notes.push('REGEN out-heals Acid'); }
    }
    if (tag === 'GRAPPLE') {
      if (defMods.has('SLIME')) { mult *= 0.4; notes.push('Defender SLIME slips Grapple'); }
    }
    const eff = att.offense * mult;
    if (eff > bestEffOffense) { bestEffOffense = eff; bestTag = tag; bestMult = mult; }
  }
  if (bestTag) notes.push(`Best attack tag: ${bestTag} (Γ—${bestMult.toFixed(2)})`);
  else notes.push('No offensive tags β€” bare-body clash');

  let effDefense = def.defense;
  if (bestTag === 'ELECTRIC' && !defMods.has('INSULATED') && defStruct === 'ARMOR') {
    effDefense = Math.max(0, effDefense - 25); notes.push('Electric ignores ARMOR bonus');
  }
  if (defender.features.includes('SPINY_RIDGE') && (bestTag === 'CRUSH' || bestTag === 'SLASH')) {
    bestEffOffense *= 0.7; notes.push('Spiny Ridge reflects 30% melee');
  }
  if (defender.features.includes('BIOLUMINESCENT_DETERRENT') && attacker.attributes.NEURAL_COMPLEXITY < 5 && rng() < 0.3) {
    bestEffOffense *= 0.4; notes.push('Bioluminescent flinch interrupted attack');
  }

  const winProbability = bestEffOffense / (bestEffOffense + effDefense || 1);
  const roll = rng();
  const attackerWon = attackerFirst ? roll < winProbability : roll < winProbability * 0.85;

  const isShatter = bestTag !== null && bestMult >= 2.0 && defStruct === 'BRITTLE';

  return {
    won: attackerWon,
    breakdown: {
      attackerFirst, evasionChance, evaded,
      effectiveOffense: Math.round(bestEffOffense),
      effectiveDefense: Math.round(effDefense),
      winProbability: Math.round(winProbability * 1000) / 1000,
      roll: Math.round(roll * 1000) / 1000, attackerWon, tagsUsed: uniqueTags, notes,
      primaryTag: bestTag, isShatter
    },
  };
}

// ─── breeding ───────────────────────────────────────────────────
export function breedOffspring(a, b) {
  const mix = (x, y) => Math.round(((x + y) / 2) * 0.85);
  const avgComp = {};
  for (const k of COMPOSITION_ORDER) avgComp[k] = mix(a.compositions[k], b.compositions[k]);

  const sum = COMPOSITION_ORDER.reduce((s, k) => s + avgComp[k], 0);
  if (sum > 0) for (const k of COMPOSITION_ORDER) avgComp[k] = Math.round((avgComp[k] / sum) * 100);
  const total = COMPOSITION_ORDER.reduce((s, k) => s + avgComp[k], 0);
  if (total !== 100) avgComp.ANIMALIA = Math.max(0, avgComp.ANIMALIA + (100 - total));

  return {
    compositions: avgComp,
    attributes: Object.fromEntries(
      Object.keys(a.attributes).map(k => [k, mix(a.attributes[k], b.attributes[k])])
    ),
    features: a.features.length >= b.features.length ? a.features.slice() : b.features.slice(),
    socialType: a.socialType,
  };
}

// ─── initial state ──────────────────────────────────────────────
export const INITIAL_STATE = {
  compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
  attributes: {
    WATER_RETENTION: 0, INSULATION: 0, MUSCLE_DENSITY: 0, BONE_DENSITY: 0,
    FAT_RESERVES: 0, METABOLIC_RATE: 0, NEURAL_COMPLEXITY: 0, THERMAL_REGULATION: 0,
    BUOYANCY: 0, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 0,
  },
  features: [],
  socialType: 'SOLITARY',
};