/* Mereka v2 — Upskill › Program (Learning Paths) — Figma-faithful rebuild */

/* ---------- Data ---------- */
const LP_PATHS = [
  {
    id: 'ai4u', title: 'AI4U', seed: 4,
    desc: 'Leverage generative AI to develop marketing strategies, attract clients, publish content and convert leads',
    courses: 5, hours: '~32H TOTAL',
    status: { type: 'enrolled', progress: 40, done: 2, total: 5 },
  },
  {
    id: 'dynamous', title: 'Dynamous AI Mastery', seed: 1,
    desc: 'Use AI to increase accuracy of financial projections. Automate data analysis, reporting and financial tracking',
    courses: 5, hours: '~32H TOTAL',
    status: { type: 'price', label: '$749 / YEAR' },
  },
  {
    id: 'fluency', title: 'AI Fluency for Beginners', seed: 3,
    desc: 'Learn to embed AI in project management workflows. Convert support tickets into tasks and generate clear reports',
    courses: 5, hours: '~32H TOTAL',
    status: { type: 'free', label: 'FREE' },
  },
  {
    id: 'pm', title: 'Project Manager Mastery', seed: 0,
    desc: 'Learn to embed AI in project management workflows. Convert support tickets into tasks and generate clear reports',
    courses: 5, hours: '~32H TOTAL',
    status: { type: 'price', label: 'RM 1,680' },
  },
  {"id": "creative-ai", "title": "Creative AI for Designers", "seed": 5, "desc": "Bring generative AI into every stage of design — ideation, moodboards, image generation and rapid iteration.", "courses": 6, "hours": "~28H TOTAL", "status": {"type": "price", "label": "RM1,290"}},
  {"id": "data-storytelling", "title": "Data Storytelling & Dashboards", "seed": 2, "desc": "Turn raw data into clear stories and live dashboards stakeholders actually use — no heavy coding required.", "courses": 6, "hours": "~24H TOTAL", "status": {"type": "price", "label": "RM980"}},
  {"id": "growth-marketing-ai", "title": "AI-Powered Growth Marketing", "seed": 6, "desc": "Run full-funnel campaigns with AI — copy, creative, segmentation and experiments that actually convert.", "courses": 6, "hours": "~30H TOTAL", "status": {"type": "price", "label": "RM1,480"}},
  {"id": "no-code-builder", "title": "No-Code App Builder", "seed": 7, "desc": "Ship real web apps and internal tools without writing code — from idea to deployed product.", "courses": 6, "hours": "~26H TOTAL", "status": {"type": "price", "label": "RM1,150"}},
  {"id": "customer-success-ai", "title": "AI for Customer Success", "seed": 3, "desc": "Use AI to deflect tickets, personalise support and turn churn signals into retention wins.", "courses": 5, "hours": "~20H TOTAL", "status": {"type": "free", "label": "FREE"}},
  {"id": "founders-ai", "title": "AI for Founders & Startups", "seed": 1, "desc": "Build, validate and scale your startup faster with AI across product, growth and operations.", "courses": 6, "hours": "~34H TOTAL", "status": {"type": "price", "label": "RM2,400"}},
  {"id": "content-creator", "title": "Content Creator Accelerator", "seed": 0, "desc": "Plan, produce and grow a content engine across video, social and newsletters with AI in the loop.", "courses": 6, "hours": "~22H TOTAL", "status": {"type": "price", "label": "RM890"}},
  {"id": "cyber-aware", "title": "Cybersecurity Essentials", "seed": 4, "desc": "Protect yourself and your team — practical security habits, threat awareness and safe AI use.", "courses": 5, "hours": "~18H TOTAL", "status": {"type": "free", "label": "FREE"}},
];

const LP_FILTER_CHIPS = ['AI Skills', 'Productivity', 'For HR Managers', 'Beginner Friendly', 'Digital Literacy', 'Intermediate'];

