// ─────────────────────────────────────────────────────────
// ChefVerse · First-run interactive guide for NEW chefs
// Replaces dashboard for profile.member_since-fresh users.
// Pillar canvas: Setup · Learning paths · Briefs · Rewards
// ─────────────────────────────────────────────────────────
const { useState: useStateFR, useMemo: useMemoFR, useEffect: useEffectFR } = React;

const FR_STRINGS = {
  en: {
    eyebrow: "FIRST 60 SECONDS · WELCOME TO CHEFVERSE",
    welcome: (n) => `Welcome, ${n}.`,
    sub: "Tap any tile to explore. We'll keep this guide pinned until you've done your first five things.",
    progress: (d, t) => `${d} of ${t} steps done`,
    setup: "Set up your kitchen",
    setup_sub: "Three small things, two minutes total.",
    paths: "Pick your learning path",
    paths_sub: "Working chefs teaching what actually moved their numbers.",
    briefs: "Earn from briefs",
    briefs_sub: "Real budgets from UFS brand teams. Pick one when you're ready.",
    rewards: "What you'll unlock",
    rewards_sub: "Real kit, real recognition. Earned, not gifted.",
    explore_paths: "Browse all paths",
    explore_briefs: "Browse all briefs",
    explore_rewards: "See full rewards ladder",
    start: "Start now",
    open: "Open",
    skip: "Skip the guide for now",
    done_label: "Done",
    next_label: "Next",
    locked: "Locked",
    minutes: "min",
    payout: "payout",
    deadline_in: (d) => `${d}d to film`,
    your_starter: "Your starter path",
    why_this: "Why this fits you",
    duration: "Total duration",
    setup_items: [
      { id: "profile",   icon: "user",     label: "Add a profile photo & bio",         sub: "Helps brand teams shortlist you faster." },
      { id: "social",    icon: "share",    label: "Connect one social channel",        sub: "We'll auto-pull reach data on submissions." },
      { id: "shipping",  icon: "package",  label: "Confirm your shipping address",     sub: "So we can mail your starter kit on day one." },
    ],
    pillar_titles: { borderless: "Borderless cuisine", streetfood: "Street food couture", futuremenus: "Future menus", flavour: "Flavour at scale" },
  },
  de: {
    eyebrow: "DIE ERSTEN 60 SEKUNDEN · WILLKOMMEN BEI CHEFVERSE",
    welcome: (n) => `Willkommen, ${n}.`,
    sub: "Tippe auf eine Kachel. Wir lassen diesen Guide oben, bis du deine ersten fünf Dinge erledigt hast.",
    progress: (d, t) => `${d} von ${t} Schritten erledigt`,
    setup: "Richte deine Küche ein",
    setup_sub: "Drei Kleinigkeiten, zwei Minuten.",
    paths: "Wähle deinen Lernpfad",
    paths_sub: "Arbeitende Köche, die zeigen, was wirklich Reichweite gebracht hat.",
    briefs: "Verdiene mit Briefings",
    briefs_sub: "Echte Budgets von UFS-Brand-Teams. Greif zu, wenn du soweit bist.",
    rewards: "Was du freischaltest",
    rewards_sub: "Echtes Material, echte Anerkennung. Verdient, nicht geschenkt.",
    explore_paths: "Alle Pfade",
    explore_briefs: "Alle Briefings",
    explore_rewards: "Komplette Belohnungsleiter",
    start: "Jetzt starten",
    open: "Öffnen",
    skip: "Guide vorerst überspringen",
    done_label: "Erledigt",
    next_label: "Weiter",
    locked: "Gesperrt",
    minutes: "Min.",
    payout: "Honorar",
    deadline_in: (d) => `${d} Tage zum Filmen`,
    your_starter: "Dein Starter-Pfad",
    why_this: "Warum das zu dir passt",
    duration: "Gesamtdauer",
    setup_items: [
      { id: "profile",   icon: "user",     label: "Profilbild & Bio hinzufügen",       sub: "Brand-Teams entscheiden so schneller." },
      { id: "social",    icon: "share",    label: "Einen Social-Kanal verbinden",      sub: "Wir ziehen automatisch Reichweitendaten." },
      { id: "shipping",  icon: "package",  label: "Lieferadresse bestätigen",          sub: "Damit dein Starter-Kit gleich rausgeht." },
    ],
    pillar_titles: { borderless: "Borderless Cuisine", streetfood: "Street Food Couture", futuremenus: "Future Menus", flavour: "Flavour at Scale" },
  },
  id: {
    eyebrow: "60 DETIK PERTAMA · SELAMAT DATANG DI CHEFVERSE",
    welcome: (n) => `Selamat datang, ${n}.`,
    sub: "Ketuk salah satu kartu untuk mulai. Panduan ini menempel sampai lima langkah pertamamu selesai.",
    progress: (d, t) => `${d} dari ${t} langkah selesai`,
    setup: "Atur dapurmu",
    setup_sub: "Tiga hal kecil, total dua menit.",
    paths: "Pilih jalur belajarmu",
    paths_sub: "Chef aktif yang mengajar hal yang benar-benar mengangkat angka mereka.",
    briefs: "Dapatkan dari brief",
    briefs_sub: "Budget nyata dari tim brand UFS. Ambil saat kamu siap.",
    rewards: "Yang akan kamu buka",
    rewards_sub: "Perlengkapan nyata, pengakuan nyata. Diperoleh, bukan dihadiahkan.",
    explore_paths: "Lihat semua jalur",
    explore_briefs: "Lihat semua brief",
    explore_rewards: "Lihat tangga reward lengkap",
    start: "Mulai sekarang",
    open: "Buka",
    skip: "Lewati panduan dulu",
    done_label: "Selesai",
    next_label: "Lanjut",
    locked: "Terkunci",
    minutes: "mnt",
    payout: "honor",
    deadline_in: (d) => `${d} hari syuting`,
    your_starter: "Jalur starter kamu",
    why_this: "Kenapa cocok untukmu",
    duration: "Durasi total",
    setup_items: [
      { id: "profile",   icon: "user",     label: "Tambahkan foto profil & bio",       sub: "Tim brand bisa pilih kamu lebih cepat." },
      { id: "social",    icon: "share",    label: "Hubungkan satu kanal sosial",       sub: "Kami tarik data reach otomatis." },
      { id: "shipping",  icon: "package",  label: "Konfirmasi alamat pengiriman",      sub: "Supaya starter kit dikirim hari pertama." },
    ],
    pillar_titles: { borderless: "Borderless Cuisine", streetfood: "Street Food Couture", futuremenus: "Future Menus", flavour: "Flavour at Scale" },
  },
};

