// mobile.jsx — mobile-friendly screens

function MobScreen({ children, title, eyebrow }) {
  return (
    <div style={{ padding: '60px 16px 100px', height: '100%', overflowY: 'auto', WebkitOverflowScrolling: 'touch' }}>
      {eyebrow && <div className="eyebrow" style={{ fontSize: 10 }}>{eyebrow}</div>}
      {title && <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 28, letterSpacing: '-0.02em', lineHeight: 1.1, margin: '6px 0 16px' }}>{title}</div>}
      {children}
    </div>
  );
}

function MobDashboard({ state, dispatch }) {
  const habits = state.habits;
  const doneToday = habits.filter(h => h.doneToday).length;
  return (
    <MobScreen eyebrow="Понедельник, 12 мая" title="Привет, Аня">
      {/* Mascot strip — clickable to open picker */}
      <div className="card mb-3" style={{ padding: 14, display: 'flex', gap: 14, alignItems: 'center', overflow: 'hidden', position: 'relative' }}
           onClick={() => dispatch('openMascotPicker')}>
        <Mascot id={state.mascotId} emotion={state.mascotEmotion} size={70} level={ME.level} aura />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="eyebrow" style={{ fontSize: 10 }}>Твой компаньон</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17, letterSpacing: '-0.01em', marginTop: 2 }}>
            {(MASCOT_BY_ID[state.mascotId] || MASCOTS[0]).name}
          </div>
          <div className="dim" style={{ fontSize: 11.5, marginTop: 2 }}>
            {(MASCOT_BY_ID[state.mascotId] || MASCOTS[0]).power}
          </div>
        </div>
        <div className="dim mono" style={{ fontSize: 11 }}>сменить →</div>
      </div>
      {/* Compact XP */}
      <div className="card mb-3" style={{ padding: 14 }}>
        <div className="spread mb-3">
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14 }}>{PROGRESSION.names[ME.level]}</div>
            <div className="dim mono" style={{ fontSize: 11 }}>LVL {ME.level} · 1820 / 2300 XP</div>
          </div>
          <div className="row" style={{ gap: 10 }}>
            <div className="row" style={{ gap: 4, color: 'var(--gold)' }}><Icon.fire /> <b className="mono" style={{fontSize: 14}}>23</b></div>
          </div>
        </div>
        <div className="xp-bar"><i style={{ width: '38%' }} /></div>
      </div>

      {/* 2x4 zones compact */}
      <div className="eyebrow mb-2">Баланс жизни</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, marginBottom: 16 }}>
        {ZONES.map(z => {
          const v = state.wheel.current[z.id];
          const t = state.wheel.target[z.id];
          return (
            <div key={z.id} className={`zone-tile ${z.cls}`} style={{ padding: 11 }}>
              <div className="row" style={{ justifyContent: 'space-between', alignItems: 'center' }}>
                <div className="row" style={{ gap: 8 }}>
                  <span style={{ fontSize: 18 }}>{z.icon}</span>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 12.5 }}>{z.name}</div>
                    <div className="dim mono" style={{ fontSize: 10 }}>{v} / {t}</div>
                  </div>
                </div>
                <ProgressRing value={v / 10} size={36} stroke={4} color={z.color} label={v} />
              </div>
            </div>
          );
        })}
      </div>

      {/* Today's habits */}
      <div className="spread mb-2">
        <div className="ttl-md">Привычки · {doneToday}/{habits.length}</div>
        <span className="dim mono" style={{ fontSize: 11 }}>сегодня</span>
      </div>
      <div className="card" style={{ padding: 6 }}>
        {habits.map((h, i) => {
          const z = ZONE_BY_ID[h.zone];
          return (
            <div key={h.id} className={`row ${z.cls}`}
                 onClick={() => dispatch('toggleHabit', h.id)}
                 style={{ padding: '10px 10px', gap: 12, borderBottom: i < habits.length - 1 ? '1px solid var(--border-subtle)' : 'none' }}>
              <button className={`check-btn ${h.doneToday ? 'done' : ''}`} style={{ width: 28, height: 28 }}>
                {h.doneToday && <Icon.check />}
              </button>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.2 }}>{h.title}</div>
                <div className="row mt-2" style={{ gap: 8 }}>
                  <ZoneChip zone={z} sm />
                  <span className="mono" style={{ fontSize: 11, color: 'var(--gold)' }}><Icon.fire style={{ verticalAlign: '-2px' }} /> {h.streak}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Activity feed */}
      <div className="ttl-md mt-4 mb-2">Активность</div>
      <div className="card">
        {FEED.slice(0, 4).map(f => {
          const u = USER_BY_ID[f.who];
          return (
            <div key={f.id} className="feed-item">
              <Avatar user={u} size="sm" />
              <div className="body">
                <div style={{ fontSize: 12.5 }}>
                  <strong>{u.name}</strong>{' '}
                  <span dangerouslySetInnerHTML={{ __html: f.text }} />
                </div>
                <div className="when mt-2">{f.when}</div>
              </div>
            </div>
          );
        })}
      </div>
    </MobScreen>
  );
}