const LP_FAQS = [
  { q: 'Do I need prior AI knowledge?', a: 'No, this course is beginner-friendly. Each learning path starts with foundational lessons before moving into applied, role-specific work — so you can join with zero experience.' },
  { q: 'How long will I have access to this course?', a: 'Once enrolled, you keep lifetime access to every course in the path, including future updates, so you can revisit material whenever you need a refresher.' },
  { q: 'Is this course fully remote?', a: 'Yes. All lessons, projects and assessments are delivered online and self-paced. Some paths also include optional live sessions with experts.' },
  { q: 'Can I learn at my own pace?', a: 'Absolutely. There are no fixed deadlines — progress through modules whenever it suits you, and pick up exactly where you left off.' },
];

const LP_FILTER_DROPDOWNS = ['Organization', 'Format', 'State', 'Language', 'Sort by'];

/* ---------- Small pieces ---------- */
function LPMetaChip({ children, tone = 'outline' }) {
  const tones = {
    outline: 'border border-neutral-200 text-neutral-600',
    enrolled: 'bg-[#ECECFF] text-[#5b53d6] border border-transparent',
  };
  return (
    <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-[12px] font-semibold tracking-wide uppercase whitespace-nowrap ${tones[tone]}`}
      style={{ fontFamily: _la }}>
      {children}
    </span>
  );
}

function LPCard({ path }) {
  const enrolled = path.status.type === 'enrolled';
  return (
    <Link to={'/web/learning-paths/' + path.id} className="group flex flex-col text-left">
      <ImageBlock aspect="1/1" seed={path.seed} className="w-full" />
      <h3 className="mt-4 text-xl font-bold text-neutral-900 group-hover:text-purple-700 transition-colors" style={{ fontFamily: _pp }}>
        {path.title}
      </h3>
      <p className="mt-1.5 text-[15px] text-neutral-500 leading-snug" style={{ fontFamily: _la }}>
        {path.desc}
      </p>

      {enrolled ? (
        <div className="mt-3">
          <Progress value={path.status.progress} tone="dark" />
          <div className="mt-1.5 flex items-center justify-between">
            <span className="text-xs font-medium text-[#5b53d6]" style={{ fontFamily: _la }}>
              {path.status.done} of {path.status.total} courses complete
            </span>
            <span className="text-sm font-bold text-neutral-700 num-tabular">{path.status.progress}%</span>
          </div>
        </div>
      ) : (
        <div className="mt-3" />
      )}

      <div className="mt-3 flex flex-wrap items-center gap-2">
        <LPMetaChip>{path.courses} Courses</LPMetaChip>
        <LPMetaChip>{path.hours}</LPMetaChip>
        {enrolled
          ? <LPMetaChip tone="enrolled">Enrolled</LPMetaChip>
          : <LPMetaChip>{path.status.label}</LPMetaChip>}
      </div>
    </Link>
  );
}

/* ---------- Hero ---------- */
function LPHero({ onBrowse }) {
  const [active, setActive] = useState(null);
  return (
    <section className="bg-white">
      <div className="max-w-[min(1960px,90vw)] mx-auto px-5 lg:px-8 pt-16 pb-12 text-center">
        <h1 className="text-5xl lg:text-[64px] font-bold text-neutral-900 leading-[1.05] tracking-tight" style={{ fontFamily: _pp }}>
          Build mastery,<br />not just modules
        </h1>
        <p className="mt-6 max-w-2xl mx-auto text-lg lg:text-xl text-neutral-500 leading-relaxed" style={{ fontFamily: _la }}>
          Learning Paths bundle related courses with shared rules, prerequisites, and a single program-level
          certificate — designed for full-stack career changes, not solo course collecting.
        </p>

        {/* Search */}
        <div className="mt-9 max-w-3xl mx-auto">
          <div className="h-14 px-5 rounded-full border border-neutral-200 bg-white flex items-center gap-3 hover:border-neutral-300 focus-within:border-neutral-400 transition-colors">
            <Icon name="search" size={20} className="text-neutral-700 flex-shrink-0" />
            <Icon name="spark" size={18} className="text-neutral-400 flex-shrink-0" />
            <input
              placeholder="Search for a learning pathway"
              className="flex-1 bg-transparent text-base text-neutral-900 placeholder:text-neutral-400 focus:outline-none"
              style={{ fontFamily: _la }} />
          </div>
        </div>

        {/* Filter chips */}
        <div className="mt-5 flex flex-wrap items-center justify-center gap-3">
          {LP_FILTER_CHIPS.map(c => {
            const on = active === c;
            return (
              <button key={c} onClick={() => setActive(on ? null : c)}
                className={`px-5 py-2.5 rounded-xl text-[15px] font-semibold border transition-colors ${on ? 'bg-neutral-900 text-white border-neutral-900' : 'bg-white text-neutral-900 border-neutral-200 hover:border-neutral-400'}`}
                style={{ fontFamily: _la }}>
                {c}
              </button>
            );
          })}
        </div>

        {/* Browse all */}
        <div className="mt-10">
          <button onClick={onBrowse}
            className="inline-flex items-center gap-3 h-14 pl-7 pr-2.5 rounded-full bg-[#1a1623] text-white text-lg font-semibold hover:bg-black transition-colors"
            style={{ fontFamily: _la }}>
            Browse all learning paths
            <span className="w-10 h-10 rounded-full bg-[#2563eb] flex items-center justify-center">
              <Icon name="arrowRight" size={18} className="text-white rotate-90" />
            </span>
          </button>
        </div>
      </div>
    </section>
  );
}

/* ---------- Popular ---------- */
function LPPopular() {
  return (
    <section className="bg-white pb-8">
      <div className="max-w-[min(2560px,95vw)] mx-auto px-5 lg:px-8">
        <h2 className="text-3xl lg:text-4xl font-bold text-neutral-900 text-center mb-10" style={{ fontFamily: _pp }}>
          Popular Learning Paths
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-x-6 gap-y-10">
          {LP_PATHS.slice(0, 4).map(p => <LPCard key={p.id} path={p} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------- Filter dropdown (display) ---------- */
function LPDropdown({ label }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('click', h);
    return () => document.removeEventListener('click', h);
  }, [open]);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)}
        className="h-10 px-4 min-w-[150px] rounded-lg border border-neutral-200 bg-white flex items-center justify-between gap-3 text-sm text-neutral-700 hover:border-neutral-400 transition-colors"
        style={{ fontFamily: _la }}>
        {label}
        <Icon name="chevronDown" size={15} className={`text-neutral-400 transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>
      {open && (
        <div className="absolute left-0 top-[calc(100%+6px)] w-full min-w-[180px] bg-white rounded-xl border border-neutral-100 py-1.5 z-30"
             style={{ boxShadow: '0 12px 32px rgba(0,0,0,0.12)' }}>
          {['All', 'Option A', 'Option B', 'Option C'].map(o => (
            <button key={o} onClick={() => setOpen(false)}
              className="w-full text-left px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-50" style={{ fontFamily: _la }}>
              {o}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------- All Learning Paths ---------- */
function LPAll({ anchorRef }) {
  const all = useMemo(() => LP_PATHS.map((p, i) => ({ ...p, _k: p.id + i })), []);
  return (
    <section ref={anchorRef} className="bg-white py-12 scroll-mt-24">
      <div className="max-w-[min(2560px,95vw)] mx-auto px-5 lg:px-8">
        <h2 className="text-3xl lg:text-4xl font-bold text-neutral-900 mb-6" style={{ fontFamily: _pp }}>
          All Learning Paths
        </h2>

        <div className="flex flex-wrap items-center gap-3 mb-9">
          {LP_FILTER_DROPDOWNS.map(d => <LPDropdown key={d} label={d} />)}
          <button className="h-10 px-3 inline-flex items-center gap-1.5 text-sm font-medium text-[#2563eb] hover:underline" style={{ fontFamily: _la }}>
            <Icon name="download" size={15} className="rotate-180" /> Reset
          </button>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-x-6 gap-y-12">
          {all.map(p => <LPCard key={p._k} path={p} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------- FAQ ---------- */
function LPFaq() {
  const [openIdx, setOpenIdx] = useState(0);
  return (
    <section className="bg-[#f4f7fc] py-16">
      <div className="max-w-[920px] mx-auto px-5 lg:px-8">
        <h2 className="text-3xl lg:text-4xl font-bold text-neutral-900 text-center" style={{ fontFamily: _pp }}>
          Common Questions
        </h2>
        <p className="mt-2 text-center text-neutral-500" style={{ fontFamily: _la }}>
          and the answers, of course.{' '}
          <a href="#" className="text-[#2563eb] font-semibold hover:underline">Still not sure? Email us</a>
        </p>

        <div className="mt-9 space-y-3">
          {LP_FAQS.map((f, i) => {
            const open = openIdx === i;
            return (
              <div key={i} className="bg-white rounded-2xl border border-neutral-100 overflow-hidden">
                <button onClick={() => setOpenIdx(open ? -1 : i)}
                  className="w-full flex items-center justify-between gap-4 px-6 py-5 text-left">
                  <span className="text-base font-bold text-neutral-900" style={{ fontFamily: _la }}>{f.q}</span>
                  <Icon name="chevronDown" size={20} className={`text-neutral-500 flex-shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
                </button>
                {open && (
                  <div className="px-6 pb-5 -mt-1">
                    <p className="text-[15px] text-neutral-600 leading-relaxed" style={{ fontFamily: _la }}>{f.a}</p>
                  </div>
                )}
              </div>
            );
          })}
        </div>

        <div className="mt-8 flex justify-center">
          <button className="h-11 px-7 rounded-full bg-white border border-neutral-200 text-sm font-semibold text-neutral-900 hover:bg-neutral-50 transition-colors" style={{ fontFamily: _la }}>
            Load All
          </button>
        </div>
      </div>
    </section>
  );
}

/* ---------- HRD badge ---------- */
function HRDBadge() {
  return (
    <div className="relative w-[104px] h-[104px] rounded-full bg-white flex items-center justify-center flex-shrink-0"
         style={{ boxShadow: '0 6px 20px rgba(0,0,0,0.2)' }}>
      <div className="absolute inset-[6px] rounded-full border border-dashed border-neutral-300" />
      <div className="text-center leading-none">
        <div className="text-[13px] font-extrabold tracking-tight" style={{ fontFamily: _pp }}>
          <span className="text-[#1e3a8a]">HRD</span><span className="text-[#dc2626]">CORP</span>
        </div>
        <div className="mt-1 text-[11px] font-bold tracking-[0.15em] text-[#1e3a8a]" style={{ fontFamily: _pp }}>CLAIMABLE</div>
      </div>
    </div>
  );
}

/* ---------- CTA ---------- */
function LPCta() {
  return (
    <section className="bg-[#1a1623] pt-4 pb-16">
      <div className="max-w-[min(2560px,95vw)] mx-auto px-5 lg:px-8">
        <div className="relative rounded-[28px] px-8 lg:px-16 py-14 overflow-hidden"
             style={{ background: 'linear-gradient(125deg, #0b1f3a 0%, #103a5a 48%, #1d7e94 100%)' }}>
          <HRDBadgeCorner />
          <div className="relative text-center max-w-2xl mx-auto">
            <h2 className="text-4xl lg:text-5xl font-bold text-white" style={{ fontFamily: _pp }}>
              Not sure where to begin?
            </h2>
            <p className="mt-5 text-lg lg:text-xl text-white/85" style={{ fontFamily: _la }}>
              Consult our expert team and we'll help you find the right programme.
            </p>
            <div className="mt-8 flex justify-center">
              <button className="inline-flex items-center gap-3 h-14 pl-2 pr-7 rounded-full bg-[#15121d] hover:bg-black transition-colors"
                style={{ fontFamily: _la }}>
                <Avatar name="Aisha Rahman" size={42} />
                <span className="text-base font-semibold text-white">Get in touch with our team</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HRDBadgeCorner() {
  return (
    <div className="hidden md:block absolute top-8 right-8 lg:right-12 z-10">
      <HRDBadge />
    </div>
  );
}

/* ---------- Page ---------- */
function WebLearningPathsPage() {
  const allRef = useRef(null);
  const onBrowse = () => {
    const el = allRef.current;
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 80;
    window.scrollTo({ top: y, behavior: 'smooth' });
  };
  return (
    <div className="min-h-screen flex flex-col bg-white" style={{ fontFamily: _la }} data-screen-label="Upskill · Program (Learning Paths)">
      <HomeHeader />
      <main className="flex-1">
        <LPHero onBrowse={onBrowse} />
        <LPPopular />
        <LPAll anchorRef={allRef} />
        <LPFaq />
        <LPCta />
      </main>
      <HomeFooter />
    </div>
  );
}

Object.assign(window, { WebLearningPathsPage });
