// data.jsx — fake demo data for Tendlet

const FOLK = [
  { id: 'luna',    name: 'Luna',    kind: 'pet',   species: 'Guinea pig',          breed: 'American', age: '2y 4m', weight: '1.04 kg', mood: 'curious', tint: 'terra', emoji: '🐹', placeholderHue: 22,
    thought: 'Where is the cilantro?',  currently: 'rearranging the hay rack', adoptedDate: 'two springs ago' },
  { id: 'mochi',   name: 'Mochi',   kind: 'pet',   species: 'Cat',                 breed: 'Ragdoll',  age: '4 yrs', weight: '5.2 kg',  mood: 'sleepy',  tint: 'sand',  emoji: '🐱', placeholderHue: 30,
    thought: 'There is something near the window.', currently: 'on the sunlit sill', adoptedDate: 'four winters ago' },
  { id: 'koda',    name: 'Koda',    kind: 'pet',   species: 'Dog',                 breed: 'Aussie mix', age: '6 yrs', weight: '18.3 kg', mood: 'playful', tint: 'honey', emoji: '🐕', placeholderHue: 36,
    thought: 'I would like to come too.', currently: 'waiting by the door', adoptedDate: 'six years ago' },
  { id: 'mira',    name: 'Mira',    kind: 'pet',   species: 'Betta fish',          breed: 'Veiltail', age: '11 mo', weight: '2 g',     mood: 'serene',  tint: 'pond',  emoji: '🐟', placeholderHue: 200,
    thought: '…', currently: 'circling slowly', adoptedDate: 'last summer' },
  { id: 'fern',    name: 'Fern',    kind: 'plant', species: 'Maidenhair fern',     latin: 'Adiantum',         care: 'low light · every 3d', tint: 'forest', emoji: '🌿', placeholderHue: 130,
    thought: 'It is lovely and damp here.', currently: 'unfurling a new frond', adoptedDate: 'three winters ago' },
  { id: 'echo',    name: 'Echo',    kind: 'plant', species: 'Monstera',            latin: 'M. deliciosa',     care: 'bright indirect · weekly', tint: 'sage',   emoji: '🌱', placeholderHue: 120,
    thought: 'I would like a little more light.', currently: 'soil medium-dry', adoptedDate: 'last March' },
  { id: 'ollie',   name: 'Ollie',   kind: 'plant', species: 'Ponytail palm',       latin: 'Beaucarnea recurvata', care: 'bright indirect · every 2w', tint: 'olive',  emoji: '🌴', placeholderHue: 90,
    thought: 'I miss the Mediterranean.', currently: 'leaves dusty', adoptedDate: 'two summers ago' },
  { id: 'sage',    name: 'Sage',    kind: 'plant', species: 'Sage',                latin: 'Salvia officinalis', care: 'full sun · weekly',        tint: 'desert', emoji: '🌿', placeholderHue: 60,
    thought: 'I am fine. Really.', currently: 'storing sun', adoptedDate: 'four years ago' },
];

const TODAY_TASKS = [
  { id: 't1', time: '07:30', folkId: 'koda',  verb: 'Morning walk',      detail: '30 min · cool weather', kind: 'walk',  done: true,  source: 'suggested', recurrence: { type: 'daily' } },
  { id: 't2', time: '08:00', folkId: 'luna',  verb: 'Refresh hay & water', detail: 'timothy + filtered',  kind: 'feed',  done: false, source: 'suggested', recurrence: { type: 'daily' } },
  { id: 't3', time: '08:15', folkId: 'mochi', verb: 'Breakfast for Mochi', detail: '40 g wet · salmon',   kind: 'feed',  done: false, source: 'suggested', recurrence: { type: 'daily' } },
  { id: 't4', time: '09:00', folkId: 'fern',  verb: 'Mist Fern',          detail: 'gentle, leaves only',  kind: 'mist',  done: false, source: 'suggested', recurrence: { type: 'every', days: 3 } },
  { id: 't5', time: '12:30', folkId: 'echo',  verb: 'Water Echo',         detail: '~200 ml, soak & drain', kind: 'water', done: false, source: 'suggested', recurrence: { type: 'weekly', days: ['tue'] } },
  { id: 't7', time: '18:30', folkId: 'mira',  verb: 'Feed Mira',          detail: '3 pellets',            kind: 'feed',  done: false, source: 'suggested', recurrence: { type: 'every', days: 2 } },
];

