const { useState, useEffect, useRef } = React

// ── Progress Store ──────────────────────────────────────────────────────────
// All localStorage access is isolated here. To upgrade to Supabase,
// replace the body of each function and keep the same async signatures.

const STORAGE_KEY = 'wiw-progress-v1'

const Progress = {
  get: async () => JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}'),
  _put: async d => { localStorage.setItem(STORAGE_KEY, JSON.stringify(d)); return d },

  saveDay: async (weekNum, dayNum, data) => {
    const p = await Progress.get()
    if (!p[`w${weekNum}`]) p[`w${weekNum}`] = {}
    if (!p[`w${weekNum}`].days) p[`w${weekNum}`].days = {}
    p[`w${weekNum}`].days[dayNum] = { ...data, savedAt: new Date().toISOString() }
    return Progress._put(p)
  },

  saveCheckIn: async (weekNum, phase, scores) => {
    const p = await Progress.get()
    if (!p[`w${weekNum}`]) p[`w${weekNum}`] = {}
    p[`w${weekNum}`][`ci_${phase}`] = { scores, savedAt: new Date().toISOString() }
    return Progress._put(p)
  },

  completeWeek: async (weekNum, reflection) => {
    const p = await Progress.get()
    if (!p[`w${weekNum}`]) p[`w${weekNum}`] = {}
    p[`w${weekNum}`].completedAt = new Date().toISOString()
    if (reflection) p[`w${weekNum}`].reflection = reflection
    return Progress._put(p)
  },

  reset: async () => localStorage.removeItem(STORAGE_KEY),
}

// ── Programme Data ──────────────────────────────────────────────────────────

const WEEKS = [
  {
    num: 1,
    title: 'Just Starting',
    tagline: 'Begin where you are',
    walkMins: 30,
    progressLabel: 'Start where you are',
    badge: '30-Minute Milestone',
    intro: 'This first week is about starting exactly where you are. No pressure, no pace requirements - just the act of lacing up your shoes and stepping outside. That single act is where transformation begins.',
    keyMessage: 'Every step counts. You do not need to be fast or far - you just need to be moving.',
    tip: 'Try a morning walk before checking your phone. Even ten minutes clears the mind and sets a positive tone for your whole day.',
    reflection: 'How did it feel to start moving this week? What surprised you?',
    hasCheckIn: false,
  },
  {
    num: 2,
    title: 'Gathering Momentum',
    tagline: 'Find your rhythm',
    walkMins: 40,
    progressLabel: 'Add a little more',
    badge: '40-Minute Achiever',
    intro: 'You have shown up once - now we build on that. This week we add a few minutes and notice what shifts. You are not just walking; you are building evidence that you are someone who keeps their word to themselves.',
    keyMessage: 'Momentum is built in the ordinary moments, not the extraordinary ones.',
    tip: 'Notice what you see on your walks. Nature has a way of grounding us in the present moment and quieting the noise of the day.',
    reflection: 'What have you noticed about your energy levels since you started walking?',
    hasCheckIn: true,
    checkInLabel: 'Midway Wellbeing Check-in',
    checkInNote: 'Rate how you feel now versus when you started. Honest reflection creates real insight into what is shifting.',
  },
  {
    num: 3,
    title: 'Confidence Builds',
    tagline: 'Trust the process',
    walkMins: 60,
    progressLabel: 'Push a little further',
    badge: '60-Minute Champion',
    intro: 'You have made it to week three. That is not nothing - that is proof that you are someone who shows up. This week we extend to a full hour. Some days will feel hard. Do it anyway.',
    keyMessage: 'Confidence comes from doing, not from waiting until you feel ready.',
    tip: 'If a full hour feels like a lot, split it - thirty minutes in the morning and thirty minutes in the evening both count.',
    reflection: 'How has your relationship with movement changed since week one?',
    hasCheckIn: false,
  },
  {
    num: 4,
    title: "You're Doing It",
    tagline: 'Celebrate your strength',
    walkMins: 80,
    progressLabel: 'Your strongest week',
    badge: '80-Minute Warrior',
    intro: "This is it - your final week. Eighty minutes of walking. You started at thirty. Look at what you have built. This week is about finishing strong and celebrating how far you have come.",
    keyMessage: "The person who started this programme and the person finishing it are not the same person.",
    tip: 'Take your final walk somewhere meaningful. Let each step be a celebration of what you have achieved.',
    reflection: 'What has this programme taught you about yourself?',
    hasCheckIn: true,
    checkInLabel: 'Final Wellbeing Assessment',
    checkInNote: 'This is your final before and after comparison. Capture what has shifted - physically, mentally, and emotionally.',
  },
]

