// === Main app shell ===

function Sidebar({ active, go, state, theme, setTheme, collapsed, setCollapsed, mobileOpen, setMobileOpen }) {
  const totalDone = M2_TOOL_IDS.filter((id) => sectionComplete(id, state)).length;
  const pct = Math.round(totalDone / 8 * 100);
  const activeModule = SECTIONS.find((s) => s.id === active)?.module || "home";
  const [optsOpen, setOptsOpen] = React.useState(false);
  const [hoverModule, setHoverModule] = React.useState(null);
  const closeMobile = () => setMobileOpen(false);

  // Module icons — distincte pentru collapsed mode (mai mari, mai expressive)
  const moduleIcon = (code, large) => {
    const size = large ? 22 : 14;
    const map = {
      // M1: book opened
      M1: <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={large ? 1.9 : 2.2} strokeLinecap="round" strokeLinejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path></svg>,
      // M2: wrench/tool
      M2: <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={large ? 1.9 : 2.2} strokeLinecap="round" strokeLinejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path></svg>,
      // M3: play in circle
      M3: <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={large ? 1.9 : 2.2} strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><polygon points="10 8 16 12 10 16 10 8" fill="currentColor"></polygon></svg>,
      // M4: trophy
      M4: <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={large ? 1.9 : 2.2} strokeLinecap="round" strokeLinejoin="round"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"></path><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"></path><path d="M4 22h16"></path><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"></path><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"></path><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"></path></svg>
    };
    return map[code];
  };

  return (
    <aside className={`sidebar ${collapsed ? "collapsed" : ""} ${mobileOpen ? "mobile-open" : ""}`}>
      <div className="sidebar-inner">
        <div className="sidebar-top">
          <button className="brand" onClick={() => { go("intro"); closeMobile(); }} title="PM Hub · Acasă">
            <div className="brand-mark">
              <span className="brand-mark-glyph"></span>
              <span className="brand-mark-name">PM Hub</span>
            </div>
            {!collapsed && <div className="brand-sub">Învățare · Practică · ANC</div>}
          </button>

          <button
            className="sidebar-toggle"
            onClick={() => setCollapsed(!collapsed)}
            title={collapsed ? "Extinde meniul" : "Colapsează meniul"}
            aria-label="Toggle sidebar">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: collapsed ? "rotate(180deg)" : "none", transition: "transform 0.2s" }}>
              <polyline points="15 18 9 12 15 6"></polyline>
            </svg>
          </button>
        </div>

        <nav className="sidebar-nav">
          <button className={`nav-item nav-home ${active === "intro" ? "active" : ""}`} onClick={() => { go("intro"); closeMobile(); }} title="Acasă">
            <span className="nav-icon">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>
            </span>
            <span className="nav-label">Acasă</span>
          </button>

          {!collapsed && <div className="nav-section-label">Module</div>}

          {MODULES.map((m) => {
            const isExpandable = m.status === "active";
            const isActiveModule = activeModule === m.id;
            const subs = SECTIONS.filter((s) => s.module === m.id && s.id !== `${m.id}-overview`);
            return (
              <div
                key={m.id}
                className="nav-module-group"
                onMouseEnter={() => collapsed && setHoverModule(m.id)}
                onMouseLeave={() => collapsed && setHoverModule(null)}>
                <button
                  className={`nav-module ${m.status} ${isActiveModule ? "expanded" : ""}`}
                  onClick={() => go(m.route)}
                  title={`${m.code} · ${m.name}`}>
                  <span className="nav-icon">{moduleIcon(m.code, collapsed)}</span>
                  <span className="nav-module-code">{m.code}</span>
                  <span className="nav-module-name">{m.name}</span>
                  {m.status === "active" ?
                    <span className="nav-module-tag active-tag">Activ</span> :
                    <span className="nav-module-tag">Soon</span>}
                </button>

                {/* Expanded inline (when not collapsed) */}
                {!collapsed && isExpandable && isActiveModule && subs.length > 0 &&
                  <div className="nav-sub">
                    {subs.map((s) => {
                      const isM2Tool = M2_TOOL_IDS.includes(s.id);
                      const isM1Lesson = M1_LESSON_IDS.includes(s.id);
                      let done = false;
                      if (isM2Tool) done = sectionComplete(s.id, state);
                      else if (isM1Lesson) done = m1LessonComplete(s.id, state);
                      return (
                        <button key={s.id}
                          className={`nav-sub-item ${active === s.id ? "active" : ""}`}
                          onClick={() => { go(s.id); closeMobile(); }}>
                          <span className="nav-sub-num">{s.num}</span>
                          <span className="nav-sub-label">{s.label}</span>
                          {(isM2Tool || isM1Lesson) && <span className={`nav-item-check ${done ? "done" : ""}`}></span>}
                        </button>
                      );
                    })}
                  </div>
                }

                {/* Flyout (when collapsed + hovered) */}
                {collapsed && isExpandable && hoverModule === m.id && subs.length > 0 &&
                  <div className="nav-flyout">
                    <div className="nav-flyout-head">
                      <span className="nav-module-code">{m.code}</span>
                      <span>{m.name}</span>
                    </div>
                    {subs.map((s) => {
                      const isM2Tool = M2_TOOL_IDS.includes(s.id);
                      const isM1Lesson = M1_LESSON_IDS.includes(s.id);
                      let done = false;
                      if (isM2Tool) done = sectionComplete(s.id, state);
                      else if (isM1Lesson) done = m1LessonComplete(s.id, state);
                      return (
                        <button key={s.id}
                          className={`nav-sub-item ${active === s.id ? "active" : ""}`}
                          onClick={() => { go(s.id); setHoverModule(null); }}>
                          <span className="nav-sub-num">{s.num}</span>
                          <span className="nav-sub-label">{s.label}</span>
                          {(isM2Tool || isM1Lesson) && <span className={`nav-item-check ${done ? "done" : ""}`}></span>}
                        </button>
                      );
                    })}
                  </div>
                }
              </div>
            );
          })}

          {!collapsed &&
            <div className="m2-mini-progress">
              <div className="m2-mini-label">Progres M2</div>
              <div className="m2-mini-val">{totalDone} / 8 instrumente</div>
              <div className="progress-bar" style={{ margin: 0 }}>
                <div className="progress-bar-fill" style={{ width: `${pct}%` }}></div>
              </div>
            </div>
          }
        </nav>

        <div className="sidebar-foot">
          {!collapsed && <div className="sidebar-auth-slot"><AuthButton /></div>}

          {!collapsed &&
            <div className="sidebar-note">
              <strong>Salvat automat.</strong> Datele rămân la tine.
            </div>
          }

          <button className="options-btn" onClick={() => setOptsOpen((o) => !o)} title="Opțiuni">
            <span className="options-icon">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
            </span>
            <span className="nav-label">Opțiuni</span>
            {!collapsed && <span className="chevron">{optsOpen ? "▼" : "▲"}</span>}
          </button>

          {optsOpen && !collapsed &&
            <div className="options-panel">
              <div className="options-row">
                <span className="options-label">Temă</span>
                <div className="theme-segment">
                  <button className={theme === "light" ? "active" : ""} onClick={() => setTheme("light")} title="Mod clar" data-comment-anchor="645628ddf5-button-92-17">
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <circle cx="12" cy="12" r="4.5"></circle>
                      <line x1="12" y1="2" x2="12" y2="4"></line>
                      <line x1="12" y1="20" x2="12" y2="22"></line>
                      <line x1="4.93" y1="4.93" x2="6.34" y2="6.34"></line>
                      <line x1="17.66" y1="17.66" x2="19.07" y2="19.07"></line>
                      <line x1="2" y1="12" x2="4" y2="12"></line>
                      <line x1="20" y1="12" x2="22" y2="12"></line>
                      <line x1="4.93" y1="19.07" x2="6.34" y2="17.66"></line>
                      <line x1="17.66" y1="6.34" x2="19.07" y2="4.93"></line>
                    </svg>
                    Clar
                  </button>
                  <button className={theme === "dark" ? "active" : ""} onClick={() => setTheme("dark")} title="Mod întunecat">
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
                    </svg>
                    Întunecat
                  </button>
                </div>
              </div>
            </div>
          }
        </div>
      </div>
    </aside>
  );
}

