// Home screen — learning path (Duolingo-style skill tree) + top status bar
// Parcours construit dynamiquement à partir de window.LESSON_INDEX.

const UNIT_COLORS = ['#E07A3E', '#4A7A8C', '#5A8A3A', '#8C6B4A', '#6B3A7A', '#B8854A'];

// Construit la liste des unités pour un track donné.
function buildUnitsFromIndex(lang, progress, trackId) {
  if (!window.LESSON_INDEX) return [];
  const track = (trackId
    ? window.LESSON_INDEX.tracks.find((t) => t.id === trackId)
    : window.LESSON_INDEX.tracks[0]) || window.LESSON_INDEX.tracks[0];
  if (!track) return [];
  // La 1re unité du track hérite de la couleur du track ; les suivantes tournent dans la palette.
  const trackColor = track.color || UNIT_COLORS[0];
  return track.units.map((u, uIdx) => {
    const color = uIdx === 0 ? trackColor : UNIT_COLORS[uIdx % UNIT_COLORS.length];
    const doneCount = progress[u.id] || 0;
    const lessons = u.lessons.map((lessonId, i) => {
      const lesson = window.getLesson(lessonId);
      const isDone = i < doneCount;
      const isActive = i === doneCount;
      // Dernière leçon = "boss" (défi), avant-dernière = "practice", reste = "lesson"
      const type = i === u.lessons.length - 1 ? 'boss'
        : i === u.lessons.length - 2 ? 'practice'
        : 'lesson';
      return {
        id: lessonId,
        lessonId,
        type,
        title: lesson ? window.loc(lesson.title, lang) : lessonId,
        done: isDone,
        active: isActive,
        crowns: isDone ? Math.max(1, 4 - i) : undefined,
      };
    });
    return {
      id: u.id,
      order: u.order,
      title: window.loc(u.title, lang),
      subtitle: lessons[Math.max(0, doneCount)]?.title || lessons[0]?.title || '',
      color,
      lessons,
    };
  });
}