const WELLBEING_QUESTIONS = [
  { id: 'energy',     label: 'Energy levels',      hint: '1 = exhausted, 10 = energised' },
  { id: 'mood',       label: 'Overall mood',        hint: '1 = low, 10 = positive' },
  { id: 'sleep',      label: 'Sleep quality',       hint: '1 = poor, 10 = excellent' },
  { id: 'confidence', label: 'Physical confidence', hint: '1 = low, 10 = high' },
  { id: 'motivation', label: 'Motivation to move',  hint: '1 = none, 10 = high' },
]

const DAILY_ITEMS = [
  {
    id: 'walked', label: 'Completed my walk', emoji: '👟',
    type: 'duration',
    options: ['15 min', '20 min', '30 min', '45 min', '60 min', '75 min', '90+ min'],
  },
  {
    id: 'meals', label: 'Ate mindfully', emoji: '🥗',
    type: 'multiselect',
    options: ['Ate slowly', 'No screens at meals', 'Listened to hunger cues', 'Chose nourishing foods', 'Cooked at home'],
  },
  {
    id: 'breathwork', label: 'Breathwork', emoji: '🌬️',
    type: 'guided',
    guide: 'Box breathing: inhale slowly for 4 counts, hold for 4, exhale for 4, hold for 4. Repeat 4 to 5 times. Do this before your walk to energise, or in the evening to unwind.',
  },
  {
    id: 'winddown', label: 'Sunset wind-down', emoji: '🌅',
    type: 'guided',
    guide: 'Step outside or sit near a window as the day quiets. Leave your phone inside. Notice the quality of the light, any sounds around you, and the air on your skin. Breathe slowly for 2 to 3 minutes and let the day dissolve.',
  },
  {
    id: 'gratitude', label: 'Gratitude', emoji: '🙏',
    type: 'text',
    placeholder: 'What are you grateful for today?',
  },
  {
    id: 'intention', label: "Tomorrow's intention", emoji: '✨',
    type: 'text',
    placeholder: 'What is your intention for tomorrow?',
  },
]

const ENCOURAGEMENT_MSGS = [
  'Well done. Every entry builds the habit.',
  'Every day you show up, you become someone who shows up.',
  "That is another day done. Keep going.",
  'Small steps, taken consistently, become big change.',
  'You did it. The hardest part was deciding to start.',
  'Progress is progress, no matter the pace.',
  'Your future self will thank you for this.',
]

// ── Helpers ─────────────────────────────────────────────────────────────────

function fmtDate(iso) {
  if (!iso) return ''
  return new Date(iso).toLocaleDateString('en-AU', { day: 'numeric', month: 'long', year: 'numeric' })
}

function isDone(item, value) {
  if (item.type === 'duration')    return !!value
  if (item.type === 'multiselect') return Array.isArray(value) && value.length > 0
  if (item.type === 'guided')      return !!value
  if (item.type === 'text')        return typeof value === 'string' && value.trim().length > 0
  return !!value
}

// ── Components ───────────────────────────────────────────────────────────────

function Nav({ onLanding }) {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <button className="nav-logo" onClick={onLanding}>
          <span className="nav-wordmark">Walk Into Wellness</span>
          <span className="nav-sub">Troy Morgan Coaching</span>
        </button>
      </div>
    </nav>
  )
}

function WeekCard({ week, weekProgress, onClick }) {
  const isComplete = !!weekProgress?.completedAt
  const daysLogged = Object.keys(weekProgress?.days || {}).length

  return (
    <button className={`week-card${isComplete ? ' complete' : ''}`} onClick={onClick}>
      <div className="wc-header">
        <span className="eyebrow">Week {week.num}</span>
        {isComplete && <span className="wc-tick">✓</span>}
      </div>
      <div className="wc-progress-label display">{week.progressLabel}</div>
      <div className="wc-title display">{week.title}</div>
      <div className="wc-tagline">{week.tagline}</div>
      {!isComplete && daysLogged > 0 && (
        <div className="wc-bar">
          <div className="wc-bar-fill" style={{ width: `${Math.round((daysLogged / 7) * 100)}%` }} />
        </div>
      )}
      {isComplete && <div className="wc-badge">{week.badge}</div>}
    </button>
  )
}

