/* app.jsx — shell: sidebar, topbar, routing, tweaks */

const NAV = [
  { id: "dashboard", label: "Dashboard", icon: "grid" },
  { id: "courses", label: "Courses", icon: "stack" },
  { id: "uploads", label: "Presentations", icon: "pptx" },
  { id: "passport", label: "Skills Passport", icon: "passport" },
  { id: "reader", label: "Reader", icon: "book" },
  { id: "achievements", label: "Achievements", icon: "trophy" },
];

function Sidebar({ route, go, deep }) {
  const { lang } = useLang();
  const TL = T[lang] || T.en;
  return (
    <nav className="rail">
      <div style={{ padding: "20px 16px 16px", display: "flex", alignItems: "center", gap: 11 }}>
        <HexMark size={34} />
        <div className="rail-wordmark">
          <Logo height={20} white={deep} />
          <div className="dim" style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".18em", textTransform: "uppercase", marginTop: 3 }}>Learning</div>
        </div>
      </div>
      <div style={{ height: 1, background: "var(--rail-border)", margin: "4px 16px 12px" }} />
      <div style={{ display: "flex", flexDirection: "column", gap: 4, padding: "0 13px", flex: 1 }}>
        {NAV.map(n => (
          <button key={n.id} className={"nav-item" + (route === n.id || (route === "course" && n.id === "courses") ? " active" : "")} onClick={() => go(n.id)}>
            <span className="nav-ico"><Icon name={n.icon} size={21} /></span>
            <span className="lbl">{TL.nav[n.id] || n.label}</span>
          </button>
        ))}
      </div>
      <LangPicker />
      <div className="rail-foot-full" style={{ padding: "8px 13px 16px" }}>
        <div style={{ height: 1, background: "var(--rail-border)", marginBottom: 12 }} />
        <button
          onClick={() => window.location.href = "Login.html"}
          className="nav-item"
          style={{ width: "100%", color: "var(--rail-ink-dim)", opacity: .75 }}
          onMouseEnter={e => { e.currentTarget.style.opacity = 1; e.currentTarget.style.color = "#f87171"; }}
          onMouseLeave={e => { e.currentTarget.style.opacity = .75; e.currentTarget.style.color = "var(--rail-ink-dim)"; }}>
          <span className="nav-ico"><Icon name="chevL" size={20} /></span>
          <span className="lbl">{TL.logout}</span>
        </button>
      </div>
    </nav>
  );
}

function Topbar({ t, toast }) {
  const { lang } = useLang();
  const TL = T[lang] || T.en;
  return (
    <header className="topbar">
      <label className="search">
        <Icon name="search" size={18} />
        <input placeholder={TL.search} />
      </label>
      <div style={{ flex: 1 }} />
      <span className="streak"><Icon name="flame" size={16} />{TL.streak(LEARNER.streak)}</span>
      <Points value={LEARNER.xp} pointsStyle={t.pointsStyle} icon="bolt" />
      <button className="icon-btn" onClick={() => toast && toast("You're all caught up — no new notifications", "bell")}><Icon name="bell" size={21} /></button>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div className="avatar">{LEARNER.initials}</div>
        <div style={{ lineHeight: 1.2 }} className="rail-foot-full">
          <div style={{ fontWeight: 700, fontSize: 13.5 }}>{LEARNER.name}</div>
          <div className="dim" style={{ fontSize: 11.5 }}>{LEARNER.role}</div>
        </div>
      </div>
    </header>
  );
}

