export function calculateCurrentDay(startDate) {
  if (!startDate) return 0;
  const start = new Date(startDate);
  const today = new Date();
  start.setHours(0, 0, 0, 0);
  today.setHours(0, 0, 0, 0);
  const diffTime = today - start;
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;
  return Math.max(1, Math.min(diffDays, 40));
}

export function getDayPhase(day) {
  if (day <= 7) return 'awakening';
  if (day <= 14) return 'building';
  if (day <= 21) return 'testing';
  if (day <= 30) return 'strengthening';
  return 'transcending';
}

export function getDayNarrative(day) {
  const phase = getDayPhase(day);
  const narratives = {
    awakening: [
      'The seed has been planted. Your old self watches curiously.',
      'Small cracks appear in old patterns. Keep going.',
      'Your identity is shifting beneath the surface.',
      'The resistance you feel is proof of change.',
      'Day by day, you become who you decided to be.',
      'Your habits are writing a new story.',
      'One week in. The foundation is forming.',
    ],
    building: [
      'Momentum is building. Can you feel it?',
      'Your new self is taking shape.',
      'The gap between who you were and who you are is growing.',
      'Discipline is becoming your default.',
      'You are proving something to yourself.',
      'Two weeks. This is no longer a phase.',
      'Your identity is crystallizing.',
    ],
    testing: [
      'This is where most people quit. You are not most people.',
      'The test is not the habit — it is who you become when it gets hard.',
      'Three weeks. Your neural pathways are rewiring.',
      'Comfort zone? You left that behind.',
      'Every day you show up, you vote for your new identity.',
      'The old you would have stopped by now.',
      'You are becoming undeniable.',
    ],
    strengthening: [
      'Your transformation is visible now.',
      'What was hard is becoming natural.',
      'You do not do these things — you ARE this person.',
      'The orbit is nearly complete.',
      'Identity is not what you say. It is what you do repeatedly.',
      'You have proven you can change.',
      'The final stretch. Every day counts.',
    ],
    transcending: [
      'The metamorphosis nears completion.',
      'You are not the same person who started this.',
      'Look back at Day 1. See how far you have come.',
      'These habits are now part of your DNA.',
      'The person you imagined? You are becoming them.',
      'Almost there. The universe is watching.',
      'Your new identity is forged.',
      'The final days. Make them count.',
      'Tomorrow, you complete your transformation.',
      'Day 40. You made it. You are Nova.',
    ],
  };

  const phaseNarratives = narratives[phase];
  const phaseStart =
    phase === 'awakening' ? 1
    : phase === 'building' ? 8
    : phase === 'testing' ? 15
    : phase === 'strengthening' ? 22
    : 31;
  const index = Math.min(day - phaseStart, phaseNarratives.length - 1);
  return phaseNarratives[index];
}

export function isCriticalDay(day) {
  return [3, 10, 21, 30].includes(day);
}

