// species-data.jsx — care intelligence library

// Difficulty: 1 (easy) → 5 (expert). Honest ratings, not "everything is easy."
// Each species has: difficulty, lifespan, needs[], mistakes[], headsup, level
// Keyed by lowercase species name (matches PET_LIBRARY / PLANT_LIBRARY .lbl)

const SPECIES_CARE = {
  // ── ANIMALS ─────────────────────────────────────────────────────────
  'cat': {
    kind: 'pet', difficulty: 2, lifespan: '12–18 years',
    level: 'A good first pet for adults — independent but bonded',
    weightRange: { lo: 3.5, hi: 5.5, unit: 'kg', freq: 'monthly',
                   note: 'Range is breed-dependent — your vet sets the personal target.' },
    tips: [
      'A slow blink from a cat is a kiss — try slow-blinking back.',
      'Cats have around 100 vocalisations. Most are only ever directed at humans.',
      'A cat\'s purr is between 25–150 Hz — a range that promotes bone healing.',
    ],
    needs: [
      'Litter box scooped daily, fully changed weekly',
      'Fresh water always — many cats prefer flowing water',
      'Play 10–15 min twice a day (predatory behaviour = mental health)',
      'Annual vet visit, dental check by age 7',
    ],
    mistakes: [
      'Free-feeding dry only — obesity and dental disease',
      'Single-cat households with no enrichment',
      'Declawing — it amputates the last knuckle of each toe',
    ],
    headsup: 'They will knock things off tables to study gravity. This is research.',
  },
  'dog': {
    kind: 'pet', difficulty: 3, lifespan: '10–15 years (varies by breed)',
    level: 'Demanding daily — but the relationship is unmatched',
    weightRange: { freq: 'monthly',
                   note: 'Set the personal target with your vet — breeds vary tenfold.' },
    tips: [
      'Tail wag direction matters: right-side wag = relaxed, left-side = anxious.',
      'Dogs read your face about every 30 seconds when off-leash. They\'re checking on you.',
      'A 20-minute sniff walk is more tiring than a 1-hour brisk one.',
    ],
    needs: [
      '1–2 hrs exercise daily, more for working breeds',
      'Mental stimulation: training, sniff-walks, chew toys',
      'Consistent meal & potty schedule',
      'Vet annually + dental cleanings',
    ],
    mistakes: [
      'Walking the same route every day — sniff is everything',
      'Punishing fear with pressure',
      'Skipping bite-inhibition training as puppies',
    ],
    headsup: 'They\'ll bring you their toy when you\'re sad. You won\'t deserve it.',
  },
  'guinea pig': {
    kind: 'pet', difficulty: 3, lifespan: '5–7 years',
    level: 'Underrated complexity — herd animals with specific diets',
    weightRange: { lo: 0.9, hi: 1.2, unit: 'kg', freq: 'weekly',
                   note: 'Guinea pigs hide illness. Weekly weight is the most reliable early warning — a 30 g loss matters.' },
    tips: [
      'They can\'t make their own vitamin C — like humans. Daily greens are non-negotiable.',
      '"Popcorning" — jumping straight up in joy — is unique to guinea pigs. It means thriving.',
      'They recognise their humans by footsteps and start wheeking before you reach the room.',
    ],
    needs: [
      'Unlimited timothy hay (teeth grow forever)',
      'Daily vitamin C — bell pepper is gold',
      'A bonded friend — solo housing is increasingly considered neglect',
      'Floor pen, 7.5 sq ft minimum for a pair',
    ],
    mistakes: [
      'Cedar / pine bedding — respiratory toxic',
      'Iceberg lettuce — no nutrition',
      'Solo housing — they get visibly depressed',
    ],
    headsup: 'They wheek loudly when the fridge opens. Forever.',
  },
  'rabbit': {
    kind: 'pet', difficulty: 4, lifespan: '8–12 years',
    level: 'Often the most misunderstood pet — not a cage animal',
    tips: [
      'A relaxed rabbit "flops" sideways like she\'s been shot. This is contentment.',
      'They binky — a mid-air twist of joy — when running freely.',
      'Rabbits are crepuscular: most active at dawn and dusk, asleep midday.',
    ],
    needs: [
      'Free-roam or x-pen, not a small hutch',
      'Unlimited hay (80% of diet)',
      'A bonded partner — pairs are happier',
      'Rabbit-proofed wires & baseboards — they chew everything',
    ],
    mistakes: [
      'Muesli/pellet-heavy diet — causes dental disease',
      'Picking up by the scruff — terrifying for them',
      'Outdoor hutches in summer — heatstroke risk',
    ],
    headsup: 'A relaxed rabbit flops sideways like she\'s been shot. This is contentment.',
  },
  'hamster': {
    kind: 'pet', difficulty: 2, lifespan: '2–3 years',
    level: 'Beginner-friendly but solitary and short-lived',
    weightRange: { lo: 0.085, hi: 0.175, unit: 'kg', freq: 'weekly',
                   note: 'Syrians: 120–175g. Dwarfs: 30–60g. Weight loss is often the first sign of dental or respiratory illness.' },
    needs: [
      'Bin cage or 450+ sq inch tank — wire cages are too small',
      'Deep substrate (15+ cm) to burrow',
      'Silent wheel, 28+ cm for Syrians',
      'Strict solitary housing — they fight to the death',
    ],
    mistakes: [
      'Brightly-coloured tube habitats — too small for adults',
      'Waking them in the day — leads to stress and biting',
      'Pairing them — almost always ends badly',
    ],
    headsup: 'You\'ll hear them at 2am stuffing seeds into their cheeks.',
  },
  'rat': {
    kind: 'pet', difficulty: 3, lifespan: '2–3 years',
    level: 'Astonishingly social — get two or more, always',
    weightRange: { lo: 0.25, hi: 0.5, unit: 'kg', freq: 'weekly',
                   note: 'Males 450–650g, females 250–450g. Weight loss can mean tumours — get vet attention quickly.' },
    needs: [
      'Pairs/groups — solitary rats become withdrawn',
      'Multi-level cage with bar spacing under 1 cm',
      '1+ hour out-of-cage time daily',
      'Lab-block diet + fresh veg, low fat',
    ],
    mistakes: [
      'Single rat housing — cruel',
      'Cedar bedding — respiratory damage',
      'Ignoring tumours/respiratory signs — they hide illness',
    ],
    headsup: 'They\'ll recognise their names and come when called.',
  },
  'chinchilla': {
    kind: 'pet', difficulty: 4, lifespan: '15–20 years',
    level: 'Long commitment — fragile, sensitive to heat',
    weightRange: { lo: 0.4, hi: 0.6, unit: 'kg', freq: 'weekly',
                   note: 'They live 15–20 years — sudden weight changes are always worth a vet visit.' },
    needs: [
      'Room temp under 24°C / 75°F always — they overheat fast',
      'Dust baths 2–3× weekly (never water)',
      'Big multi-level cage with safe wood ledges',
      'Hay + chinchilla pellets only — most treats are too rich',
    ],
    mistakes: [
      'Wooden ledges of cedar, pine, plywood — toxic',
      'Sugary treats (raisins, fruit) — diabetic risk',
      'Handling roughly — fur slips out as a defence',
    ],
    headsup: 'Their fur is so dense fleas can\'t live in it.',
  },
  'hedgehog': {
    kind: 'pet', difficulty: 4, lifespan: '3–6 years',
    level: 'Exotic — check local laws first, many places ban them',
    weightRange: { lo: 0.25, hi: 0.6, unit: 'kg', freq: 'weekly',
                   note: 'Weight loss is often the first sign of WHS (wobbly hedgehog syndrome) or fatty liver — track it weekly.' },
    needs: [
      'Constant 23–26°C / 73–79°F — drops cause hibernation attempts',
      'Solitary housing — no exceptions',
      'Solid-bottom large cage, no wire mesh',
      'High-protein insectivore diet',
    ],
    mistakes: [
      'Treating like a hamster — totally different needs',
      'Room temps under 21°C — life-threatening torpor',
      'Wheel with bars — feet & legs catch and break',
    ],
    headsup: 'When startled, they self-anoint with foam they make in their mouth. It is bizarre.',
  },
  'bird': {
    kind: 'pet', difficulty: 3, lifespan: '5–15 years (small species)',
    level: 'Social, vocal, intelligent — not a passive pet',
    needs: [
      'Out-of-cage time daily, social interaction',
      'Wide flight cage, never round',
      'Varied diet — seed only causes deficiency',
      'Foraging toys & enrichment',
    ],
    mistakes: [
      'All-seed diet — fatty liver disease',
      'Teflon/non-stick pans nearby — fumes are fatal',
      'Single bird with no human time — feather plucking',
    ],
    headsup: 'They form deep one-person bonds — and grieve loudly when you leave the room.',
  },
  'parrot': {
    kind: 'pet', difficulty: 5, lifespan: '20–80 years',
    level: 'Lifetime commitment — many outlive their owners',
    needs: [
      'Hours of daily interaction',
      'Pelleted diet + fresh veg, limited seed',
      'Loud calls accepted as part of life',
      'Enrichment puzzles — boredom = self-harm',
    ],
    mistakes: [
      'Wing clipping as default — controversial, removes their language',
      'Punishing screaming — usually means a need is unmet',
      'Underestimating noise — neighbours and partners may not cope',
    ],
    headsup: 'A bored parrot will scream the alphabet at 6am. Don\'t buy on impulse.',
  },
  'fish': {
    kind: 'pet', difficulty: 3, lifespan: '2–5 years (betta), longer for many',
    level: 'Easy to keep alive, hard to keep thriving',
    tips: [
      'A happy betta builds a bubble nest at the surface. Don\'t pop it.',
      'They can recognise their human and follow your finger at the glass.',
      'Fish sleep — some even change colour to camouflage while they do.',
    ],
    needs: [
      'Minimum 10L / 2.5 gal for a betta — never a bowl',
      'Heater + gentle filter, cycled tank',
      'Weekly 25% water change with conditioner',
      'Live or silk plants — plastic shreds fins',
    ],
    mistakes: [
      'Unfiltered bowls — ammonia builds up',
      'Putting them with goldfish or aggressive tank mates',
      'Tap water without dechlorinator',
    ],
    headsup: 'A happy betta builds bubble nests at the surface. Don\'t pop them.',
  },
  'turtle': {
    kind: 'pet', difficulty: 4, lifespan: '20–50+ years',
    level: 'Aquatic turtles are full aquarium projects',
    needs: [
      'Tank at least 10× shell length',
      'UVB light + basking heat lamp, replaced every 6 months',
      'Powerful filter + weekly water changes',
      'Varied protein + leafy greens',
    ],
    mistakes: [
      'Tiny "turtle starter" tanks — they outgrow in months',
      'Missing UVB — shell deformities (MBD)',
      'Releasing into the wild — illegal in most places, devastates ecosystems',
    ],
    headsup: 'They live for decades. Make sure your 70-year-old self also wants this.',
  },
  'lizard': {
    kind: 'pet', difficulty: 4, lifespan: '5–20 years (varies)',
    level: 'Setup is everything — heat, light, prey, all dialled in',
    needs: [
      'Species-specific temperature gradient',
      'UVB lighting on a cycle',
      'Live prey for many species',
      'Hides on both warm + cool sides',
    ],
    mistakes: [
      'Hot rocks — burn injuries are common',
      'Crickets left in overnight — they bite the lizard',
      'Stress from over-handling juveniles',
    ],
    headsup: 'Each species is its own world. Research the specific one before buying.',
  },
  'snake': {
    kind: 'pet', difficulty: 3, lifespan: '10–30 years',
    level: 'Low-maintenance once the enclosure is right',
    needs: [
      'Properly sized vivarium with hot + cool sides',
      'Frozen-thawed prey (safer than live)',
      'Secure lid — they will find any gap',
      'Hides and clutter so they feel safe',
    ],
    mistakes: [
      'Handling within 48h of feeding — regurgitation risk',
      'Heat mats without thermostats — burns',
      'Water bowls too small to soak in',
    ],
    headsup: 'They will escape. Plan for it.',
  },
  'frog': {
    kind: 'pet', difficulty: 4, lifespan: '5–15 years',
    level: 'Humidity-sensitive — small mistakes are visible fast',
    needs: [
      'High humidity (60–90% depending on species)',
      'Dechlorinated water — they breathe through skin',
      'Live insects, gut-loaded',
      'Tight-fitting mesh lid',
    ],
    mistakes: [
      'Handling with bare hands — skin oils damage them',
      'Tap water — chlorine is lethal',
      'Co-housing different species — disease and predation',
    ],
    headsup: 'A frog with dry skin is a frog in trouble. Look closely.',
  },
  'invertebrate': {
    kind: 'pet', difficulty: 3, lifespan: 'varies wildly',
    level: 'Beautifully strange — but \'invertebrate\' covers many worlds',
    needs: [
      'Species-specific humidity & temp',
      'Substrate matched to natural habitat',
      'Specific prey or plant matter',
      'Patience — many move very slowly',
    ],
    mistakes: [
      'Generic exotic care — every species differs hugely',
      'Handling in shedding/moulting periods',
      'Mixing tarantulas — they\'re cannibals',
    ],
    headsup: 'A tarantula on her back is moulting, not dying. Do not flip her.',
  },

  // ── PLANTS ──────────────────────────────────────────────────────────
  'monstera': {
    kind: 'plant', difficulty: 2, lifespan: '20+ years indoors',
    level: 'Forgiving — perfect first leafy plant',
    tips: [
      'Splits and holes only appear on mature leaves with enough light. Patience.',
      'Aerial roots aren\'t a sign of disease — they want a moss pole to climb.',
      'In Mexican rainforests they grow 20m tall on trees. Yours is a baby.',
    ],
    needs: [
      'Bright indirect light — not full sun',
      'Water when top 5 cm of soil is dry, usually weekly',
      'Chunky aroid mix with bark + perlite',
      'Moss pole as it climbs (it\'s a climber in the wild)',
    ],
    mistakes: [
      'Tiny pot — roots want to spread, leaves want to fenestrate',
      'Wet feet — soggy soil rots the rhizome',
      'No moss pole — sad small leaves forever',
    ],
    headsup: 'Splits appear on mature leaves only — give her time and light.',
  },
  'fern': {
    kind: 'plant', difficulty: 4, lifespan: 'years with care',
    level: 'Drama queens of the houseplant world',
    tips: [
      'The brown dots underneath fronds aren\'t pests — they\'re spore cases.',
      'Ferns are among the oldest plant lineages — they predate flowers by 200 million years.',
      'A crispy fern often recovers if you trim back hard and reset humidity.',
    ],
    needs: [
      'High humidity (60%+) — bathrooms thrive',
      'Consistently moist soil, never bone dry',
      'Bright indirect light, no direct sun',
      'Distilled or rain water — they hate chlorine',
    ],
    mistakes: [
      'Letting them dry out once — they crisp dramatically',
      'Tap water with hard minerals',
      'Direct afternoon sun — instant fry',
    ],
    headsup: 'A crispy fern often recovers if you trim back and start the humidity fresh.',
  },
  'snake plant': {
    kind: 'plant', difficulty: 1, lifespan: 'decades',
    level: 'Almost unkillable — perfect first plant',
    tips: [
      'NASA studied them as air purifiers. They quietly clean while you sleep.',
      'Unlike most plants, they release oxygen at night — good bedroom companions.',
      'When in doubt, don\'t water. Underwatering rarely kills them.',
    ],
    needs: [
      'Bright indirect → low light, both work',
      'Water once every 2–4 weeks',
      'Well-draining soil — cactus mix or add perlite',
      'Pot with drainage holes (always)',
    ],
    mistakes: [
      'Overwatering — the #1 cause of death',
      'Wet leaves left to sit — rot starts at the base',
      'Tiny pots forever — they like to be slightly root-bound but not strangled',
    ],
    headsup: 'When in doubt, don\'t water. Underwatering rarely kills snake plants.',
  },
  'pothos': {
    kind: 'plant', difficulty: 1, lifespan: 'years',
    level: 'The plant that started everyone\'s collection',
    tips: [
      'Cuttings root in a glass of water in a week. Share with friends.',
      'In the wild they climb 20m up trees and their leaves grow huge.',
      'They thrive on neglect more than fussing.',
    ],
    needs: [
      'Any light from bright indirect to medium',
      'Water when top inch is dry',
      'Average potting mix',
      'Pinch back to encourage bushiness',
    ],
    mistakes: [
      'Letting vines get leggy without pruning',
      'Watering on a schedule instead of checking soil',
    ],
    headsup: 'Cuttings root in a glass of water in a week. Share with friends.',
  },
  'cactus': {
    kind: 'plant', difficulty: 2, lifespan: 'decades',
    level: 'Forgiving as long as you respect the season',
    needs: [
      'Full bright sun — south-facing windows',
      'Water deeply, then leave dry for weeks',
      'Cactus + grit soil mix',
      'Almost no water in winter dormancy',
    ],
    mistakes: [
      'Winter watering — they\'re asleep, the water rots them',
      'Pebble-only top dressing trapping moisture',
      'Tiny pots without drainage',
    ],
    headsup: 'A wrinkly cactus is thirsty. A mushy one is too late.',
  },
  'fiddle leaf': {
    kind: 'plant', difficulty: 4, lifespan: 'years with effort',
    level: 'The friend who needs a lot of attention',
    needs: [
      'One bright spot — never move them',
      'Consistent watering schedule',
      'Wipe leaves monthly — dust dims them',
      'Stable temperature, no draughts',
    ],
    mistakes: [
      'Moving the pot — they sulk and drop leaves',
      'Watering when soil is still moist',
      'Window draughts in winter',
    ],
    headsup: 'They drop leaves the way other plants change colour. Don\'t panic the first time.',
  },
  'peace lily': {
    kind: 'plant', difficulty: 2, lifespan: 'years',
    level: 'Forgiving — and dramatic about it',
    needs: [
      'Medium to low light',
      'Water when leaves droop (or weekly)',
      'Average potting mix',
      'Wipe leaves monthly for shine',
    ],
    mistakes: [
      'Direct sun — leaves scorch',
      'Tap water with fluoride — brown leaf tips',
    ],
    headsup: 'They wilt completely, then bounce back in an hour after water. Showy.',
  },
  'orchid': {
    kind: 'plant', difficulty: 4, lifespan: 'years',
    level: 'Intimidating reputation, often easier than it looks',
    needs: [
      'Bright indirect light, east window ideal',
      'Soak roots for 15 min weekly, then dry',
      'Orchid bark, not soil',
      'Clear pot so roots can photosynthesise',
    ],
    mistakes: [
      'Ice cubes as water — slow shock',
      'Cutting the spike too early after blooms',
      'Potting in soil — roots need air',
    ],
    headsup: 'Roots should be silvery-green between waterings. Mushy means too wet.',
  },
  'palm': {
    kind: 'plant', difficulty: 3, lifespan: 'years',
    level: 'Loves humidity — sulks in dry rooms',
    needs: [
      'Bright indirect light',
      'Even moisture, never bone dry',
      'Humidity above 50%',
      'Wipe fronds occasionally',
    ],
    mistakes: [
      'Bone-dry air — brown leaf tips inevitable',
      'Hard water — mineral buildup browns tips',
    ],
    headsup: 'A few brown tips on older fronds are normal. Wholesale crisping is not.',
  },
  'olive tree': {
    kind: 'plant', difficulty: 3, lifespan: '50+ years',
    level: 'Mediterranean — wants the sun it left behind',
    needs: [
      'Full sun, 6+ hours direct',
      'Deep watering, then let dry',
      'Gritty, well-drained soil',
      'Cool winter rest, less water',
    ],
    mistakes: [
      'Low light — they slowly weaken',
      'Constantly moist soil — root rot',
    ],
    headsup: 'A little stress is fine. Olive trees fruit better when treated firmly.',
  },
  'herb': {
    kind: 'plant', difficulty: 2, lifespan: 'months to years (depends on herb)',
    level: 'Cooks\' joy — most are annuals indoors',
    needs: [
      'Full sun on a windowsill',
      'Even watering, no swamps',
      'Pinch tips to keep bushy',
      'Repot from supermarket pots immediately — they\'re crammed',
    ],
    mistakes: [
      'Stripping the plant when harvesting — leaves growth points only',
      'Letting basil flower — it goes bitter',
    ],
    headsup: 'Most supermarket herbs are 5–10 seedlings in one pot. Separate them.',
  },
  'sage': {
    kind: 'plant', difficulty: 2, lifespan: '3–5 years',
    level: 'Mediterranean herb — sun first, water second',
    needs: [
      'Full sun, 6+ hours when possible',
      'Let the top soil dry between waterings',
      'Lean, well-drained mix',
      'Pinch tips to keep it compact',
    ],
    mistakes: [
      'Soggy roots — sage wants air around them',
      'Low winter light plus frequent watering',
      'Harvesting woody stems without leaving fresh growth',
    ],
    headsup: 'Sage is drought-tolerant once settled. Indoors, the danger is usually kindness with too much water.',
  },
  'vegetable': {
    kind: 'plant', difficulty: 3, lifespan: 'one growing season',
    level: 'Rewarding but seasonal',
    needs: [
      'Full sun, 6+ hours',
      'Rich compost-amended soil',
      'Consistent watering — irregular = split fruit',
      'Stakes/cages for tall growers',
    ],
    mistakes: [
      'Overcrowding — air flow prevents disease',
      'Cold nights still in single digits',
    ],
    headsup: 'Tomatoes need so much water you can barely overdo it once they\'re fruiting.',
  },
  'flower': {
    kind: 'plant', difficulty: 3, lifespan: 'varies',
    level: 'Annuals are short, perennials reward patience',
    needs: [
      'Light matched to the species',
      'Deadhead spent blooms for more flowers',
      'Feed during bloom season',
      'Mulch keeps roots cool',
    ],
    mistakes: [
      'Watering the leaves instead of the base',
      'Skipping mulch in summer',
    ],
    headsup: 'A plant that hasn\'t bloomed yet may just need more light — wait a season.',
  },
  'avocado': {
    kind: 'plant', difficulty: 3, lifespan: 'years indoors, decades outdoors',
    level: 'A long science project, rarely fruits indoors',
    needs: [
      'Bright direct light',
      'Deep watering, then let dry',
      'Top-pruning to encourage branching',
      'Patience — fruit (if any) takes 5–13 years',
    ],
    mistakes: [
      'Expecting fruit indoors',
      'Tiny pot — they want depth',
    ],
    headsup: 'Even if it never fruits, the leaves smell beautiful when crushed.',
  },
  'hibiscus': {
    kind: 'plant', difficulty: 3, lifespan: 'years',
    level: 'Tropical drama — every bloom is a one-day wonder',
    needs: [
      'Full sun',
      'Deep weekly watering',
      'Feed weekly during bloom',
      'Prune in late winter for shape',
    ],
    mistakes: [
      'Letting them dry in summer — buds drop',
      'Cold snaps under 10°C',
    ],
    headsup: 'Each flower lasts one day. The plant keeps making more all season.',
  },

  // generic fallback
  '_default_pet':   { kind: 'pet', difficulty: 3, lifespan: 'varies', level: 'Let\'s learn together.',
                      needs: ['Fresh water always', 'Clean enclosure', 'Species-appropriate diet', 'Vet familiar with this species'],
                      mistakes: ['Generic small-animal care — research the specific species', 'Skipping exotic-vet research before adoption'],
                      headsup: 'Custom species — tap Ask Tendlet to learn more.' },
  '_default_plant': { kind: 'plant', difficulty: 3, lifespan: 'varies', level: 'Let\'s learn together.',
                      needs: ['Light matched to its origin', 'Drainage in the pot', 'Watering only when soil tells you', 'Wipe leaves monthly'],
                      mistakes: ['Treating all plants the same', 'Watering on a fixed schedule'],
                      headsup: 'Custom plant — tap Ask Tendlet to learn more.' },
};

// Look up by species label (case-insensitive). Falls back to a generic.
function careFor(species, kind) {
  if (!species) return SPECIES_CARE['_default_' + (kind || 'pet')];
  const k = species.toLowerCase().trim();
  return SPECIES_CARE[k]
      || Object.entries(SPECIES_CARE).find(([key]) => k.includes(key) && !key.startsWith('_'))?.[1]
      || SPECIES_CARE['_default_' + (kind || 'pet')];
}

// Pick a tip for this species at the given index (stable rotation).
// Falls back to using a needs-line as a tip if no tips array exists.
function tipFor(species, kind, idx = 0) {
  const c = careFor(species, kind);
  if (!c) return null;
  if (c.tips && c.tips.length) return c.tips[idx % c.tips.length];
  // gentle fallback
  const pool = (c.headsup ? [c.headsup] : []).concat(c.needs ? c.needs.slice(0, 2) : []);
  return pool.length ? pool[idx % pool.length] : null;
}

window.SPECIES_CARE = SPECIES_CARE;
window.careFor = careFor;
window.tipFor = tipFor;