const WEEK = [
  { d: 'M', date: 11, count: 4, today: false },
  { d: 'T', date: 12, count: 5, today: false },
  { d: 'W', date: 13, count: 5, today: false },
  { d: 'T', date: 14, count: 6, today: true  },
  { d: 'F', date: 15, count: 4, today: false },
  { d: 'S', date: 16, count: 3, today: false },
  { d: 'S', date: 17, count: 5, today: false },
];

const JOURNAL_LUNA = [
  { id: 'j1', date: 'Tue · Mar 10', kind: 'note',   text: 'Wheeked loudly when fridge opened. Standard.' },
  { id: 'j2', date: 'Mon · Mar 9',  kind: 'health', text: 'Weight check: 1.04 kg (+20 g)' },
  { id: 'j3', date: 'Sun · Mar 8',  kind: 'photo',  text: 'Lap time on the porch, late afternoon.' },
  { id: 'j4', date: 'Sat · Mar 7',  kind: 'vet',    text: 'Annual exam — clean teeth, no scurvy signs.' },
  { id: 'j5', date: 'Fri · Mar 6',  kind: 'note',   text: 'New burrow under the hay rack.' },
];

const MOOD_WEEK = [3, 4, 4, 3, 5, 4, 5]; // 1-5 mood scale

const SHOP = [
  { id: 's1', for: 'luna',  item: 'Timothy hay, 1 kg',     low: true,  vendor: 'Small Pet Select' },
  { id: 's2', for: 'echo',  item: 'Aroid potting mix, 8L', low: false, vendor: 'Tend' },
  { id: 's3', for: 'koda',  item: 'Salmon kibble, 6 kg',   low: true,  vendor: 'Open Farm' },
  { id: 's4', for: 'mira',  item: 'Betta pellets, 30 g',   low: false, vendor: 'Hikari' },
];