// Shuffle array (Fisher-Yates)
function shuffle(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

// Habit pool — each keyword maps to many habits, pick random subset
const HABIT_POOL = {
  // Fitness / Body
  'fit,gym,exercise,workout,body,weight,muscle,run,jog,active': [
    { title: 'Move your body 30 minutes', description: 'Walk, run, lift — just move' },
    { title: 'Take 10,000 steps', description: 'Stay active throughout the day' },
    { title: 'Do a morning stretch', description: '10 minutes to wake your body up' },
    { title: 'No elevator — take stairs', description: 'Small movement adds up' },
    { title: 'Try a new workout', description: 'Keep your body guessing' },
    { title: 'Track your workout', description: 'Log sets, reps, or distance' },
    { title: 'Cool down after exercise', description: '5 min stretch post-workout' },
  ],
  // Health / Nutrition
  'health,eat,food,diet,nutrition,sugar,meal,cook,clean': [
    { title: 'Eat one clean meal', description: 'Whole foods, no processed stuff' },
    { title: 'Drink 2L of water', description: 'Hydrate before you caffeinate' },
    { title: 'No junk food today', description: 'Choose fuel over comfort' },
    { title: 'Eat a fruit or vegetable', description: 'Add color to your plate' },
    { title: 'Cook one meal at home', description: 'Control what goes in your body' },
    { title: 'Skip sugar after 6pm', description: 'Let your body rest clean' },
    { title: 'Eat slowly — no screen', description: 'Be present with your meal' },
  ],
  // Sleep / Rest
  'sleep,rest,tired,exhaust,energy,insomnia,bed': [
    { title: 'Sleep by 11pm', description: 'Protect your rest window' },
    { title: 'No screens 30min before bed', description: 'Let your brain wind down' },
    { title: 'Sleep 7+ hours', description: 'Make rest non-negotiable' },
    { title: 'Create a bedtime ritual', description: 'Tea, book, stretch — your call' },
    { title: 'Wake at the same time daily', description: 'Consistency over alarm snoozing' },
    { title: 'No caffeine after 2pm', description: 'Protect your sleep quality' },
  ],
  // Reading / Learning
  'read,book,learn,study,knowledge,smart,curious,educat': [
    { title: 'Read 15 pages', description: 'A small chapter changes everything' },
    { title: 'Listen to a podcast', description: 'Learn while you commute' },
    { title: 'Write one thing you learned', description: 'Retention through reflection' },
    { title: 'Replace 30min scrolling with reading', description: 'Swap consumption types' },
    { title: 'Teach someone what you learned', description: 'Teaching deepens understanding' },
    { title: 'Read before bed instead of phone', description: 'End the day growing' },
    { title: 'Take handwritten notes', description: 'Pen to paper locks it in' },
  ],
  // Discipline / Routine
  'disciplin,routine,consist,habit,lazy,procrastinat,structure': [
    { title: 'Wake up at the same time', description: 'Discipline starts with your alarm' },
    { title: 'Make your bed immediately', description: 'First win of the day' },
    { title: 'Follow a written schedule', description: 'Plan it, then do it' },
    { title: 'Do the hardest task first', description: 'Eat the frog before noon' },
    { title: 'No snooze button', description: 'Rise when the alarm rings' },
    { title: 'End the day with a review', description: 'What went well? What to fix?' },
    { title: 'Say no to one distraction', description: 'Guard your time like your life' },
  ],
  // Focus / Productivity
  'focus,product,distract,attention,deep work,concentrat,procrast': [
    { title: 'One 90-min deep work block', description: 'Phone off, door closed, create' },
    { title: 'Use a Pomodoro timer', description: '25 on, 5 off — repeat' },
    { title: 'Plan your top 3 tasks tonight', description: 'Wake up with clarity' },
    { title: 'Clear your workspace', description: 'Clean space, clear mind' },
    { title: 'Single-task for 1 hour', description: 'No tabs, no switching' },
    { title: 'Delete one app that wastes time', description: 'Remove temptation at the source' },
    { title: 'Review your week every Sunday', description: 'Reflect and recalibrate' },
  ],
  // Confidence / Social
  'confiden,shy,social,anxi,fear,brave,courage,speak,voice': [
    { title: 'Give one genuine compliment', description: 'Kindness builds confidence' },
    { title: 'Speak up once in a group', description: 'Your voice matters' },
    { title: 'Make eye contact with strangers', description: 'Presence over avoidance' },
    { title: 'Write 3 wins from today', description: 'Train your brain to see strength' },
    { title: 'Say no to something you don\'t want', description: 'Boundaries are self-respect' },
    { title: 'Do one thing that scares you', description: 'Growth lives outside comfort' },
    { title: 'Record a voice note to yourself', description: 'Hear your own conviction' },
  ],
  // Calm / Mental health
  'calm,stress,anxious,peace,mental,meditat,mindful,relax,overwhelm,worry': [
    { title: 'Meditate for 10 minutes', description: 'Sit still. Breathe. That\'s enough' },
    { title: 'Write in a gratitude journal', description: '3 things you\'re thankful for' },
    { title: 'Take a walk in nature', description: 'No phone, just presence' },
    { title: 'Do a 5-minute breathing exercise', description: 'Inhale 4, hold 4, exhale 4' },
    { title: 'Digital detox for 1 hour', description: 'Unplug and reconnect with yourself' },
    { title: 'Stretch for 10 minutes', description: 'Release tension from your body' },
    { title: 'Listen to calming music', description: 'Let sound reset your mood' },
  ],
  // Creative / Art
  'creat,art,music,draw,paint,design,write,craft,imagin,innovat': [
    { title: 'Create something for 20 minutes', description: 'Draw, write, build — anything' },
    { title: 'Brainstorm 5 ideas', description: 'Quantity unlocks quality' },
    { title: 'Practice your craft', description: 'Show up even without inspiration' },
    { title: 'Consume inspiring work', description: 'Study someone you admire' },
    { title: 'Share one thing you made', description: 'Put your work into the world' },
    { title: 'Try a new creative technique', description: 'Experiment without pressure' },
    { title: 'Freewrite for 10 minutes', description: 'No editing, just flow' },
  ],
  // Finance / Career
  'money,financ,save,earn,career,business,invest,rich,wealth,job,work': [
    { title: 'Track every expense today', description: 'Awareness is the first step' },
    { title: 'Save before you spend', description: 'Pay yourself first' },
    { title: 'Learn one new skill for your career', description: '15 minutes of growth' },
    { title: 'Review your financial goals', description: 'Are you on track?' },
    { title: 'Avoid one impulse purchase', description: 'Ask: do I need this or want this?' },
    { title: 'Network — reach out to someone', description: 'Opportunities come through people' },
    { title: 'Read about your industry', description: 'Stay sharp and informed' },
  ],
  // Relationships
  'relationship,friend,family,love,connect,lonel,kind,empath,partner': [
    { title: 'Call or text someone you care about', description: 'Connection takes 2 minutes' },
    { title: 'Practice active listening', description: 'Listen to understand, not to reply' },
    { title: 'Give an unexpected compliment', description: 'Brighten someone\'s day' },
    { title: 'Be fully present in a conversation', description: 'Phone down, eyes up' },
    { title: 'Write a thank-you message', description: 'Gratitude strengthens bonds' },
    { title: 'Forgive one small thing', description: 'Carrying grudges weighs you down' },
    { title: 'Plan quality time with someone', description: 'Make people a priority, not an afterthought' },
  ],
  // Morning / Routine
  'morn,wake,alarm,sunrise,start,begin,early': [
    { title: 'Wake before 6:30 AM', description: 'Own the morning, own the day' },
    { title: 'No phone for first 30 minutes', description: 'Your mind deserves a slow start' },
    { title: 'Drink water before coffee', description: 'Rehydrate first' },
    { title: 'Move your body within 15 min of waking', description: 'Jumpstart your energy' },
    { title: 'Set 3 intentions for the day', description: 'Know what matters before you start' },
    { title: 'Eat a real breakfast', description: 'Fuel, not just caffeine' },
  ],
  // Spiritual / Purpose
  'spirit,purpose,meaning,faith,pray,god,soul,grateful,thank': [
    { title: 'Spend 10 minutes in stillness', description: 'Prayer, meditation, or silence' },
    { title: 'Write what you\'re grateful for', description: 'Gratitude changes your lens' },
    { title: 'Read something that feeds your soul', description: 'A verse, a poem, a passage' },
    { title: 'Reflect on your purpose', description: 'Why are you here? What matters?' },
    { title: 'Do one act of kindness', description: 'Give without expecting return' },
    { title: 'Forgive yourself for something', description: 'Grace is a daily practice' },
  ],
};

// Universal habits that apply to anyone
const UNIVERSAL_HABITS = [
  { title: 'Journal for 5 minutes', description: 'Put your thoughts on paper' },
  { title: 'Drink a full glass of water first thing', description: 'Start clean' },
  { title: 'Take a 10-minute walk', description: 'Movement clears the mind' },
  { title: 'Do one thing outside your comfort zone', description: 'Growth is on the other side' },
  { title: 'Spend 5 minutes planning tomorrow', description: 'Never wake up without a plan' },
  { title: 'Say something kind to yourself', description: 'You talk to yourself more than anyone' },
  { title: 'Avoid complaining for 1 hour', description: 'Replace complaints with solutions' },
  { title: 'Tidy one small area', description: 'Order outside creates order inside' },
  { title: 'Do something you\'ve been avoiding', description: 'The relief is worth the effort' },
  { title: 'Go to bed 15 minutes earlier', description: 'Small shifts, big impact' },
];

export function generateHabitsFromIdentity(title) {
  const text = (title || '').toLowerCase();
  const matched = [];

  // Collect all matching habits from the pool
  for (const [keys, habits] of Object.entries(HABIT_POOL)) {
    const keyList = keys.split(',');
    if (keyList.some((k) => text.includes(k.trim()))) {
      habits.forEach((h) => {
        if (!matched.some((m) => m.title === h.title)) matched.push(h);
      });
    }
  }

  // Shuffle matched and pick 3-5
  if (matched.length > 0) {
    const picked = shuffle(matched).slice(0, 3 + Math.floor(Math.random() * 2));
    return picked;
  }

  // No keyword match — return random universal habits
  return shuffle(UNIVERSAL_HABITS).slice(0, 3);
}

export function getSuggestionsForIdentity(title) {
  if (!title || title.trim().length < 2) return [];
  const text = title.toLowerCase();
  const matched = [];

  for (const [keys, habits] of Object.entries(HABIT_POOL)) {
    const keyList = keys.split(',');
    if (keyList.some((k) => text.includes(k.trim()))) {
      habits.forEach((h) => {
        if (!matched.includes(h.title)) matched.push(h.title);
      });
    }
  }

  // Shuffle so same input doesn't always show same order
  const shuffled = shuffle(matched);

  // If few matches, pad with universal habits
  if (shuffled.length < 5) {
    const universalTitles = shuffle(UNIVERSAL_HABITS).map((h) => h.title);
    universalTitles.forEach((t) => {
      if (!shuffled.includes(t)) shuffled.push(t);
    });
  }

  return shuffled.slice(0, 8);
}

export function formatDate(date) {
  return new Date(date).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}