function FirstRunHome({ locale, profile, onRoute, onOpenCourse, onOpenBrief, onOpenModule, onSkip, onReplayTour }) {
  const v2 = true;
  const s = FR_STRINGS[locale];
  const t = window.I18N[locale];
  const firstName = profile.name.split(" ")[0];

  // Starter path = first course
  const starter = window.COURSES[0];
  const starterModules = (window.COURSE_MODULES_BY_ID && window.COURSE_MODULES_BY_ID[starter.id]) || window.COURSE_MODULES;
  const progress = window.useCourseProgress();

  // Top 3 briefs in market
  const liveBriefs = window.BRIEFS.filter(b => b.market.includes(locale)).slice(0, 2);

  // Rewards ladder — first 4
  const rewardLadder = window.REWARDS.slice(0, 4);

  // overall step counter — modules + briefs
  const totalSteps = 3;
  const stepsDone =
    (profile.modules_done > 0 ? 1 : 0)
    + (profile.briefs_won > 0 ? 1 : 0)
    + (profile.streak >= 3 ? 1 : 0);

  return (
    <div className="page fr-page">
      {/* HEADER */}
      <div className="fr-header">
        <div>
          <h1 className="fr-greet">{s.welcome(firstName)}</h1>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          {onReplayTour && (
            <button className="link-btn" onClick={onReplayTour}>
              <Icon name="play" size={12} /> {locale === "de" ? "Guide ansehen" : locale === "id" ? "Lihat panduan" : "Watch the guide"}
            </button>
          )}
          <button className="link-btn fr-skip" onClick={onSkip}>{s.skip} <Icon name="arrow-right" size={11} /></button>
        </div>
      </div>

      {/* CANVAS — three pillars */}
      <div className="fr-canvas">
        {/* PATHS */}
        <section className="fr-tile fr-tile-paths" data-tour="fr-paths">
          <div className="fr-tile-h">
            <div>
              <h2 className="fr-tile-title">{v2 ? (locale === "de" ? "Starte mit Modul 01" : locale === "id" ? "Mulai dari Modul 01" : "Start with Module 01") : s.paths}</h2>
              <p className="fr-tile-sub display-italic" style={{ whiteSpace: "nowrap" }}>{v2 ? (locale === "de" ? "Acht Module — in Reihenfolge freigeschaltet, von Profis gefilmt." : locale === "id" ? "Delapan modul — dibuka berurutan, difilmkan oleh chef profesional." : "Eight modules — unlocked in order, filmed by working chefs.") : s.paths_sub}</p>
            </div>
            <button className="link-btn" onClick={() => onRoute("courses")}>{v2 ? (locale === "de" ? "Alle Module" : locale === "id" ? "Semua modul" : "Browse all modules") : s.explore_paths} <Icon name="arrow-right" size={11} /></button>
          </div>

          {v2 ? (
            <div className="fr-v2-mods">
              {/* Featured: Module 01 — the entry point for new chefs */}
              {(() => {
                const fm = starterModules[0];
                if (!fm) return null;
                const fCover = (window.MODULE_COVERS && window.MODULE_COVERS[0]) || starter.cover;
                const fMin = Math.floor((fm.dur || 360) / 60);
                const fTotal = progress.chapterCount(starter.id, 0);
                const minutesLab = locale === "de" ? "Min" : locale === "id" ? "menit" : "min";
                const chaptersLab = locale === "de" ? "Kapitel" : locale === "id" ? "bab" : "chapters";
                const ofLab = locale === "de" ? "von" : locale === "id" ? "dari" : "of";
                return (
                  <div className="featured-path featured-path-mod" data-tour="fr-starter">
                    <div className="featured-cover" style={{ background: fCover }}>
                      <CoverImage src={window.PHOTOS && window.PHOTOS.moduleCoverFor(starter.id, 0)} dim={0.45} />
                      <div className="featured-cover-inner">
                        <span className="eyebrow" style={{ color: "#fff" }}>
                          {locale === "de" ? "STARTE HIER" : locale === "id" ? "MULAI DI SINI" : "START HERE"}
                        </span>
                        <div className="featured-h">{fm.title[locale]}</div>
                      </div>
                    </div>
                    <div className="featured-meta">
                      <div className="featured-pill display-italic">
                        {locale === "de" ? "Modul" : locale === "id" ? "Modul" : "Module"} 01 {ofLab} {String(starterModules.length).padStart(2, "0")} · with {starter.instructor}
                      </div>
                      <h2>{fm.title[locale]}</h2>
                      <p className="lead display-italic" style={{ color: "var(--smoke)" }}>
                        {locale === "de"
                          ? `${fTotal} kurze Kapitel mit Praxis und einem Test am Ende. Etwa ${fMin} Min.`
                          : locale === "id"
                            ? `${fTotal} bab pendek dengan praktik dan kuis di akhir. Sekitar ${fMin} menit.`
                            : `${fTotal} short chapters with hands-on practice and a quick check at the end. About ${fMin} minutes.`}
                      </p>
                      <div className="featured-stats">
                        <div className="fs-item">
                          <div className="fs-val">{fTotal}</div>
                          <div className="fs-lab">{chaptersLab}</div>
                        </div>
                        <div className="fs-item">
                          <div className="fs-val">{fMin}</div>
                          <div className="fs-lab">{minutesLab}</div>
                        </div>
                        <div className="fs-item">
                          <div className="fs-val">{starter.level[locale]}</div>
                          <div className="fs-lab">{locale === "de" ? "Level" : locale === "id" ? "Level" : "Level"}</div>
                        </div>
                      </div>
                      <div style={{ display: "flex", gap: 8 }}>
                        <button className="btn btn-primary" onClick={() => onOpenModule && onOpenModule(starter.id, 0)}>
                          <Icon name="play" size={14} /> {locale === "de" ? "Modul starten" : locale === "id" ? "Mulai modul" : "Start module"}
                        </button>
                        <button className="btn btn-outline" onClick={() => onRoute("courses")}>
                          <Icon name="list-video" size={14} /> {locale === "de" ? "Alle Module" : locale === "id" ? "Semua modul" : "All modules"}
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })()}
              {/* Modules 02–04 in a row of 3 under the hero */}
              <div className="mod-grid mod-grid-3" style={{ marginTop: 16 }}>
                {starterModules.slice(1, 4).map((m, i) => {
                  const idx = i + 1;
                  const total = progress.chapterCount(starter.id, idx);
                  return (
                    <window.ModuleCard
                      key={idx}
                      module={m}
                      idx={idx}
                      locale={locale}
                      status="locked"
                      pct={0}
                      done={0}
                      total={total}
                      onClick={() => onOpenModule && onOpenModule(starter.id, idx)}
                    />
                  );
                })}
              </div>
            </div>
          ) : (
            <>
              <button className="fr-starter" data-tour="fr-starter" onClick={() => onOpenCourse(starter.id)}>
                <div className="fr-starter-cover" style={{ background: starter.cover }}>
                  <div className="fr-starter-tag">{s.your_starter}</div>
                  <div className="fr-starter-play"><Icon name="play" size={22} style={{ marginLeft: 2 }} /></div>
                </div>
                <div className="fr-starter-body">
                  <div className="eyebrow">{starter.level[locale]} · {starter.modules} {t.course.modules} · {starter.hours} {t.course.hours}</div>
                  <h3 className="fr-starter-title">{starter.title[locale]}</h3>
                  <p className="fr-starter-instr">{starter.instructor}</p>
                  <div className="fr-starter-modlist">
                    {starterModules.slice(0, 8).map((m, i) => (
                      <div key={m.idx ?? i} className="fr-mod-pill not-started">
                        <span className="fr-mod-i">{String(i + 1).padStart(2, "0")}</span>
                        <span className="fr-mod-t">{m.title[locale]}</span>
                        <span className="fr-mod-d">{Math.round(m.dur / 60)} {s.minutes}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </button>

              <div className="fr-paths-rail">
                {window.COURSES.slice(1, 4).map((c) => {
                  const pillar = window.PILLARS[c.pillar];
                  return (
                    <button key={c.id} className="course-card" onClick={() => onOpenCourse(c.id)}>
                      <div className="course-cover" style={{ background: c.cover }}>
                        <CoverImage src={window.PHOTOS && window.PHOTOS.courseCoverFor(c.id)} />
                        <div className="course-pillar-tag" style={{ background: "rgba(255,255,255,0.92)", color: pillar.color }}>
                          {pillar.name[locale]}
                        </div>
                      </div>
                      <div className="course-body">
                        <div className="course-instructor display-italic">with {c.instructor}</div>
                        <div className="course-title">{c.title[locale]}</div>
                        <div className="subtle course-desc">{c.desc[locale]}</div>
                        <div className="course-meta">
                          <span className="course-meta-item"><Icon name="list-video" size={12} /> {c.modules} {t.course.modules}</span>
                          <span className="course-dot" />
                          <span className="course-meta-item"><Icon name="clock" size={12} /> {c.hours} {t.course.hours}</span>
                          <span className="course-dot" />
                          <span className="course-meta-item">{c.level[locale]}</span>
                        </div>
                        <div className="course-footer">
                          <span className="course-cta">
                            {t.course.enroll} <Icon name="arrow-right" size={12} />
                          </span>
                        </div>
                      </div>
                    </button>
                  );
                })}
              </div>
            </>
          )}
        </section>

        {/* BRIEFS */}
        <section className="fr-tile fr-tile-briefs" data-tour="fr-briefs">
          <div className="fr-tile-h">
            <div>
              <h2 className="fr-tile-title">{s.briefs}</h2>
              <p className="fr-tile-sub display-italic">{s.briefs_sub}</p>
            </div>
            <button className="link-btn" onClick={() => onRoute("briefs")}>{s.explore_briefs} <Icon name="arrow-right" size={11} /></button>
          </div>
          <div className="fr-briefs-rail brief-grid">
            {liveBriefs.map((b, idx) => (
              <div key={b.id} data-tour={idx === 0 ? "fr-brief-card" : undefined}>
                <BriefCard brief={b} locale={locale} onOpen={() => onOpenBrief(b.id)} layout="grid" />
              </div>
            ))}
          </div>
        </section>

        {/* REWARDS LADDER */}
        <section className="fr-tile fr-tile-rewards" data-tour="fr-rewards">
          <div className="fr-tile-h">
            <div>
              <h2 className="fr-tile-title">{s.rewards}</h2>
              <p className="fr-tile-sub display-italic">{s.rewards_sub}</p>
            </div>
            <button className="link-btn" onClick={() => onRoute("rewards")}>{s.explore_rewards} <Icon name="arrow-right" size={11} /></button>
          </div>
          <ol className="fr-rewards-ladder v2">
            {rewardLadder.map((r, i) => {
              const isPhysical = r.kind === "physical";
              const triggerKind = r.trigger.startsWith("module") ? "module" : "brief";
              const n = parseInt(r.trigger.split("_")[1], 10);
              return (
                <li key={r.id} className={"fr-reward-row v2 " + (isPhysical ? "is-physical" : "is-digital")}>
                  <div className="fr-reward-thumb">
                    <div className="fr-reward-thumb-icon">
                      {isPhysical ? <Icon name="package" size={22} /> : <Icon name="award" size={22} />}
                    </div>
                    <div className="fr-reward-thumb-tag">{isPhysical ? "KIT" : "BADGE"}</div>
                  </div>
                  <div className="fr-reward-body">
                    <div className="fr-reward-title">{r.title[locale]}</div>
                    <div className="fr-reward-sub">{r.sub[locale]}</div>
                  </div>
                  <div className="fr-reward-trigger">
                    <div className="fr-reward-trigger-num">{n}</div>
                    <div className="fr-reward-trigger-lab">
                      {triggerKind === "module"
                        ? (n === 1 ? "module" : "modules")
                        : (n === 1 ? "brief" : "briefs")}
                    </div>
                  </div>
                </li>
              );
            })}
          </ol>
        </section>
      </div>
    </div>
  );
}

window.FirstRunHome = FirstRunHome;