/* ---- Courses grid ---- */
function Courses({ t, openCourse }) {
  const { lang } = useLang();
  const TL = T[lang] || T.en;
  const [filter, setFilter] = useState("all"); // all | reco | done
  const [track, setTrack] = useState("All");

  const current = COURSES.filter(c => c.progress > 0 && c.progress < 100);
  const completed = COURSES.filter(c => c.progress === 100);
  const reco = (() => {
    const notStarted = COURSES.filter(c => c.progress === 0);
    const topId = recommendNext().course.id;
    return [...notStarted.filter(c => c.id === topId), ...notStarted.filter(c => c.id !== topId)];
  })();

  const tracks = ["All", ...Array.from(new Set(COURSES.map(c => c.track)))];
  const filters = [
    { key: "all", label: "All courses", icon: "layers", count: COURSES.length },
    { key: "reco", label: "Recommended for you", icon: "sparkle", count: reco.length },
    { key: "done", label: "Completed", icon: "checkCircle", count: completed.length },
  ];
  const list = filter === "done" ? completed
    : filter === "reco" ? reco
    : (track === "All" ? COURSES : COURSES.filter(c => c.track === track));

  return (
    <div className="vh-in">
      <PageHead eyebrow={TL.pages.courses.eyebrow} title={TL.pages.courses.title} sub={TL.pages.courses.sub} />

      {/* Current courses — continue where you left off (like the dashboard) */}
      {current.length > 0 && (
        <div style={{ marginBottom: 30 }}>
          <div className="between" style={{ marginBottom: 14 }}>
            <h2 style={{ fontSize: 19, fontWeight: 700, display: "flex", alignItems: "center", gap: 9 }}><Icon name="rocket" size={18} style={{ color: "var(--accent)" }} />Current courses</h2>
            <span className="dim" style={{ fontSize: 12.5, fontWeight: 600 }}>{current.length} in progress</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
            {current.map(c => <CourseCard key={c.id} c={c} t={t} onOpen={() => openCourse(c)} />)}
          </div>
        </div>
      )}

      {/* Filter: All / Recommended / Completed */}
      <div style={{ borderTop: "1px solid var(--line)", paddingTop: 22 }}>
        <div style={{ display: "flex", gap: 8, marginBottom: 16, flexWrap: "wrap" }}>
          {filters.map(f => (
            <button key={f.key} className={"tag" + (filter === f.key ? " accent" : "")} onClick={() => setFilter(f.key)} style={{ cursor: "pointer", fontSize: 12.5, padding: "8px 15px", gap: 6 }}>
              <Icon name={f.icon} size={14} />{f.label}<span style={{ opacity: .55, fontWeight: 700 }}>{f.count}</span>
            </button>
          ))}
        </div>

        {filter === "all" && (
          <div style={{ display: "flex", gap: 8, marginBottom: 20, flexWrap: "wrap" }}>
            {tracks.map(tr => <button key={tr} className={"tag" + (track === tr ? " accent" : "")} onClick={() => setTrack(tr)} style={{ cursor: "pointer", fontSize: 12, padding: "6px 12px", opacity: track === tr ? 1 : .82 }}>{tr}</button>)}
          </div>
        )}
        {filter === "reco" && <p className="muted" style={{ fontSize: 13.5, marginBottom: 18 }}>Picked from your skills profile — your weakest competency comes first.</p>}

        {list.length > 0 ? (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
            {list.map(c => <CourseCard key={c.id} c={c} t={t} onOpen={() => openCourse(c)} />)}
          </div>
        ) : (
          <p className="muted" style={{ fontSize: 14, padding: "30px 0", textAlign: "center" }}>Nothing here yet.</p>
        )}
      </div>
    </div>
  );
}