function MobWishes({ state, dispatch }) {
  const [activeZone, setActiveZone] = React.useState('all');
  const list = activeZone === 'all' ? state.wishes : state.wishes.filter(w => w.zone === activeZone);
  return (
    <MobScreen eyebrow="Карта желаний · 18 целей" title="Желания">
      {/* Zone filter chips */}
      <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 12, marginBottom: 12, marginLeft: -16, paddingLeft: 16, marginRight: -16, paddingRight: 16 }}>
        <button onClick={() => setActiveZone('all')}
          className="chip"
          style={{
            background: activeZone === 'all' ? 'var(--accent)' : 'var(--bg-card)',
            color: activeZone === 'all' ? '#fff' : 'var(--text-secondary)',
            borderColor: activeZone === 'all' ? 'var(--accent)' : 'var(--border)',
            flexShrink: 0, fontSize: 12.5, padding: '6px 12px',
          }}>Все · {state.wishes.length}</button>
        {ZONES.map(z => {
          const cnt = state.wishes.filter(w => w.zone === z.id).length;
          return (
            <button key={z.id} onClick={() => setActiveZone(z.id)}
              className={`chip ${z.cls}`}
              style={{
                flexShrink: 0, fontSize: 12.5, padding: '6px 12px',
                background: activeZone === z.id ? z.color : undefined,
                color: activeZone === z.id ? '#fff' : undefined,
              }}>{z.icon} {z.name} · {cnt}</button>
          );
        })}
      </div>

      <div className="col" style={{ gap: 10 }}>
        {list.map(w => <WishCard key={w.id} wish={w} draggable={false} />)}
      </div>
    </MobScreen>
  );
}

function MobWheel({ state, dispatch }) {
  const overall = ZONES.reduce((s, z) => s + state.wheel.current[z.id], 0) / 8;
  return (
    <MobScreen eyebrow="Колесо баланса" title="Оцени баланс">
      <div className="card" style={{ display: 'grid', placeItems: 'center', padding: 12, position: 'relative' }}>
        <LifeWheel size={300} current={state.wheel.current} target={state.wheel.target} />
        <div style={{ position: 'absolute', top: 12, right: 16 }}>
          <ProgressRing value={overall / 10} size={50} stroke={5} color="var(--accent)" label={overall.toFixed(1)} sub="/ 10" />
        </div>
      </div>

      <div className="card mt-3">
        <div className="ttl-md mb-3">Слайдеры</div>
        {ZONES.map(z => {
          const v = state.wheel.current[z.id];
          return (
            <div key={z.id} style={{ marginBottom: 12 }}>
              <div className="spread mb-2">
                <div className="row" style={{ gap: 8 }}>
                  <span style={{ color: z.color, fontSize: 14 }}>{z.icon}</span>
                  <span style={{ fontWeight: 500, fontSize: 13.5 }}>{z.name}</span>
                </div>
                <span className="mono" style={{ color: z.color, fontWeight: 700, fontSize: 13 }}>{v}</span>
              </div>
              <input type="range" min="1" max="10" value={v}
                onChange={(e) => dispatch('wheel', { zone: z.id, value: Number(e.target.value) })}
                style={{
                  width: '100%', height: 4, appearance: 'none', WebkitAppearance: 'none',
                  background: `linear-gradient(90deg, ${z.color} 0%, ${z.color} ${v * 10}%, var(--border) ${v * 10}%, var(--border) 100%)`,
                  borderRadius: 2, outline: 'none',
                }} />
            </div>
          );
        })}
      </div>
      <button className="btn primary mt-3" style={{ width: '100%', justifyContent: 'center' }}>Сохранить снимок</button>
    </MobScreen>
  );
}

