/* global React, window, Icon, Mascot, Reveal, FloatingDeco, HeroScene, CourseCover, useT, useEyad, ThemeIcon, SUBJECTS, COURSES, PILLARS */
const { useState, useEffect, useRef } = React;

// ============================================================
// NAV — with language + theme toggles
// ============================================================
function Nav({ active, onNav, onSignup }) {
  const t = useT();
  const { lang, theme, setLang, setTheme } = useEyad();
  const links = [
    { id: "why", label: t.nav.why },
    { id: "courses", label: t.nav.courses },
    { id: "journey", label: t.nav.journey },
    { id: "teachers", label: t.nav.teachers },
    { id: "stories", label: t.nav.stories },
  ];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#top" className="brand" onClick={(e) => { e.preventDefault(); onNav("top"); }}>
          <span className="brand-mark"><Icon name="spark" size={20}/></span>
          <span>{t.nav.brand}</span>
        </a>
        <ul>
          {links.map(l => (
            <li key={l.id}>
              <a href={`#${l.id}`} className={active === l.id ? "active" : ""}
                 onClick={(e) => { e.preventDefault(); onNav(l.id); }}>{l.label}</a>
            </li>
          ))}
        </ul>
        <div className="nav-cta">
          <button
            className="nav-icon-btn"
            onClick={() => setLang(lang === "ar" ? "en" : "ar")}
            aria-label="Switch language"
            title={lang === "ar" ? "Switch to English" : "تغيير إلى العربية"}>
            <span style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13 }}>
              {lang === "ar" ? "EN" : "ع"}
            </span>
          </button>
          <button
            className="nav-icon-btn"
            onClick={() => setTheme(theme === "light" ? "dark" : "light")}
            aria-label="Toggle theme"
            title={theme === "light" ? "Switch to dark" : "Switch to light"}>
            <ThemeIcon theme={theme === "light" ? "light" : "dark"}/>
          </button>
          <button className="btn btn-ghost nav-login" onClick={() => onNav("login")}>{t.nav.login}</button>
          <button className="btn btn-primary" onClick={onSignup}>
            {t.nav.start}
            <Icon name="arrow" size={16}/>
          </button>
        </div>
      </div>
    </nav>
  );
}

// ============================================================
// HERO
// ============================================================
function Hero({ mascotStyle, onSignup, onScrollCourses }) {
  const t = useT();
  return (
    <section className="hero" id="top">
      <FloatingDeco variant="hero"/>
      <div className="container">
        <div className="hero-grid">
          <Reveal className="hero-copy">
            <span className="eyebrow"><span className="dot"></span>{t.hero.eyebrow}</span>
            <h1>
              {t.hero.titleA}&nbsp;
              <span className="grad">{t.hero.titleB}</span><br/>
              {t.hero.titleC}
            </h1>
            <p className="lead">{t.hero.lead}</p>
            <div className="hero-cta">
              <button className="btn btn-primary" onClick={onSignup}>
                {t.hero.cta1}
                <Icon name="arrow" size={16}/>
              </button>
              <button className="btn btn-ghost" onClick={onScrollCourses}>
                <Icon name="play" size={14}/>
                {t.hero.cta2}
              </button>
            </div>
            <div className="hero-stats">
              <div className="hero-stat"><div className="n">{t.hero.s1n}</div><div className="l">{t.hero.s1l}</div></div>
              <div className="hero-stat"><div className="n">{t.hero.s2n}</div><div className="l">{t.hero.s2l}</div></div>
              <div className="hero-stat"><div className="n">{t.hero.s3n}</div><div className="l">{t.hero.s3l}</div></div>
            </div>
          </Reveal>

          <Reveal delay={200} className="hero-visual">
            <div className="hv-photo">
              <HeroScene/>
            </div>
            <div className="hv-mascot">
              <Mascot style={mascotStyle}/>
            </div>
            <div className="hv-chip hv-chip-a">
              <div className="icon"><Icon name="check" size={18}/></div>
              <div>
                <div className="l">{t.hero.chipA}</div>
                <div className="n">{t.hero.chipAv}</div>
              </div>
            </div>
            <div className="hv-chip hv-chip-b">
              <div className="icon" style={{ background: "linear-gradient(135deg, #C9B8FF, #8B7AD9)", color: "#fff" }}>
                <Icon name="star" size={18}/>
              </div>
              <div>
                <div className="l">{t.hero.chipB}</div>
                <div className="n">{t.hero.chipBv}</div>
              </div>
            </div>
            <div className="hv-progress">
              <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 14 }}>
                <span style={{ color: "var(--navy)" }}>{t.hero.progress}</span>
                <span style={{ color: "var(--gold-deep)" }}>{t.hero.progressV}</span>
              </div>
              <div className="bar"><div></div></div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// WHY EYAD