/* ---- Achievements ---- */
function Achievements({ t, toast }) {
  const { lang } = useLang();
  const TL = T[lang] || T.en;
  const got = BADGES.filter(b => b.got).length;
  const pct = Math.round((LEARNER.xp / LEARNER.xpToNext) * 100);
  return (
    <div className="vh-in">
      <PageHead eyebrow={TL.pages.achievements.eyebrow} title={TL.pages.achievements.title}
        sub={TL.pages.achievements.sub} />

      {/* level banner */}
      <div className="card" style={{ padding: 24, marginBottom: 22, display: "flex", alignItems: "center", gap: 26, flexWrap: "wrap" }}>
        <Ring value={pct} size={92} stroke={9} color="var(--accent)">
          <div style={{ textAlign: "center", lineHeight: 1 }}>
            <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 30 }}>{LEARNER.level}</div>
            <div className="dim" style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".14em" }}>LEVEL</div>
          </div>
        </Ring>
        <div style={{ flex: 1, minWidth: 220 }}>
          <h2 style={{ fontSize: 22, fontWeight: 700 }}>{LEARNER.levelName}</h2>
          <p className="muted" style={{ fontSize: 14, marginTop: 4 }}>{(LEARNER.xpToNext - LEARNER.xp).toLocaleString()} XP to <b>Level {LEARNER.level + 1}</b></p>
          <div className="bar" style={{ marginTop: 12, height: 11 }}><i style={{ width: pct + "%", background: "linear-gradient(90deg,var(--vh-peach),var(--accent))" }} /></div>
        </div>
        <div style={{ display: "flex", gap: 26 }}>
          {[["Badges", got + "/" + BADGES.length, "medal"], ["Rank", "#" + LEARNER.rank, "trophy"], ["Streak", LEARNER.streak + "d", "flame"]].map(([k, v, ic]) => (
            <div key={k} style={{ textAlign: "center" }}>
              <Icon name={ic} size={20} style={{ color: "var(--accent)" }} />
              <div className="kpi" style={{ fontSize: 26, marginTop: 5 }}>{v}</div>
              <div className="dim" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".05em" }}>{k}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Prizes & Awards ────────────────────────────── */}
      {(() => {
        const now = new Date();
        const daysToSunday = (7 - now.getDay()) % 7 || 7;
        const daysToMonthEnd = new Date(now.getFullYear(), now.getMonth()+1, 0).getDate() - now.getDate();
        const daysToYearEnd = Math.ceil((new Date(now.getFullYear(), 11, 31) - now) / 86400000);
        const WEEK_LB  = [{rank:1,name:"Jonas Bakker",initials:"JB",xp:840,you:false},{rank:2,name:"Aisha Karim",initials:"AK",xp:720,you:false},{rank:3,name:"Mara de Vries",initials:"MV",xp:610,you:true}];
        const MONTH_LB = [{rank:1,name:"Jonas Bakker",initials:"JB",xp:2840,you:false},{rank:2,name:"Aisha Karim",initials:"AK",xp:2510,you:false},{rank:3,name:"Mara de Vries",initials:"MV",xp:1920,you:true}];
        const YEAR_LB  = LEADERBOARD.slice(0,3);
        const prizes = [
          { id:"week",  period:"Week",  icon:"book",       grad:"linear-gradient(135deg,#f99d25,#c97010)",    accentCol:"#f99d25",
            prize:"Free ebook",      detail:'"Project Management by ICB4"',   value:"€45", daysLeft:daysToSunday,  unit:"days",  lb:WEEK_LB  },
          { id:"month", period:"Month", icon:"graduation", grad:"linear-gradient(135deg,var(--vh-blue-500),var(--vh-navy))", accentCol:"var(--vh-blue-500)",
            prize:"Free eLearning",   detail:"Course of your choice",          value:"€199", daysLeft:daysToMonthEnd, unit:"days",  lb:MONTH_LB },
          { id:"year",  period:"Year",  icon:"trophy",    grad:"linear-gradient(135deg,#1d3d7c,#0a1429)",    accentCol:"#c0932b",
            prize:"Learner of the Year", detail:"Physical trophy + award ceremony", value:"Annual", daysLeft:daysToYearEnd, unit:"days", lb:YEAR_LB, special:true },
        ];
        return (
          <>
            <div className="between" style={{ margin:"4px 0 16px" }}>
              <div>
                <h2 style={{ fontSize:20, fontWeight:700 }}>Prizes &amp; Awards</h2>
                <p className="dim" style={{ fontSize:13, marginTop:3 }}>Top learners each week, month and year win real rewards.</p>
              </div>
              <span className="tag accent"><Icon name="trophy" size={13}/>Community recognition</span>
            </div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:16, marginBottom:26 }}>
              {prizes.map(p => (
                <div key={p.id} className="card" style={{ padding:0, overflow:"hidden" }}>
                  {/* header */}
                  <div style={{ padding:"18px 20px 16px", background:p.grad, position:"relative", overflow:"hidden" }}>
                    <div className="hexfield" style={{opacity:.22}} />
                    <div style={{ position:"relative" }}>
                      <div style={{ display:"flex", alignItems:"flex-start", justifyContent:"space-between", gap:10 }}>
                        <div>
                          <div className="eyebrow" style={{ color:"rgba(255,255,255,.7)", marginBottom:4 }}>Prize of the {p.period}</div>
                          <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:20, color:"#fff", lineHeight:1.1 }}>{p.prize}</div>
                          <div style={{ fontSize:12.5, color:"rgba(255,255,255,.82)", marginTop:4, lineHeight:1.4 }}>{p.detail}</div>
                        </div>
                        <div className="hex-flat" style={{ width:44, height:48, flex:"none", clipPath:"polygon(50% 0,93% 25%,93% 75%,50% 100%,7% 75%,7% 25%)", background:p.special?"#c0932b":"rgba(255,255,255,.2)", display:"grid", placeItems:"center" }}>
                          <Icon name={p.icon} size={22} style={{color:p.special?"#231f20":"#fff"}} />
                        </div>
                      </div>
                      <div style={{ display:"flex", alignItems:"center", gap:10, marginTop:12 }}>
                        <span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:12, fontWeight:700, color:"rgba(255,255,255,.9)", background:"rgba(255,255,255,.15)", borderRadius:999, padding:"3px 10px" }}>
                          <Icon name="medal" size={12}/>  {p.value} value
                        </span>
                        <span style={{ fontSize:12, color:"rgba(255,255,255,.6)"}}>· {p.daysLeft} days left</span>
                      </div>
                    </div>
                  </div>
                  {/* standings */}
                  <div style={{ padding:"14px 18px" }}>
                    <div className="eyebrow" style={{ marginBottom:10 }}>Current standings</div>
                    {p.lb.map((ldr,i) => (
                      <div key={ldr.rank} style={{ display:"flex", alignItems:"center", gap:9, padding:"7px 0", borderBottom:i<p.lb.length-1?"1px solid var(--line-2)":"none" }}>
                        <span style={{ width:18, fontFamily:"var(--display)", fontWeight:800, fontSize:14, color:i===0?p.accentCol:"var(--ink-3)" }}>{i+1}</span>
                        <div className="avatar" style={{ width:28, height:28, borderRadius:8, fontSize:11, background:ldr.you?"linear-gradient(135deg,var(--accent),var(--vh-orange))":undefined }}>{ldr.initials}</div>
                        <span style={{ flex:1, fontSize:13, fontWeight:ldr.you?700:500 }}>{ldr.name}{ldr.you&&" · you"}</span>
                        <span style={{ fontFamily:"var(--display)", fontWeight:700, fontSize:12.5 }}>{ldr.xp.toLocaleString()}</span>
                      </div>
                    ))}
                    <button className="btn btn-ghost" style={{ width:"100%", marginTop:10, fontSize:12.5 }} onClick={()=>toast("Full prize rankings — coming soon","clock")}>
                      Full rankings <Icon name="arrowR" size={13}/>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </>
        );
      })()}

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 20 }}>
        {/* badges */}
        <div className="card" style={{ padding: 24 }}>
          <div className="between" style={{ marginBottom: 18 }}>
            <h3 style={{ fontSize: 18, fontWeight: 700 }}>Badges</h3>
            <span className="dim" style={{ fontSize: 13, fontWeight: 600 }}>{got} earned · {BADGES.length - got} to go</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 18 }}>
            {BADGES.map(b => (
              <button key={b.id} onClick={() => b.got ? toast(b.name + " — " + b.desc, b.icon) : toast("Locked: " + b.desc, "lock")}
                style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10, padding: "8px 4px", cursor: "pointer", background: "none", textAlign: "center" }}>
                <Badge icon={b.icon} size={66} color={b.color} ink="#fff" locked={!b.got} style={t.badgeStyle} />
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: b.got ? "var(--ink)" : "var(--ink-3)" }}>{b.name}</div>
                  <div className="dim" style={{ fontSize: 10.5, marginTop: 2, lineHeight: 1.3 }}>{b.desc}</div>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* leaderboard full */}
        <div className="card" style={{ padding: 24 }}>
          <div className="between" style={{ marginBottom: 16 }}>
            <h3 style={{ fontSize: 18, fontWeight: 700 }}>Cohort leaderboard</h3>
            <span className="tag accent" style={{ fontSize: 11 }}><Icon name="users" size={12} />24 learners</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {LEADERBOARD.map(p => (
              <div key={p.rank} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 11px", borderRadius: 12, background: p.you ? "var(--accent-soft)" : "var(--surface-2)", border: "1px solid " + (p.you ? "color-mix(in oklab,var(--accent),transparent 60%)" : "var(--line)") }}>
                <span style={{ width: 22, textAlign: "center", fontFamily: "var(--display)", fontWeight: 800, fontSize: 16, color: p.rank <= 3 ? "var(--accent)" : "var(--ink-3)" }}>{p.rank}</span>
                <div className="avatar" style={{ width: 36, height: 36, borderRadius: 11, fontSize: 13, background: p.you ? "linear-gradient(135deg,var(--accent),var(--vh-orange))" : undefined }}>{p.initials}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{p.name}{p.you && <span className="dim" style={{ fontWeight: 600 }}> · you</span>}</div>
                  <div className="dim" style={{ fontSize: 11.5 }}>Level {p.rank <= 2 ? 8 : 7}</div>
                </div>
                <Icon name={p.trend === "up" ? "chevD" : p.trend === "down" ? "chevD" : "arrowR"} size={15} style={{ color: p.trend === "up" ? "var(--vh-teal)" : p.trend === "down" ? "var(--vh-orange)" : "var(--ink-3)", transform: p.trend === "up" ? "rotate(180deg)" : "none" }} />
                <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 14 }}>{p.xp.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---- Tweaks ---- */
const ACCENTS = [
  { v: "#f99d25", name: "Van Haren Orange" },
  { v: "#3bc1ce", name: "Teal" },
  { v: "#1281c4", name: "Brand Blue" },
  { v: "#7a5ad6", name: "Violet" },
  { v: "#e0556b", name: "Coral" },
];
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "look": "clear",
  "accent": "#f99d25",
  "badgeStyle": "hex",
  "pointsStyle": "solid"
}/*EDITMODE-END*/;

function App() {
  const [lang, setLang] = useState(() => localStorage.getItem('vhl_lang') || 'en');
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useState("dashboard");
  const [course, setCourse] = useState(null);
  const [toastMsg, setToastMsg] = useState(null);
  const [viewer, setViewer]   = useState(null); // 'slides' | 'kahoot' | 'wordcloud'
  const [readerBook, setReaderBook] = useState(null); // deep-link: open the Reader with this book pre-selected
  const toast = (msg, icon) => setToastMsg({ msg, icon, key: Date.now() });

  useEffect(() => {
    localStorage.setItem('vhl_lang', lang);
    const isRTL = (LANG_LIST.find(l => l.code === lang) || {}).rtl;
    document.documentElement.dir = isRTL ? 'rtl' : 'ltr';
    document.documentElement.lang = lang;
  }, [lang]);

  const go = (r) => { setRoute(r); setCourse(null); setReaderBook(null); document.querySelector(".canvas")?.scrollTo(0, 0); };
  /* course pages open the SAME Reader as the menu — only with the course's book pre-selected */
  const openReaderBook = (b) => { setReaderBook(b); setRoute("reader"); setCourse(null); document.querySelector(".canvas")?.scrollTo(0, 0); };
  const openCourse = (c) => { setCourse(c); setRoute("course"); };

  const deep = t.look === "deep";
  const accentVars = {
    "--accent": t.accent,
    "--accent-soft": `color-mix(in oklab, ${t.accent}, ${deep ? "#0c1830 78%" : "white 84%"})`,
    "--accent-ink": deep ? `color-mix(in oklab, ${t.accent}, white 35%)` : `color-mix(in oklab, ${t.accent}, black 52%)`,
  };

  return (
    <LangContext.Provider value={{ lang, setLang }}>
    <>
    <div className={"app" + (deep ? " look-deep" : "")} style={accentVars}>
      <Sidebar route={route} go={go} deep={deep} />
      <div className="main">
        <Topbar t={t} toast={toast} />
        <div className="canvas scroll">
          {route === "dashboard" && <Dashboard t={t} navigate={go} openCourse={openCourse} onViewSlides={() => setViewer("slides")} />}
          {route === "courses" && <Courses t={t} openCourse={openCourse} />}
          {route === "uploads" && <UploadedDecks t={t} toast={toast} />}
          {route === "course" && course && <CourseScreen course={course} back={() => go("courses")} t={t} toast={toast} onViewSlides={() => setViewer("slides")} onOpenBook={() => openReaderBook({ id: "ipma-prep", track: "IPMA-D® Certification" })} onKahoot={() => setViewer("kahoot")} onWordCloud={() => setViewer("wordcloud")} />}
          {route === "passport" && <Passport t={t} toast={toast} />}
          {route === "reader" && <ReaderScreen t={t} toast={toast} initialBook={readerBook} goToCourse={(id) => { const c = COURSES.find((x) => x.id === id); if (c) { setReaderBook(null); openCourse(c); document.querySelector(".canvas")?.scrollTo(0, 0); } }} />}
          {route === "achievements" && <Achievements t={t} toast={toast} />}
        </div>
      </div>

      {toastMsg && <Toast key={toastMsg.key} icon={toastMsg.icon} onDone={() => setToastMsg(null)}>{toastMsg.msg}</Toast>}

      <TweaksPanel>
        <TweakSection label="Overall look" />
        <TweakRadio label="Theme" value={t.look} options={["clear", "deep"]} onChange={v => setTweak("look", v)} />
        <TweakSection label="Accent colour" />
        <TweakColor label="Accent" value={t.accent} options={ACCENTS.map(a => a.v)} onChange={v => setTweak("accent", v)} />
        <TweakSection label="Badges & points" />
        <TweakRadio label="Badge shape" value={t.badgeStyle} options={["hex", "shield", "circle"]} onChange={v => setTweak("badgeStyle", v)} />
        <TweakRadio label="Points style" value={t.pointsStyle} options={["solid", "soft", "outline"]} onChange={v => setTweak("pointsStyle", v)} />
      </TweaksPanel>
    </div>
    {viewer === "slides" && <IPMASlideFrame onClose={() => setViewer(null)} toast={toast} onKahoot={() => setViewer("kahoot")} onWordCloud={() => setViewer("wordcloud")} />}
    {viewer === "kahoot"    && <IPMAKahootGame   onClose={() => setViewer(null)} />}
    {viewer === "wordcloud" && <IPMAWordCloudGame onClose={() => setViewer(null)} />}
    </>
    </LangContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