function HomeScreen({ theme, lang, onLessonClick, onTabClick, progress, goal, activeTrackId, setActiveTrackId, streak = 7, hearts = 4, gems = 1250, xp = 840 }) {
  // Progression reçue en prop (source : app.jsx) — fallback pour démo isolée.
  const resolvedProgress = progress || { u1: 4, u2: 0, u3: 0, u4: 0, u5: 0, f1: 0 };
  const tracks = (window.LESSON_INDEX && window.LESSON_INDEX.tracks) || [];
  const resolvedTrackId = activeTrackId || tracks[0]?.id;
  const units = buildUnitsFromIndex(lang, resolvedProgress, resolvedTrackId);
  const [scrolled, setScrolled] = React.useState(false);
  const goalLabels = {
    fr: { student: 'Étudiant·e · révisions', pro: 'Montée en compétence', entrepreneur: 'Freelance / TPE', curious: 'Par curiosité' },
    en: { student: 'Student · exam prep', pro: 'Level up skills', entrepreneur: 'Freelance / SME', curious: 'Just curious' },
  };
  const goalLabel = goal ? goalLabels[lang][goal] : null;

  return (
    <div style={{ height: '100%', background: theme.bg, display: 'flex', flexDirection: 'column' }}>
      {/* top status bar */}
      <div style={{
        padding: '60px 16px 12px', background: theme.bg,
        borderBottom: scrolled ? `1px solid ${theme.border}` : '1px solid transparent',
        display: 'flex', alignItems: 'center', gap: 10, zIndex: 10,
      }}>
        <StatPill icon="flag" value="FR" theme={theme}/>
        <div style={{ flex: 1 }}/>
        <StatPill icon="flame" value={streak} color="#FF9500" theme={theme}/>
        <StatPill icon="gem" value={gems} color="#00B4E6" theme={theme}/>
        <StatPill icon="heart" value={hearts} color="#FF4B4B" theme={theme}/>
      </div>
      {/* goal banner (set by onboarding) */}
      {goalLabel && (
        <div style={{
          margin: '4px 16px 0', padding: '6px 12px', borderRadius: 10,
          background: theme.primarySoft, color: theme.primaryDark,
          fontFamily: theme.fontBody, fontSize: 11, fontWeight: 800,
          letterSpacing: 0.5, textTransform: 'uppercase', textAlign: 'center',
        }}>🎯 {goalLabel}</div>
      )}
      {/* track switcher — visible dès qu'il y a plus d'un parcours */}
      {tracks.length > 1 && (
        <div style={{
          display: 'flex', gap: 6, padding: '8px 16px 4px',
          overflowX: 'auto', WebkitOverflowScrolling: 'touch',
        }}>
          {tracks.map((t) => {
            const active = t.id === resolvedTrackId;
            const tcolor = t.color || theme.primary;
            return (
              <button key={t.id}
                onClick={() => setActiveTrackId && setActiveTrackId(t.id)}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '6px 12px', borderRadius: 999, border: 'none', cursor: 'pointer',
                  background: active ? tcolor : theme.surface,
                  color: active ? '#fff' : theme.ink,
                  boxShadow: active ? `0 2px 0 ${shadeColor(tcolor, -20)}` : `0 2px 0 ${theme.border}`,
                  fontFamily: theme.fontBody, fontSize: 12, fontWeight: 800,
                  whiteSpace: 'nowrap',
                }}
              >
                {t.icon && <span style={{ fontSize: 14 }}>{t.icon}</span>}
                {window.loc(t.title, lang)}
              </button>
            );
          })}
        </div>
      )}

      {/* scrollable path */}
      <div
        onScroll={(e) => setScrolled(e.target.scrollTop > 10)}
        style={{ flex: 1, overflow: 'auto', paddingBottom: 110 }}
      >
        {units.map((unit, uIdx) => (
          <div key={unit.id} style={{ marginTop: uIdx === 0 ? 0 : 24 }}>
            {/* unit banner */}
            <div style={{
              margin: '12px 16px 20px', padding: '14px 18px',
              background: unit.color, borderRadius: theme.radius,
              color: '#fff', boxShadow: `0 4px 0 ${shadeColor(unit.color, -20)}`,
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div>
                <div style={{ fontFamily: theme.fontBody, fontSize: 12, fontWeight: 700, letterSpacing: 0.5, opacity: 0.9, textTransform:'uppercase' }}>
                  {lang==='fr'?'Unit\u00e9':'Unit'} {unit.order}
                </div>
                <div style={{ fontFamily: theme.font, fontSize: 20, fontWeight: theme.headingWeight, marginTop: 2 }}>
                  {unit.title.split('—')[1]?.trim() || unit.subtitle}
                </div>
              </div>
              <div style={{ flex: 1 }}/>
              <div style={{
                width: 36, height: 36, borderRadius: 8,
                background: 'rgba(255,255,255,0.2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                cursor: 'pointer',
              }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5">
                  <path d="M4 19h16M4 12h16M4 5h16"/>
                </svg>
              </div>
            </div>

            {/* skill nodes zig-zag */}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
              {unit.lessons.map((l, i) => {
                const offset = Math.sin(i * 0.8) * 60;
                return (
                  <div key={l.id} style={{
                    transform: `translateX(${offset}px)`,
                    display: 'flex', flexDirection: 'column', alignItems: 'center',
                  }}>
                    <SkillNode lesson={l} theme={theme} unitColor={unit.color} onClick={() => onLessonClick(l)}/>
                  </div>
                );
              })}
            </div>
          </div>
        ))}

        {/* end of path */}
        <div style={{ textAlign: 'center', padding: '40px 24px', color: theme.inkSoft, fontFamily: theme.fontBody, fontSize: 13 }}>
          {lang==='fr'?'Plus de contenu arrive bient\u00f4t \u2728':'More content coming soon \u2728'}
        </div>
      </div>

      {/* floating Milo companion */}
      <FloatingMilo theme={theme} lang={lang}/>

      {/* bottom tab bar */}
      <BottomTabs theme={theme} active="home" onTabClick={onTabClick}/>
    </div>
  );
}

function SkillNode({ lesson, theme, unitColor, onClick }) {
  const done = lesson.done;
  const active = lesson.active;
  const locked = !done && !active;

  const bg = done ? unitColor : active ? '#fff' : theme.muted;
  const border = done ? shadeColor(unitColor, -20) : active ? unitColor : theme.border;
  const iconColor = done ? '#fff' : active ? unitColor : '#B0A79A';

  let icon;
  if (lesson.type === 'boss') {
    icon = <svg width="28" height="28" viewBox="0 0 24 24" fill={iconColor}><path d="M4 3l2 6h12l2-6-4 4-4-6-4 6-4-4zm0 8h16l-1 10H5z"/></svg>;
  } else if (lesson.type === 'practice') {
    icon = <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={iconColor} strokeWidth="2.5"><path d="M9 11l3 3L22 4M20 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2h11"/></svg>;
  } else {
    icon = <svg width="28" height="28" viewBox="0 0 24 24" fill={iconColor}><path d="M12 2l3 6 6 1-4.5 4.5L18 20l-6-3-6 3 1.5-6.5L3 9l6-1z"/></svg>;
  }

  return (
    <div style={{ padding: '8px 0', textAlign: 'center' }}>
      {active && (
        <div style={{
          background: theme.ink, color: '#fff',
          padding: '4px 12px', borderRadius: 6,
          fontFamily: theme.fontBody, fontSize: 11, fontWeight: 800,
          letterSpacing: 1, textTransform: 'uppercase',
          position: 'relative', marginBottom: 4, display: 'inline-block',
        }}>
          START
          <div style={{
            position: 'absolute', bottom: -5, left: '50%', transform: 'translateX(-50%)',
            width: 0, height: 0, borderLeft: '5px solid transparent', borderRight: '5px solid transparent',
            borderTop: `5px solid ${theme.ink}`,
          }}/>
        </div>
      )}
      <button onClick={onClick} disabled={locked} style={{
        width: 74, height: 74, borderRadius: '50%',
        background: bg, border: `3px solid ${border}`,
        boxShadow: locked ? 'none' : `0 6px 0 ${border}`,
        cursor: locked ? 'not-allowed' : 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative', padding: 0,
        opacity: locked ? 0.6 : 1,
        animation: active ? 'nodePulse 2s ease-in-out infinite' : 'none',
      }}>
        {locked ? (
          <svg width="24" height="24" viewBox="0 0 24 24" fill="#B0A79A"><path d="M6 10V7a6 6 0 0112 0v3h1a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2v-9a2 2 0 012-2h1zm2 0h8V7a4 4 0 00-8 0v3z"/></svg>
        ) : icon}
        {/* crown indicator */}
        {done && lesson.crowns && (
          <div style={{
            position: 'absolute', bottom: -6, left: '50%', transform: 'translateX(-50%)',
            background: theme.gold, padding: '2px 8px', borderRadius: 8,
            fontSize: 11, fontWeight: 800, color: theme.ink,
            fontFamily: theme.fontBody,
            display: 'flex', alignItems: 'center', gap: 2,
            border: `2px solid ${shadeColor(theme.gold, -15)}`,
          }}>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M3 20h18l-2-10-4 3-5-6-5 6-4-3z"/></svg>
            {lesson.crowns}
          </div>
        )}
      </button>
      <style>{`@keyframes nodePulse{0%,100%{transform:scale(1)}50%{transform:scale(1.05)}}`}</style>
    </div>
  );
}

function StatPill({ icon, value, color, theme }) {
  const iconEl = {
    flame: <FlameIcon size={18}/>,
    heart: <HeartIcon size={18}/>,
    gem: <GemIcon size={18}/>,
    flag: <div style={{ width: 22, height: 14, borderRadius: 2, overflow: 'hidden', display: 'flex' }}>
      <div style={{ flex: 1, background: '#0055A4' }}/>
      <div style={{ flex: 1, background: '#fff' }}/>
      <div style={{ flex: 1, background: '#EF4135' }}/>
    </div>,
  }[icon];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      fontFamily: theme.fontBody, fontWeight: 800,
      color: color || theme.ink, fontSize: 16,
    }}>
      {iconEl}
      {value !== undefined && <span>{value}</span>}
    </div>
  );
}