// ============================================================
function Why() {
  const t = useT();
  return (
    <section className="section" id="why">
      <div className="container">
        <Reveal className="section-head">
          <span className="eyebrow"><span className="dot"></span>{t.why.eyebrow}</span>
          <h2>{t.why.titleA}<br/>{t.why.titleB}</h2>
          <p className="lead">{t.why.lead}</p>
        </Reveal>

        <div className="why-grid">
          {PILLARS.map((p, i) => (
            <Reveal key={p.icon} delay={i * 100}>
              <div className="pillar">
                <div className="icon"><Icon name={p.icon} size={28}/></div>
                <h3>{t.why.pillars[i].title}</h3>
                <p>{t.why.pillars[i].desc}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// SUBJECTS
// ============================================================
function Subjects({ onSelectSubject }) {
  const t = useT();
  return (
    <section className="section" id="subjects" style={{ paddingTop: 40 }}>
      <FloatingDeco variant="subtle"/>
      <div className="container" style={{ position: "relative", zIndex: 1 }}>
        <Reveal className="section-head">
          <span className="eyebrow"><span className="dot"></span>{t.subjects.eyebrow}</span>
          <h2>{t.subjects.titleA}<br/>{t.subjects.titleB}</h2>
          <p className="lead">{t.subjects.lead}</p>
        </Reveal>

        <div className="subjects-grid">
          {SUBJECTS.map((s, i) => {
            const loc = t.subjects.items[s.id];
            return (
              <Reveal key={s.id} delay={i * 80}>
                <div className="subject" onClick={() => onSelectSubject(s.id)}>
                  <div className="glyph" style={{ background: s.glyph, color: "var(--navy)" }}>
                    <Icon name={s.icon} size={30}/>
                  </div>
                  <div className="en-label en">{s.en}</div>
                  <h3>{loc.name}</h3>
                  <p style={{ fontSize: 14, color: "var(--ink-soft)", margin: "6px 0 14px", lineHeight: 1.6 }}>{loc.desc}</p>
                  <div className="meta">
                    <span>{t.subjects.discover}</span>
                    <Icon name="chevron" size={14}/>
                  </div>
                </div>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// COURSES
// ============================================================
function localizeCourse(c, t) {
  const o = t.courseOverrides?.[c.id] || {};
  return {
    ...c,
    title: o.title || c.title,
    short: o.short || c.short,
    tag: o.tag || c.tag,
    level: o.level || c.level,
    age: o.age || c.age,
    duration: o.duration || c.duration,
    teacher: { ...c.teacher, name: o.teacher || c.teacher.name, role: o.role || c.teacher.role },
    curriculum: o.curriculum ? o.curriculum.map((title, i) => ({ t: title, d: o.cd[i] })) : c.curriculum,
  };
}

function Courses({ activeSubject, setActiveSubject, onOpenCourse }) {
  const t = useT();
  const tabs = [
    { id: "all", label: t.courses.all },
    ...SUBJECTS.map(s => ({ id: s.id, label: t.subjects.items[s.id].name })),
  ];
  const filtered = activeSubject === "all"
    ? COURSES
    : COURSES.filter(c => c.subject === activeSubject);
  const counts = SUBJECTS.reduce((acc, s) => {
    acc[s.id] = COURSES.filter(c => c.subject === s.id).length;
    return acc;
  }, { all: COURSES.length });

  return (
    <section className="section" id="courses" style={{ background: "linear-gradient(180deg, transparent 0%, var(--cream-3) 50%, transparent 100%)" }}>
      <div className="container">
        <Reveal className="section-head">
          <span className="eyebrow"><span className="dot"></span>{t.courses.eyebrow}</span>
          <h2>{t.courses.titleA}<br/>{t.courses.titleB}</h2>
          <p className="lead">{t.courses.lead}</p>
        </Reveal>

        <Reveal className="filter-bar">
          {tabs.map(tb => (
            <button key={tb.id}
              className={`filter-chip ${activeSubject === tb.id ? "active" : ""}`}
              onClick={() => setActiveSubject(tb.id)}>
              {tb.label}
              <span className="count">{counts[tb.id] || 0}</span>
            </button>
          ))}
        </Reveal>

        <div className="courses-grid">
          {filtered.map((cRaw, i) => {
            const c = localizeCourse(cRaw, t);
            return (
              <Reveal key={c.id} delay={i * 60}>
                <article className="course" onClick={() => onOpenCourse(c)}>
                  <div className="course-cover">
                    <CourseCover subject={c.subject}/>
                    <span className="course-badge">{c.level}</span>
                  </div>
                  <div className="course-body">
                    <div className="course-tag">{c.tag} · <span className="en">{c.titleEn}</span></div>
                    <h3 className="course-title">{c.title}</h3>
                    <p style={{ fontSize: 14, color: "var(--ink-soft)", margin: 0, lineHeight: 1.6 }}>{c.short}</p>
                    <div className="course-meta">
                      <span><Icon name="clock" size={14}/> {c.duration}</span>
                      <span className="dot"></span>
                      <span><Icon name="book" size={14}/> {c.lessons} {t.courses.lesson}</span>
                      <span className="dot"></span>
                      <span><Icon name="users" size={14}/> {c.age}</span>
                    </div>
                    <div className="course-progress">
                      <div className="bar"><div style={{ width: `${c.progress}%` }}/></div>
                      <span>{c.progress}%</span>
                    </div>
                    <div className="course-teacher">
                      <div className="avatar">{c.teacher.initials}</div>
                      <div style={{ flex: 1 }}>
                        <div className="name">{c.teacher.name}</div>
                        <div className="role">{c.teacher.role}</div>
                      </div>
                      <div style={{ display: "flex", alignItems: "center", gap: 4, color: "var(--gold-deep)", fontWeight: 700, fontFamily: "var(--f-display)" }}>
                        <Icon name="star" size={14}/>
                        {c.rating}
                      </div>
                    </div>
                  </div>
                </article>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// COURSE MODAL
// ============================================================
function CourseModal({ course, onClose, onEnroll }) {
  const t = useT();
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, [onClose]);

  if (!course) return null;
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-cover">
          <CourseCover subject={course.subject}/>
          <button className="modal-close" onClick={onClose}><Icon name="close" size={18}/></button>
          <div style={{ position: "absolute", bottom: 20, insetInlineEnd: 24, color: "white" }}>
            <div style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13, letterSpacing: "0.05em", opacity: 0.85, textTransform: "uppercase" }}>
              <span className="en">{course.titleEn}</span>
            </div>
            <h2 style={{ color: "white", fontSize: 28, marginTop: 4 }}>{course.title}</h2>
          </div>
        </div>
        <div className="modal-body">
          <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <span style={{ padding: "6px 14px", borderRadius: 999, background: "rgba(217,164,65,0.15)", color: "var(--gold-deep)", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 12 }}>{course.tag}</span>
            <span style={{ padding: "6px 14px", borderRadius: 999, background: "var(--chip-bg)", fontFamily: "var(--f-display)", fontWeight: 600, fontSize: 12, color: "var(--navy)" }}>{course.level}</span>
            <span style={{ padding: "6px 14px", borderRadius: 999, background: "var(--chip-bg)", fontFamily: "var(--f-display)", fontWeight: 600, fontSize: 12, color: "var(--navy)" }}>{course.age}</span>
          </div>
          <p className="lead">{course.short}</p>
          <div className="modal-stats">
            <div className="s"><div className="n">{course.lessons}</div><div className="l">{t.courses.modal.lessons}</div></div>
            <div className="s"><div className="n">{course.duration}</div><div className="l">{t.courses.modal.duration}</div></div>
            <div className="s"><div className="n">{course.students.toLocaleString()}</div><div className="l">{t.courses.modal.students}</div></div>
          </div>
          <div className="modal-curriculum">
            <h3 style={{ fontSize: 18, marginBottom: 12 }}>{t.courses.modal.content}</h3>
            <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
              {course.curriculum.map((item, i) => (
                <li key={i}>
                  <span className="n">{i + 1}</span>
                  <span>{item.t}</span>
                  <span className="dur">{item.d}</span>
                </li>
              ))}
            </ul>
          </div>
          <div className="modal-cta">
            <button className="btn btn-primary" onClick={() => onEnroll(course)}>
              {t.courses.modal.enroll}
              <Icon name="arrow" size={16}/>
            </button>
            <button className="btn btn-ghost" onClick={onClose}>{t.courses.modal.back}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Nav, Hero, Why, Subjects, Courses, CourseModal });