function DayGrid({ weekNum, weekProgress, onDayClick }) {
  return (
    <div className="day-grid">
      {Array.from({ length: 7 }, (_, i) => {
        const day = i + 1
        const dayData = weekProgress?.days?.[day]
        const done = dayData ? DAILY_ITEMS.filter(item => isDone(item, dayData[item.id])).length : 0
        return (
          <button
            key={day}
            className={`day-cell${dayData ? ' logged' : ''}`}
            onClick={() => onDayClick(day)}
            aria-label={`Day ${day}`}
          >
            <span className="dc-day">{day}</span>
            {dayData ? (
              <span className="dc-progress">{done}/{DAILY_ITEMS.length}</span>
            ) : (
              <span className="dc-add">+</span>
            )}
          </button>
        )
      })}
    </div>
  )
}

function CheckInComparison({ before, after }) {
  return (
    <div className="ci-comparison">
      <div className="ci-comp-header">
        <span>Area</span>
        <span>Before</span>
        <span>After</span>
        <span>Change</span>
      </div>
      {WELLBEING_QUESTIONS.map(q => {
        const b = before?.[q.id] ?? 0
        const a = after?.[q.id] ?? 0
        const diff = a - b
        return (
          <div key={q.id} className="ci-comp-row">
            <span className="ci-q-label">{q.label}</span>
            <span className="ci-val">{b}</span>
            <span className="ci-val">{a}</span>
            <span className={`ci-diff ${diff > 0 ? 'pos' : diff < 0 ? 'neg' : 'flat'}`}>
              {diff > 0 ? `+${diff}` : diff === 0 ? '=' : diff}
            </span>
          </div>
        )
      })}
    </div>
  )
}

function JourneyComparison({ startScores, endScores }) {
  const totalImprovement = WELLBEING_QUESTIONS.reduce((sum, q) => {
    const diff = (endScores?.[q.id] ?? 0) - (startScores?.[q.id] ?? 0)
    return sum + Math.max(0, diff)
  }, 0)

  return (
    <section className="journey-comparison">
      <span className="eyebrow section-title">Your Wellbeing Journey</span>
      <h3 className="jc-heading display">What shifted</h3>
      <div className="ci-comparison">
        <div className="ci-comp-header">
          <span>Area</span>
          <span>Start</span>
          <span>Finish</span>
          <span>Change</span>
        </div>
        {WELLBEING_QUESTIONS.map(q => {
          const b = startScores?.[q.id] ?? 0
          const a = endScores?.[q.id] ?? 0
          const diff = a - b
          return (
            <div key={q.id} className="ci-comp-row">
              <span className="ci-q-label">{q.label}</span>
              <span className="ci-val">{b}</span>
              <span className="ci-val">{a}</span>
              <span className={`ci-diff ${diff > 0 ? 'pos' : diff < 0 ? 'neg' : 'flat'}`}>
                {diff > 0 ? `+${diff}` : diff === 0 ? '=' : diff}
              </span>
            </div>
          )
        })}
      </div>
      {totalImprovement > 0 && (
        <p className="jc-summary">
          Across all five areas, you improved by {totalImprovement} {totalImprovement === 1 ? 'point' : 'points'}.
        </p>
      )}
    </section>
  )
}

// ── Views ────────────────────────────────────────────────────────────────────