function BottomTabs({ theme, active, onTabClick }) {
  const tabs = [
    { k: 'home', label: 'Leçon', icon: (c) => <svg width="26" height="26" viewBox="0 0 24 24" fill={c}><path d="M12 2L2 12h3v8h14v-8h3L12 2z"/></svg> },
    { k: 'tracks', label: 'Parcours', icon: (c) => <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.5" strokeLinecap="round"><path d="M4 7h16M4 12h10M4 17h16"/><circle cx="18" cy="12" r="2" fill={c}/></svg> },
    { k: 'catalog', label: 'Cours', icon: (c) => <svg width="26" height="26" viewBox="0 0 24 24" fill={c}><path d="M4 4h16v4H4zM4 10h16v4H4zM4 16h16v4H4z"/></svg> },
    { k: 'league', label: 'Ligue', icon: (c) => <svg width="26" height="26" viewBox="0 0 24 24" fill={c}><path d="M7 3h10v2h3v4a5 5 0 01-3.5 4.8A5 5 0 0113 17v2h3v2H8v-2h3v-2a5 5 0 01-3.5-3.2A5 5 0 014 9V5h3V3z"/></svg> },
    { k: 'profile', label: 'Profil', icon: (c) => <svg width="26" height="26" viewBox="0 0 24 24" fill={c}><circle cx="12" cy="8" r="4"/><path d="M4 22c0-4 4-7 8-7s8 3 8 7"/></svg> },
  ];
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 20,
      background: theme.surface, borderTop: `1px solid ${theme.border}`,
      display: 'flex', padding: '8px 4px 30px',
    }}>
      {tabs.map(t => {
        const act = active === t.k;
        return (
          <button key={t.k} onClick={() => onTabClick(t.k)} style={{
            flex: 1, background: 'transparent', border: 'none',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            padding: '8px 0', cursor: 'pointer',
            color: act ? theme.primary : theme.inkSoft,
          }}>
            {t.icon(act ? theme.primary : '#A0A0A0')}
            <span style={{ fontSize: 10, fontWeight: 700, fontFamily: theme.fontBody, letterSpacing: 0.3 }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

function FloatingMilo({ theme, lang }) {
  const [open, setOpen] = React.useState(false);
  const tip = lang==='fr'
    ? 'Psst ! Plus que 2 le\u00e7ons pour terminer l\u2019Unit\u00e9 1 \ud83d\udd25'
    : 'Psst! Only 2 lessons to finish Unit 1 \ud83d\udd25';
  return (
    <div style={{ position: 'absolute', right: 12, bottom: 96, zIndex: 15 }}>
      {open && (
        <div style={{
          position: 'absolute', right: 68, bottom: 8, width: 200,
          background: theme.surface, border: `2px solid ${theme.border}`,
          borderRadius: 14, padding: '10px 12px',
          fontFamily: theme.fontBody, fontSize: 13, color: theme.ink,
          boxShadow: `0 2px 0 ${theme.border}`,
        }}>
          {tip}
          <div style={{
            position: 'absolute', right: -9, bottom: 16,
            width: 0, height: 0,
            borderLeft: `10px solid ${theme.surface}`,
            borderTop: '8px solid transparent',
            borderBottom: '8px solid transparent',
          }}/>
        </div>
      )}
      <button onClick={() => setOpen(!open)} style={{
        width: 64, height: 64, borderRadius: '50%',
        background: theme.surface, border: `3px solid ${theme.primary}`,
        boxShadow: `0 4px 0 ${theme.primaryDark}`,
        padding: 0, cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <MiloHead size={52} emotion="happy"/>
      </button>
    </div>
  );
}

function shadeColor(hex, percent) {
  const f = parseInt(hex.slice(1), 16);
  const t = percent < 0 ? 0 : 255;
  const p = Math.abs(percent) / 100;
  const R = f >> 16, G = (f >> 8) & 0x00FF, B = f & 0x0000FF;
  return '#' + (0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 + (Math.round((t - G) * p) + G) * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1);
}

Object.assign(window, { HomeScreen, SkillNode, StatPill, BottomTabs, FloatingMilo, shadeColor });