// Floating "scroll to top" button — appears once user scrolls past 400px,
// fades back out when at the top. Smooth scroll on click.
function ScrollToTopButton() {
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const SHOW_AT = 400;
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        setVisible(window.scrollY > SHOW_AT);
        ticking = false;
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll(); // initial check
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const handleClick = () => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <button
      className={`scroll-top-btn ${visible ? "visible" : ""}`}
      onClick={handleClick}
      aria-label="Înapoi la început"
      title="Înapoi la început"
      tabIndex={visible ? 0 : -1}
    >
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <polyline points="18 15 12 9 6 15"></polyline>
      </svg>
    </button>
  );
}

function MobileTopbar({ go, setMobileOpen, mobileOpen }) {
  return (
    <header className="topbar">
      <button className="topbar-burger" onClick={() => setMobileOpen(!mobileOpen)} aria-label="Meniu">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <line x1="3" y1="6" x2="21" y2="6"></line>
          <line x1="3" y1="12" x2="21" y2="12"></line>
          <line x1="3" y1="18" x2="21" y2="18"></line>
        </svg>
      </button>
      <button className="topbar-brand" onClick={() => go("intro")}>
        <span className="brand-mark-glyph"></span>
        <span>PM Hub</span>
      </button>
      <div className="topbar-auth-slot"><AuthButton /></div>
    </header>
  );
}