function LandingView({ progress, nav, showToast }) {
  const hasAnyProgress = Object.keys(progress).some(k => k.startsWith('w'))

  const currentWeekNum = (() => {
    for (let i = WEEKS.length; i >= 1; i--) {
      if (progress[`w${i}`]) return i
    }
    return 1
  })()

  const currentDayNum = (() => {
    const days = progress[`w${currentWeekNum}`]?.days || {}
    const logged = Object.keys(days).map(Number).sort((a, b) => b - a)
    return logged[0] || 1
  })()

  const handleShare = async () => {
    const url = window.location.href.split('?')[0]
    const text = "I am doing the Walk Into Wellness programme by Troy Morgan Coaching. Want to join me?"
    if (navigator.share) {
      try { await navigator.share({ title: 'Walk Into Wellness', text, url }) } catch {}
    } else {
      navigator.clipboard.writeText(`${text} ${url}`).then(() => showToast('Link copied'))
    }
  }

  return (
    <div className="landing-view">
      <header className="lv-hero">
        <div className="container">
          <p className="eyebrow lv-eyebrow">Troy Morgan OAM</p>
          <h1 className="lv-title display">Walk Into<br /><em>Wellness</em></h1>
          <p className="lv-tagline">A guided 4-week walking programme by Troy Morgan Coaching</p>
          <p className="lv-intro">
            Walk Into Wellness is a gentle, practical programme for anyone ready to make movement a part of their everyday life. Over four weeks, you will build your walking habit one step at a time, at your own pace. No gym, no gear, and no experience required.
          </p>
          <button className="lv-cta" onClick={() => nav.home()}>
            {hasAnyProgress ? 'Continue where you left off' : 'Begin your journey'}
          </button>
          {hasAnyProgress && (
            <p className="lv-return-hint">Week {currentWeekNum} · Day {currentDayNum}</p>
          )}
        </div>
      </header>

      <section className="lv-weeks">
        <div className="container">
          <span className="eyebrow section-title">What you'll do</span>
          <div className="lv-week-grid">
            {WEEKS.map(week => (
              <div key={week.num} className="lv-week-card">
                <span className="eyebrow lv-wk-eyebrow">Week {week.num}</span>
                <span className="lv-wk-title display">{week.title}</span>
                <span className="lv-wk-label display">{week.progressLabel}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="lv-includes">
        <div className="container">
          <span className="eyebrow section-title">What is included</span>
          <ul className="lv-includes-list">
            <li>Daily log: walk, breathwork, mindful eating, gratitude, and intention</li>
            <li>Mood tracking each day</li>
            <li>Wellbeing check-ins at week 2 and week 4</li>
            <li>A share card to mark each weekly milestone</li>
            <li>Progress saves automatically. No account needed</li>
          </ul>
        </div>
      </section>

      <section className="lv-about">
        <div className="container">
          <span className="eyebrow section-title">About Troy</span>
          <div className="lv-about-inner">
            <img src="assets/troy-morgan.webp" alt="Troy Morgan OAM" className="lv-troy-photo" />
            <p className="lv-about-text">
              Troy Morgan OAM is a Toowoomba-based wellness coach and founder of TK Publications. His programmes are designed for real people navigating real lives, not elite athletes or fitness enthusiasts. Troy was awarded the Order of Australia Medal for his contribution to community wellbeing.
            </p>
          </div>
        </div>
      </section>

      <div className="lv-footer-cta">
        <div className="container">
          <button className="lv-cta" onClick={() => nav.home()}>
            {hasAnyProgress
              ? `Continue: Week ${currentWeekNum}, Day ${currentDayNum}`
              : 'Begin your journey'}
          </button>
          <button className="lv-share-btn" onClick={handleShare}>
            Share with a friend
          </button>
        </div>
      </div>

      <footer className="app-footer">
        <p>Troy Morgan Coaching · TK Publications</p>
      </footer>
    </div>
  )
}

function HomeView({ progress, nav }) {
  const weeksDone = WEEKS.filter(w => progress[`w${w.num}`]?.completedAt).length

  const handleReset = async () => {
    if (!window.confirm('Reset all progress? This cannot be undone.')) return
    await Progress.reset()
    window.location.reload()
  }

  return (
    <div>
      <header className="hero">
        <div className="container">
          <p className="eyebrow">4-Week Walking Programme</p>
          <h1 className="hero-title display">Walk Into<br /><em>Wellness</em></h1>
          <p className="hero-sub">A guided programme by Troy Morgan Coaching</p>
          {weeksDone > 0 && (
            <p className="hero-progress">{weeksDone} of 4 weeks complete</p>
          )}
        </div>
      </header>

      <section className="weeks-section container">
        <div className="weeks-grid">
          {WEEKS.map(week => (
            <WeekCard
              key={week.num}
              week={week}
              weekProgress={progress[`w${week.num}`]}
              onClick={() => nav.week(week.num)}
            />
          ))}
        </div>
      </section>

      <footer className="app-footer">
        <p>Troy Morgan Coaching</p>
        <button className="reset-link" onClick={handleReset}>Reset progress</button>
      </footer>
    </div>
  )
}

function WeekView({ week, weekProgress, nav, refresh, showToast }) {
  const [reflection, setReflection] = useState(weekProgress?.reflection || '')
  const [saving, setSaving] = useState(false)

  const isComplete = !!weekProgress?.completedAt
  const hasBefore = !!weekProgress?.ci_before
  const hasAfter = !!weekProgress?.ci_after

  const handleComplete = async () => {
    setSaving(true)
    await Progress.completeWeek(week.num, reflection)
    await refresh()
    setSaving(false)
    showToast(`Week ${week.num} complete!`)
    setTimeout(() => nav.card(week.num), 900)
  }

  return (
    <div className="week-view">
      <div className="container">
        <button className="back-btn" onClick={() => nav.home()}>← All Weeks</button>

        <div className="wv-header">
          <p className="eyebrow">Week {week.num}</p>
          <h2 className="wv-title display">{week.title}</h2>
          <p className="wv-time">{week.progressLabel}</p>
        </div>

        <blockquote className="wv-message">"{week.keyMessage}"</blockquote>
        <p className="wv-intro">{week.intro}</p>

        <section className="wv-days">
          <span className="eyebrow section-title">This Week's Days</span>
          <DayGrid weekNum={week.num} weekProgress={weekProgress} onDayClick={day => nav.day(week.num, day)} />
        </section>

        {week.hasCheckIn && (
          <section className="wv-checkin">
            <span className="eyebrow section-title">{week.checkInLabel}</span>
            <p className="wv-checkin-note">{week.checkInNote}</p>
            <div className="checkin-phases">
              <button
                className={`phase-btn${hasBefore ? ' done' : ''}`}
                onClick={() => nav.checkIn(week.num, 'before')}
              >
                {hasBefore ? '✓ ' : ''}Before Check-in
              </button>
              <button
                className={`phase-btn${hasAfter ? ' done' : ''}`}
                onClick={() => nav.checkIn(week.num, 'after')}
              >
                {hasAfter ? '✓ ' : ''}After Check-in
              </button>
            </div>
            {hasBefore && hasAfter && (
              <CheckInComparison
                before={weekProgress.ci_before.scores}
                after={weekProgress.ci_after.scores}
              />
            )}
          </section>
        )}

        <section className="wv-reflect">
          <span className="eyebrow section-title">Reflection</span>
          <p className="wv-q">{week.reflection}</p>
          <textarea
            className="reflect-input"
            value={reflection}
            onChange={e => setReflection(e.target.value)}
            placeholder="Write your reflection here..."
            rows={4}
          />
        </section>

        {!isComplete ? (
          <button className="complete-btn" onClick={handleComplete} disabled={saving}>
            {saving ? 'Saving...' : `Mark Week ${week.num} Complete`}
          </button>
        ) : (
          <div className="complete-state">
            <p className="complete-msg">Week {week.num} complete</p>
            <p className="complete-date">{fmtDate(weekProgress.completedAt)}</p>
            <button className="share-btn" onClick={() => nav.card(week.num)}>View Share Card</button>
            <button className="home-btn" onClick={() => nav.home()}>Back to Programme</button>
          </div>
        )}
      </div>
    </div>
  )
}

function GuidedItem({ item, value, onChange }) {
  const [expanded, setExpanded] = useState(false)
  return (
    <div className={`item-block${value ? ' done' : ''}`}>
      <div className="item-block-header">
        <span className="item-emoji">{item.emoji}</span>
        <span className="item-label">{item.label}</span>
        <div className="guided-actions">
          <button className="guided-toggle" onClick={() => setExpanded(e => !e)}>
            {expanded ? 'Hide' : 'How to'}
          </button>
          <button
            className={`guided-done-btn${value ? ' active' : ''}`}
            onClick={() => onChange(!value)}
          >
            {value ? '✓ Done' : 'Mark done'}
          </button>
        </div>
      </div>
      {expanded && <p className="guided-text">{item.guide}</p>}
    </div>
  )
}

function DailyItemBlock({ item, value, onChange }) {
  if (item.type === 'guided') return <GuidedItem item={item} value={value} onChange={onChange} />

  const done = isDone(item, value)

  return (
    <div className={`item-block${done ? ' done' : ''}`}>
      <div className="item-block-header">
        <span className="item-emoji">{item.emoji}</span>
        <span className="item-label">{item.label}</span>
        {done && <span className="item-done-mark">✓</span>}
      </div>

      {item.type === 'duration' && (
        <div className="chip-group">
          {item.options.map(opt => (
            <button
              key={opt}
              className={`chip${value === opt ? ' selected' : ''}`}
              onClick={() => onChange(value === opt ? null : opt)}
            >
              {opt}
            </button>
          ))}
        </div>
      )}

      {item.type === 'multiselect' && (
        <div className="chip-group">
          {item.options.map(opt => {
            const sel = Array.isArray(value) && value.includes(opt)
            return (
              <button
                key={opt}
                className={`chip${sel ? ' selected' : ''}`}
                onClick={() => {
                  const cur = Array.isArray(value) ? value : []
                  onChange(sel ? cur.filter(s => s !== opt) : [...cur, opt])
                }}
              >
                {opt}
              </button>
            )
          })}
        </div>
      )}

      {item.type === 'text' && (
        <textarea
          className="item-textarea"
          value={value || ''}
          onChange={e => onChange(e.target.value)}
          placeholder={item.placeholder}
          rows={2}
        />
      )}
    </div>
  )
}

function DayView({ week, dayNum, dayProgress, nav, refresh, showToast }) {
  const [items, setItems] = useState(() => {
    const init = {}
    DAILY_ITEMS.forEach(item => {
      const saved = dayProgress?.[item.id]
      if (item.type === 'duration')    init[item.id] = saved || null
      else if (item.type === 'multiselect') init[item.id] = Array.isArray(saved) ? saved : []
      else if (item.type === 'guided') init[item.id] = !!saved
      else if (item.type === 'text')   init[item.id] = saved || ''
    })
    return init
  })
  const [moodScore, setMoodScore] = useState(dayProgress?.moodScore || 0)
  const [saving, setSaving] = useState(false)

  const [dirty, setDirty] = useState(false)
  const updateItem = (id, value) => { setItems(prev => ({ ...prev, [id]: value })); setDirty(true) }
  const handleMood = score => { setMoodScore(score); setDirty(true) }

  const handleBack = () => {
    if (dirty && !window.confirm('You have unsaved changes. Go back without saving?')) return
    nav.week(week.num)
  }

  const handleSave = async () => {
    setSaving(true)
    await Progress.saveDay(week.num, dayNum, { ...items, moodScore })
    await refresh()
    setSaving(false)
    setDirty(false)
    showToast(ENCOURAGEMENT_MSGS[new Date().getDay()])
    nav.week(week.num)
  }

  return (
    <div className="day-view">
      <div className="container">
        <button className="back-btn" onClick={handleBack}>← Week {week.num}</button>

        <div className="dv-header">
          <p className="eyebrow">Week {week.num}</p>
          <h2 className="dv-title display">Day {dayNum}</h2>
          <p className="dv-tip">{week.tip}</p>
        </div>

        <section className="dv-items">
          {DAILY_ITEMS.map(item => (
            <DailyItemBlock
              key={item.id}
              item={item}
              value={items[item.id]}
              onChange={val => updateItem(item.id, val)}
            />
          ))}
        </section>

        <section className="dv-mood">
          <span className="eyebrow section-title">Mood Today</span>
          <div className="mood-scale">
            {['😔', '😕', '😐', '🙂', '😊'].map((emoji, i) => (
              <button
                key={i}
                className={`mood-btn${moodScore === i + 1 ? ' active' : ''}`}
                onClick={() => handleMood(i + 1)}
              >
                {emoji}
              </button>
            ))}
          </div>
        </section>

        <button className="save-btn" onClick={handleSave} disabled={saving}>
          {saving ? 'Saving...' : 'Save Day'}
        </button>
      </div>
    </div>
  )
}

function CheckInView({ week, phase, existing, nav, refresh, showToast }) {
  const [scores, setScores] = useState(() => {
    const init = {}
    WELLBEING_QUESTIONS.forEach(q => { init[q.id] = existing?.scores?.[q.id] ?? 5 })
    return init
  })
  const [saving, setSaving] = useState(false)

  const handleSave = async () => {
    setSaving(true)
    await Progress.saveCheckIn(week.num, phase, scores)
    await refresh()
    setSaving(false)
    showToast('Check-in saved')
    nav.week(week.num)
  }

  return (
    <div className="checkin-view">
      <div className="container">
        <button className="back-btn" onClick={() => nav.week(week.num)}>← Week {week.num}</button>

        <div className="cv-header">
          <p className="eyebrow">{week.checkInLabel}</p>
          <h2 className="cv-title display">
            {phase === 'before' ? 'How do you feel right now?' : 'How do you feel after the week?'}
          </h2>
          <p className="cv-sub">Rate each area honestly from 1 to 10.</p>
        </div>

        <div className="wq-list">
          {WELLBEING_QUESTIONS.map(q => (
            <div key={q.id} className="wq-row">
              <div className="wq-meta">
                <span className="wq-label">{q.label}</span>
                <span className="wq-hint">{q.hint}</span>
              </div>
              <div className="wq-scale">
                <span className="wq-val">{scores[q.id]}</span>
                <input
                  type="range"
                  min={1}
                  max={10}
                  value={scores[q.id]}
                  onChange={e => setScores(prev => ({ ...prev, [q.id]: +e.target.value }))}
                  className="wq-slider"
                />
              </div>
            </div>
          ))}
        </div>

        <button className="save-btn" onClick={handleSave} disabled={saving}>
          {saving ? 'Saving...' : 'Save Check-in'}
        </button>
      </div>
    </div>
  )
}

function CardView({ week, nav }) {
  const cardRef = useRef(null)
  const [downloading, setDownloading] = useState(false)

  const handleDownload = async () => {
    if (!window.html2canvas) {
      alert('Download unavailable. Please take a screenshot instead.')
      return
    }
    setDownloading(true)
    try {
      await document.fonts.ready
      const canvas = await window.html2canvas(cardRef.current, {
        scale: 3,
        useCORS: true,
        backgroundColor: null,
        logging: false,
      })
      const link = document.createElement('a')
      link.download = `walk-into-wellness-week-${week.num}.png`
      link.href = canvas.toDataURL('image/png')
      link.click()
    } catch {
      alert('Could not generate the card. Try taking a screenshot instead.')
    }
    setDownloading(false)
  }

  return (
    <div className="card-view">
      <div className="container">
        <button className="back-btn" onClick={() => nav.week(week.num)}>← Week {week.num}</button>

        <div className="card-preview">
          <div className="share-card" ref={cardRef}>
            <div className="sc-top">
              <p className="sc-program">Walk Into Wellness</p>
              <p className="sc-by">Troy Morgan Coaching</p>
            </div>

            <div className="sc-week-block">
              <div className="sc-week-bg">{week.num}</div>
              <div className="sc-week-label">Week</div>
              <div className="sc-week-num-display display">{week.num}</div>
            </div>

            <div className="sc-content">
              <h2 className="sc-title">{week.title}</h2>
              <p className="sc-goal">{week.walkMins} minutes completed</p>
              <p className="sc-quote">"{week.keyMessage}"</p>
            </div>

            <div className="sc-bottom">
              <span className="sc-badge-pill">{week.badge}</span>
              <p className="sc-footer-text">Walk Into Wellness</p>
            </div>
          </div>
        </div>

        <button className="download-btn" onClick={handleDownload} disabled={downloading}>
          {downloading ? 'Generating...' : 'Download Share Card'}
        </button>
        <button className="home-btn" onClick={() => nav.home()}>Back to Programme</button>
      </div>
    </div>
  )
}

function ProgrammeCompleteView({ progress, nav, showToast }) {
  const cardRef = useRef(null)
  const [downloading, setDownloading] = useState(false)

  const w1Done = progress.w1?.completedAt
  const w4Done = progress.w4?.completedAt

  const hasJourney = !!(
    progress.w2?.ci_before?.scores &&
    progress.w2?.ci_after?.scores &&
    progress.w4?.ci_before?.scores &&
    progress.w4?.ci_after?.scores
  )

  const handleDownload = async () => {
    if (!window.html2canvas) {
      alert('Download unavailable. Please take a screenshot instead.')
      return
    }
    setDownloading(true)
    try {
      await document.fonts.ready
      const canvas = await window.html2canvas(cardRef.current, {
        scale: 3,
        useCORS: true,
        backgroundColor: null,
        logging: false,
      })
      const link = document.createElement('a')
      link.download = 'walk-into-wellness-complete.png'
      link.href = canvas.toDataURL('image/png')
      link.click()
    } catch {
      alert('Could not generate the card. Try taking a screenshot instead.')
    }
    setDownloading(false)
  }

  const handleStartAgain = async () => {
    if (!window.confirm('Reset all progress? This cannot be undone.')) return
    await Progress.reset()
    window.location.reload()
  }

  const handleShare = async () => {
    const url = window.location.href.split('?')[0]
    const text = "I just completed the Walk Into Wellness programme by Troy Morgan Coaching. Four weeks of building a walking habit, done."
    if (navigator.share) {
      try { await navigator.share({ title: 'Walk Into Wellness', text, url }) } catch {}
    } else {
      navigator.clipboard.writeText(`${text} ${url}`).then(() => showToast('Link copied'))
    }
  }

  return (
    <div className="programme-complete-view">
      <div className="container">
        <div className="pcv-header">
          <p className="eyebrow">Programme complete</p>
          <h1 className="pcv-headline display">You walked your way to wellness.</h1>
          {w1Done && w4Done && (
            <p className="pcv-dates">Started {fmtDate(w1Done)} · Completed {fmtDate(w4Done)}</p>
          )}
          <p className="pcv-stats">4 weeks. 4 milestones. One step at a time.</p>
        </div>

        <blockquote className="wv-message">"{WEEKS[3].keyMessage}"</blockquote>

        {hasJourney && (
          <JourneyComparison
            startScores={progress.w2.ci_before.scores}
            endScores={progress.w4.ci_after.scores}
          />
        )}

        <div className="card-preview">
          <div className="share-card programme-card" ref={cardRef}>
            <div className="pc-top">
              <p className="pc-program display">Walk Into Wellness</p>
              <p className="pc-complete-label eyebrow">Complete</p>
            </div>

            <div className="pc-timeline">
              {WEEKS.map(week => (
                <div key={week.num} className="pc-week-row">
                  <span className="pc-wk-num">Week {week.num}</span>
                  <span className="pc-wk-title">{week.title}</span>
                  <span className="pc-wk-check">✓</span>
                </div>
              ))}
            </div>

            <div className="pc-stat-row">
              <span className="pc-stat">4 Weeks</span>
              <span className="pc-stat-dot">·</span>
              <span className="pc-stat">210 min goal</span>
            </div>

            <div className="pc-bottom">
              <p className="pc-by">Troy Morgan Coaching</p>
              {w4Done && <p className="pc-date">{fmtDate(w4Done)}</p>}
            </div>
          </div>
        </div>

        <button className="download-btn" onClick={handleDownload} disabled={downloading}>
          {downloading ? 'Generating...' : 'Download Programme Card'}
        </button>
        <button className="lv-share-btn pcv-share-btn" onClick={handleShare}>
          Share this programme with a friend
        </button>
        <button className="start-again-btn" onClick={handleStartAgain}>
          Start again
        </button>
      </div>
    </div>
  )
}

// ── Root App ─────────────────────────────────────────────────────────────────

function App() {
  const [view, setView] = useState('landing')
  const [weekNum, setWeekNum] = useState(null)
  const [dayNum, setDayNum] = useState(null)
  const [checkInPhase, setCheckInPhase] = useState(null)
  const [progress, setProgress] = useState({})
  const [toast, setToast] = useState(null)

  useEffect(() => {
    Progress.get().then(setProgress)
  }, [])

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' })
  }, [view])

  const refresh = async () => {
    const p = await Progress.get()
    setProgress(p)
    return p
  }

  const showToast = (msg) => {
    setToast(msg)
    setTimeout(() => setToast(null), 2800)
  }

  const nav = {
    landing: () => { setView('landing') },
    home:    () => { setView('home') },
    complete:() => { setView('complete') },
    week:    num => { setWeekNum(num); setView('week') },
    day:     (wk, dy) => { setWeekNum(wk); setDayNum(dy); setView('day') },
    checkIn: (wk, phase) => { setWeekNum(wk); setCheckInPhase(phase); setView('checkin') },
    card:    wk => { setWeekNum(wk); setView('card') },
  }

  const allWeeksDone = WEEKS.every(w => progress[`w${w.num}`]?.completedAt)
  const resolvedView = (view === 'home' && allWeeksDone) ? 'complete' : view

  const week = WEEKS[weekNum - 1]
  const wp = progress[`w${weekNum}`]

  return (
    <div className="app">
      <Nav onLanding={nav.landing} />

      <main>
        {resolvedView === 'landing' && (
          <LandingView progress={progress} nav={nav} showToast={showToast} />
        )}
        {resolvedView === 'home' && (
          <HomeView progress={progress} nav={nav} />
        )}
        {resolvedView === 'complete' && (
          <ProgrammeCompleteView progress={progress} nav={nav} showToast={showToast} />
        )}
        {resolvedView === 'week' && week && (
          <WeekView
            week={week}
            weekProgress={wp}
            nav={nav}
            refresh={refresh}
            showToast={showToast}
          />
        )}
        {resolvedView === 'day' && week && (
          <DayView
            week={week}
            dayNum={dayNum}
            dayProgress={wp?.days?.[dayNum]}
            nav={nav}
            refresh={refresh}
            showToast={showToast}
          />
        )}
        {resolvedView === 'checkin' && week && (
          <CheckInView
            week={week}
            phase={checkInPhase}
            existing={wp?.[`ci_${checkInPhase}`]}
            nav={nav}
            refresh={refresh}
            showToast={showToast}
          />
        )}
        {resolvedView === 'card' && week && (
          <CardView week={week} nav={nav} />
        )}
      </main>

      {toast && <div className="toast">{toast}</div>}
    </div>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<App />)