// ── Recurrence helpers ──────────────────────────────────────────────────
const DAY_FULL = { mon: 'Monday', tue: 'Tuesday', wed: 'Wednesday', thu: 'Thursday', fri: 'Friday', sat: 'Saturday', sun: 'Sunday' };
const DAY_SHORT = { mon: 'Mon', tue: 'Tue', wed: 'Wed', thu: 'Thu', fri: 'Fri', sat: 'Sat', sun: 'Sun' };
const DAY_ORDER = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
function ordinal(n) {
  const s = ['th', 'st', 'nd', 'rd'], v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function formatRecurrence(r) {
  if (!r) return 'Every day';
  if (r.type === 'daily') return 'Every day';
  if (r.type === 'weekly') {
    const days = (r.days || []).slice().sort((a, b) => DAY_ORDER.indexOf(a) - DAY_ORDER.indexOf(b));
    if (!days.length) return 'Weekly';
    if (days.length === 7) return 'Every day';
    if (days.length === 1) return `Every ${DAY_FULL[days[0]]}`;
    if (days.length === 2 && days.includes('sat') && days.includes('sun')) return 'Weekends';
    if (days.length === 5 && !days.includes('sat') && !days.includes('sun')) return 'Weekdays';
    return days.map((d) => DAY_SHORT[d]).join(' · ');
  }
  if (r.type === 'every') return `Every ${r.days} day${r.days === 1 ? '' : 's'}`;
  if (r.type === 'monthly') {
    if (r.day === 'first') return '1st of each month';
    if (r.day === 'last')  return 'Last day of month';
    return `${ordinal(r.day)} of each month`;
  }
  if (r.type === 'once') return `Once · ${r.date}`;
  return 'Every day';
}

// ── Editorial "moment" content — pool that the home cycles through ──
const MOMENTS = [
  { kind: 'memory',  kicker: 'On this day',     line: 'Two years ago, you brought Luna home in a shoebox.' },
  { kind: 'memory',  kicker: 'On this day',     line: 'Last spring, Echo unfurled her first true leaf.' },
  { kind: 'wisdom',  kicker: 'From the journal', line: 'Maidenhair ferns drink the air — they thrive next to a kettle.' },
  { kind: 'wisdom',  kicker: 'Old keepers say', line: 'Guinea pigs do better in pairs. Loneliness shows in the eyes.' },
  { kind: 'wisdom',  kicker: 'Tend gently',     line: 'Cats notice the smallest changes. Move furniture slowly.' },
  { kind: 'growth',  kicker: 'Something to notice', line: 'Koda has gained 0.3 kg this season. The same coat fits looser.' },
  { kind: 'growth',  kicker: 'Quiet progress',  line: 'Mochi has not woken you before sunrise in eleven days.' },
  { kind: 'season',  kicker: 'Late spring',     line: 'Pollen rises. Wipe leaves once this week so they can breathe.' },
];

const FOLK_THOUGHTS_FALLBACK = [
  'thinking about birds again', 'considering a nap', 'watching the dust catch light',
  'listening to the kettle', 'remembering the rain',
];

function householdWarningsFor(folks) {
  const list = Array.isArray(folks) ? folks : [];
  const norm = (value) => (value || '').toLowerCase();
  const name = (folk, fallback) => (folk?.name || fallback).trim();
  const joinNames = (items) => {
    const names = items.map((item) => name(item, 'them')).filter(Boolean);
    if (names.length <= 1) return names[0] || 'your pets';
    if (names.length === 2) return `${names[0]} and ${names[1]}`;
    return `${names.slice(0, -1).join(', ')}, and ${names[names.length - 1]}`;
  };
  const pets = list.filter((folk) => folk.kind === 'pet');
  const plants = list.filter((folk) => folk.kind === 'plant');
  const catsAndDogs = pets.filter((folk) => {
    const species = norm(folk.species);
    return species.includes('cat') || species.includes('dog');
  });
  const guineaPigs = pets.filter((folk) => norm(folk.species).includes('guinea'));
  const warnings = [];

  plants.forEach((plant) => {
    const species = norm(plant.species);
    if (species.includes('monstera') && catsAndDogs.length) {
      warnings.push({
        id: `${plant.id}-monstera-pet-toxicity`,
        folkId: plant.id,
        severity: 'hard',
        title: 'Monstera near pets',
        body: `${name(plant, 'This monstera')} can irritate ${joinNames(catsAndDogs)} if chewed. Keep leaves out of reach and call a vet if drooling, vomiting, or swelling appears.`,
      });
    }
  });

  if (guineaPigs.length === 1) {
    const guinea = guineaPigs[0];
    warnings.push({
      id: `${guinea.id}-solo-guinea-pig`,
      folkId: guinea.id,
      severity: 'hard',
      title: 'Guinea pigs are social',
      body: `${name(guinea, 'Your guinea pig')} should not live alone long-term. Plan a bonded companion and watch appetite or weight changes closely.`,
    });
  }

  const severityRank = { lethal: 0, hard: 1, soft: 2 };
  return warnings.sort((a, b) => (severityRank[a.severity] ?? 3) - (severityRank[b.severity] ?? 3) || a.title.localeCompare(b.title));
}

// ─── Generators for fresh user data ──────────────────────────────────────

// Turn onboarding-shaped folk into FOLK-shaped folk
function hydrateOnboardingFolk(list) {
  return list.map((f) => ({
    id: f.id,
    name: (f.name || '').trim() || 'Unnamed',
    kind: f.kind,
    species: f.species,
    breed: f.custom ? 'custom' : undefined,
    age: '—',
    weight: f.kind === 'pet' ? '—' : undefined,
    mood: f.kind === 'pet' ? 'new here' : undefined,
    care: f.kind === 'plant' ? 'routine forming…' : undefined,
    tint: f.tint,
    emoji: f.em,
    iconKey: f.iconKey,
    latin: '',
  }));
}

// Build a default daily routine for a list of folks
function generateTasksFor(folks) {
  const out = [];
  let n = 1;
  const maxToday = 6;
  const push = (time, folkId, verb, detail, kind, recurrence) =>
    out.length < maxToday && out.push({ id: `g${n++}`, time, folkId, verb, detail, kind, done: false, source: 'suggested', recurrence: recurrence || { type: 'daily' } });

  folks.forEach((f) => {
    const s = (f.species || '').toLowerCase();
    const nm = (f.name || '').trim() || (f.kind === 'pet' ? 'them' : 'this plant');

    if (f.kind === 'pet') {
      if (s.includes('dog'))      { push('07:30', f.id, `Morning walk with ${nm}`, '30 min', 'walk');
                                    push('08:00', f.id, `Breakfast for ${nm}`,    'kibble + fresh water', 'feed'); }
      else if (s.includes('cat')) { push('08:00', f.id, `Breakfast for ${nm}`,    '40 g wet', 'feed');
                                    push('19:00', f.id, `Dinner for ${nm}`,       '40 g wet', 'feed'); }
      else if (s.includes('fish'))      { push('18:30', f.id, `Feed ${nm}`, '3 pellets', 'feed', { type: 'every', days: 2 });
                                          push('09:00', f.id, `Check water temp`, '24–27°', 'water', { type: 'daily' }); }
      else if (s.includes('bird') || s.includes('parrot')) {
                                    push('08:00', f.id, `Fresh seed & water`, 'rinse bowl', 'feed');
                                    push('18:00', f.id, `Out-of-cage time for ${nm}`, '20 min', 'love'); }
      else if (s.includes('snake')|| s.includes('lizard') || s.includes('turtle') || s.includes('frog')) {
                                    push('09:00', f.id, `Check heat & humidity`, 'log readings', 'water');
                                    push('19:00', f.id, `Feed ${nm}`, 'per schedule', 'feed'); }
      else                        { // small mammals: guinea pig, rabbit, hamster, rat, chinchilla, hedgehog, etc.
                                    push('08:00', f.id, `Refresh hay & water for ${nm}`, 'timothy + filtered', 'feed');
                                    push('12:30', f.id, `Fresh greens for ${nm}`, 'romaine + bell pepper', 'feed'); }
    } else {
      // plants — light & water
      if (s.includes('cactus') || s.includes('succulent'))
        push('10:00', f.id, `Check ${nm}`,  'water only if soil dry', 'water', { type: 'every', days: 14 });
      else if (s.includes('fern') || s.includes('peace') || s.includes('orchid'))
      { push('09:00', f.id, `Mist ${nm}`,  'humidity boost', 'mist', { type: 'every', days: 3 }); }
      else if (s.includes('herb') || s.includes('vegetable') || s.includes('tomato'))
      { push('08:30', f.id, `Water ${nm}`, 'till runoff', 'water', { type: 'daily' });
        push('17:00', f.id, `Check ${nm} for pests`, 'leaves underside', 'mist', { type: 'weekly', days: ['sun'] }); }
      else {
        push('12:30', f.id, `Water ${nm}`, '~200 ml, soak & drain', 'water', { type: 'weekly', days: ['tue'] });
      }
    }
  });

  out.sort((a, b) => a.time.localeCompare(b.time));
  return out;
}

Object.assign(window, { FOLK, TODAY_TASKS, WEEK, JOURNAL_LUNA, MOOD_WEEK, SHOP, MOMENTS, FOLK_THOUGHTS_FALLBACK, householdWarningsFor, generateTasksFor, hydrateOnboardingFolk, formatRecurrence });