function MobHabits({ state, dispatch }) {
  const habits = state.habits;
  const doneToday = habits.filter(h => h.doneToday).length;
  return (
    <MobScreen eyebrow="Трекер привычек" title="Привычки">
      <div className="row mb-3" style={{ gap: 8 }}>
        <div className="card" style={{ flex: 1, padding: 12, textAlign: 'center' }}>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: 'var(--gold)' }}><Icon.fire /> 23</div>
          <div className="dim" style={{ fontSize: 10.5 }}>лучший стрик</div>
        </div>
        <div className="card" style={{ flex: 1, padding: 12, textAlign: 'center' }}>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: 'var(--success)' }}>{doneToday}/{habits.length}</div>
          <div className="dim" style={{ fontSize: 10.5 }}>сегодня</div>
        </div>
        <div className="card" style={{ flex: 1, padding: 12, textAlign: 'center' }}>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: 'var(--accent-2)' }}>79%</div>
          <div className="dim" style={{ fontSize: 10.5 }}>за месяц</div>
        </div>
      </div>

      <div className="col" style={{ gap: 10 }}>
        {habits.map((h, i) => {
          const z = ZONE_BY_ID[h.zone];
          return (
            <div key={h.id} className={`card ${z.cls}`}>
              <div className="spread mb-2">
                <div className="row" style={{ gap: 10, flex: 1 }}>
                  <button className={`check-btn ${h.doneToday ? 'done' : ''}`} onClick={() => dispatch('toggleHabit', h.id)}>
                    {h.doneToday && <Icon.check />}
                  </button>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>{h.title}</div>
                    <div className="row mt-2" style={{ gap: 8 }}>
                      <ZoneChip zone={z} sm />
                      <span className="mono dim" style={{ fontSize: 11 }}><Icon.fire style={{ verticalAlign: '-2px', color: 'var(--gold)' }} /> {h.streak} / {h.longest}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div style={{ overflowX: 'auto' }}>
                <Heatmap data={state.heat[i].slice(-182)} zone={h.zone} compact />
              </div>
            </div>
          );
        })}
      </div>
    </MobScreen>
  );
}