function App() {
  const [state, update, reset] = useAppState();
  const [active, setActive] = React.useState(() => {
    const h = window.location.hash.replace("#", "");
    return SECTIONS.find((s) => s.id === h) ? h : "intro";
  });
  const [theme, setThemeState] = React.useState(() => {
    try { return localStorage.getItem("pm_theme") || "light"; } catch (e) { return "light"; }
  });
  const [collapsed, setCollapsedState] = React.useState(() => {
    try { return localStorage.getItem("pm_sidebar_collapsed") === "1"; } catch (e) { return false; }
  });
  const [mobileOpen, setMobileOpen] = React.useState(false);

  // Lock body scroll when mobile drawer is open
  React.useEffect(() => {
    if (mobileOpen) {
      const scrollY = window.scrollY;
      document.body.style.top = `-${scrollY}px`;
      document.body.classList.add("no-scroll");
      return () => {
        document.body.classList.remove("no-scroll");
        document.body.style.top = "";
        window.scrollTo(0, scrollY);
      };
    }
  }, [mobileOpen]);

  // Close mobile drawer when clicking outside (on main content)
  React.useEffect(() => {
    if (!mobileOpen) return;
    const handler = (e) => {
      const sidebar = document.querySelector(".sidebar");
      const burger = document.querySelector(".topbar-burger");
      if (!sidebar) return;
      if (sidebar.contains(e.target)) return;
      if (burger && burger.contains(e.target)) return;
      setMobileOpen(false);
    };
    document.addEventListener("mousedown", handler);
    document.addEventListener("touchstart", handler);
    return () => {
      document.removeEventListener("mousedown", handler);
      document.removeEventListener("touchstart", handler);
    };
  }, [mobileOpen]);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("pm_theme", theme); } catch (e) {}
  }, [theme]);

  React.useEffect(() => {
    try { localStorage.setItem("pm_sidebar_collapsed", collapsed ? "1" : "0"); } catch (e) {}
  }, [collapsed]);

  // Auto-collapse on small screens, restore on large
  React.useEffect(() => {
    const check = () => {
      const w = window.innerWidth;
      if (w < 1100 && w >= 900) {
        setCollapsedState(true);
      }
    };
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, []);

  const setTheme = React.useCallback((t) => setThemeState(t), []);
  const setCollapsed = React.useCallback((c) => setCollapsedState(c), []);

  const go = React.useCallback((id) => {
    setActive(id);
    window.location.hash = id;
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);

  React.useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace("#", "");
      if (SECTIONS.find((s) => s.id === h)) setActive(h);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Close mobile drawer when route changes via sub-items only (not via outer modules)
  // Sub-items in nav call closeMobile() directly. Outer modules just navigate.

  const renderSection = () => {
    const props = { state, update, go, reset };
    switch (active) {
      case "intro": return <IntroSection {...props} />;
      case "m1-overview": return <M1OverviewSection {...props} />;
      case "m1-definitions": return <DefinitionsSection {...props} />;
      case "m1-pert": return <PERTSection {...props} />;
      case "m1-eisenhower": return <EisenhowerSection {...props} />;
      case "m1-orgs": return <OrgsSection {...props} />;
      case "m1-glossary": return <GlossarySection {...props} />;
      case "m1-quiz": return <QuizSection {...props} />;
      case "m3-overview": return <M3OverviewSection {...props} />;
      case "m3-sim": return <SimulatorSection {...props} />;
      case "m3-report": return <ReportSection {...props} />;
      case "m3-team-setup": return <TeamSetupSection {...props} />;
      case "m3-team-sim": return <TeamSimulatorSection {...props} />;
      case "m3-team-report": return <TeamReportSection {...props} />;
      case "privacy": return <PrivacySettings {...props} />;
      case "history": return <HistoryPage {...props} />;
      case "m4-overview": return <M4OverviewSection {...props} />;
      case "m4-exam": return <MockExamSection {...props} />;
      case "m4-certificate": return <CertificateSection {...props} />;
      case "m2-overview": return <M2OverviewSection {...props} />;
      case "org": return <OrgSection {...props} />;
      case "scope": return <ScopeSection {...props} />;
      case "needs": return <NeedsSection {...props} />;
      case "activities": return <ActivitiesSection {...props} />;
      case "gantt": return <GanttSection {...props} />;
      case "budget": return <BudgetSection {...props} />;
      case "mgmt": return <ManagementSection {...props} />;
      case "risk": return <RiskSection {...props} />;
      case "export": return <ExportSection {...props} />;
      case "m1": return <M1OverviewSection {...props} />;
      case "m3": return <M3OverviewSection {...props} />;
      case "m4": return <M4OverviewSection {...props} />;
      default: return <IntroSection {...props} />;
    }
  };

  return (
    <div className={`app ${collapsed ? "sidebar-collapsed" : ""} ${mobileOpen ? "mobile-open" : ""}`} data-screen-label={active}>
      <MobileTopbar go={go} setMobileOpen={setMobileOpen} mobileOpen={mobileOpen} />
      <Sidebar
        active={active} go={go} state={state}
        theme={theme} setTheme={setTheme}
        collapsed={collapsed} setCollapsed={setCollapsed}
        mobileOpen={mobileOpen} setMobileOpen={setMobileOpen} />
      {mobileOpen && <div className="mobile-backdrop" onClick={() => setMobileOpen(false)}></div>}
      <main className="main">
        {renderSection()}
        <SiteFooter go={go} />
      </main>
      <ScrollToTopButton />
    </div>
  );
}

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