function MobMatrix({ state, dispatch }) {
  const quads = [
    { id: 'q1', label: 'Сделать сейчас',   sub: 'Срочно · Важно',     cls: 'q1' },
    { id: 'q2', label: 'Запланировать',     sub: 'Не срочно · Важно',  cls: 'q2' },
    { id: 'q3', label: 'Делегировать',      sub: 'Срочно · Не важно',  cls: 'q3' },
    { id: 'q4', label: 'Отложить',          sub: 'Не срочно · Не важно', cls: 'q4' },
  ];
  return (
    <MobScreen eyebrow="Матрица Эйзенхауэра" title="Приоритеты">
      <div className="col" style={{ gap: 10 }}>
        {quads.map(q => {
          const items = state.priorities.filter(p => p.quad === q.id);
          return (
            <div key={q.id} className={`quad ${q.cls}`} style={{ height: 'auto', padding: 12 }}>
              <div className="qh mb-2">
                <div>
                  <div className="ql">{q.label}</div>
                  <div className="qm">{q.sub}</div>
                </div>
                <div className="qcount">{items.length}</div>
              </div>
              <div className="col" style={{ gap: 6 }}>
                {items.map(p => {
                  const w = WISHES.find(x => x.id === p.wid);
                  if (!w) return null;
                  const z = ZONE_BY_ID[w.zone];
                  return (
                    <div key={p.id} className={`mini-wish ${z.cls}`}>
                      <span>{w.cover}</span>
                      <span style={{ flex: 1 }}>{w.title}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </MobScreen>
  );
}

function MobProfile({ state, dispatch }) {
  const earned = BADGES.filter(b => b.earned);
  const locked = BADGES.filter(b => !b.earned);
  return (
    <MobScreen eyebrow="Профиль">
      <div className="profile-hero" style={{ flexDirection: 'column', textAlign: 'center', padding: 18, gap: 10 }}>
        <Avatar user={ME} size="xl" ring />
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 }}>{ME.full}</div>
          <div className="row mt-2" style={{ gap: 6, justifyContent: 'center' }}>
            <span className="lvl-pill">LVL {ME.level}</span>
            <span className="chip" style={{ '--zc': 'var(--gold)', background: 'rgba(245,166,35,0.15)', color: 'var(--gold-2)' }}>
              <Icon.fire /> 23
            </span>
          </div>
        </div>
        <div style={{ width: '100%' }}>
          <XPBar />
        </div>
      </div>

      <div className="ttl-md mt-3 mb-2">Бейджи · {earned.length}/{BADGES.length}</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
        {[...earned, ...locked].slice(0, 12).map(b => <BadgeCell key={b.id} badge={b} />)}
      </div>

      <div className="ttl-md mt-4 mb-2">Рейтинг недели</div>
      <div className="card">
        {LEADER.map((row, i) => {
          const u = USER_BY_ID[row.user];
          return (
            <div key={u.id} className="row" style={{ padding: '10px 4px', gap: 10, borderBottom: i < LEADER.length - 1 ? '1px solid var(--border-subtle)' : 'none' }}>
              <div className="mono" style={{ width: 18, fontWeight: 700, color: i === 0 ? 'var(--gold)' : 'var(--text-tertiary)' }}>{i + 1}</div>
              <Avatar user={u} size="sm" />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: u.id === ME.id ? 700 : 500, fontSize: 13.5 }}>{u.name}</div>
              </div>
              <span className="mono" style={{ fontWeight: 600 }}>{row.xp}</span>
            </div>
          );
        })}
      </div>

      <button className="btn primary mt-4" style={{ width: '100%', justifyContent: 'center' }}
              onClick={() => dispatch('showBadge', BADGES[10])}>
        ⚡ Показать получение бейджа
      </button>
    </MobScreen>
  );
}

// Bottom nav
function MobBottomNav({ active, onChange }) {
  const items = [
    { id: 'dashboard',  label: 'Главная',   icon: Icon.dashboard },
    { id: 'wishes',     label: 'Желания',   icon: Icon.map },
    { id: 'habits',     label: 'Привычки',  icon: Icon.habits },
    { id: 'collection', label: 'Герои',     icon: Icon.star },
    { id: 'profile',    label: 'Профиль',   icon: Icon.profile },
  ];
  return (
    <div className="btm-nav">
      {items.map(it => (
        <div key={it.id} className={`nav ${active === it.id ? 'active' : ''}`} onClick={() => onChange(it.id)}>
          {it.icon()}
          <span>{it.label}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  MobDashboard, MobWishes, MobWheel, MobHabits, MobMatrix, MobProfile,
  MobBottomNav, MobScreen,
});
