/* global React, Icons, FitPaper, CoverFit, makeCoverDoc, SAMPLE_RESUME,
   PROFILES, getProfile, profileForTemplate, TEMPLATES, COVER_TEMPLATES, isProTemplate */
// ============================================================
//  Gallery — profile-first template picker (résumés + cover letters)
// ============================================================

const ALL_PROFILE = { id: "all", name: "All", icon: "grid", accent: "#e6e600", accent2: "#7deb00" };

// short chip labels (full names stay in the banner)
const CHIP_LABEL = {
  all: "All", swe: "Engineering", design: "Design", finance: "Finance",
  marketing: "Marketing", sales: "Sales", health: "Healthcare",
  data: "Data Science", grad: "New Graduate",
};

function ProfileRail({ profileId, setProfileId, mode }) {
  const items = [ALL_PROFILE, ...PROFILES];
  return (
    <div className="prof-rail">
      {items.map((p) => {
        const Ic = Icons[p.icon] || Icons.user;
        const on = p.id === profileId;
        const total = mode === "covers" ? COVER_TEMPLATES.length : TEMPLATES.length;
        const sub = p.id === "all" ? `${total} designs` : `${p.designs.length} designs`;
        return (
          <button key={p.id} className={`prof-chip ${on ? "on" : ""}`}
            style={{ "--pp": p.accent, "--pp2": p.accent2 }}
            onClick={() => setProfileId(p.id)}>
            <span className="prof-chip-ic"><Ic size={17} /></span>
            <span className="prof-chip-txt">
              <b>{CHIP_LABEL[p.id] || p.name}</b>
              <em>{sub}</em>
            </span>
          </button>
        );
      })}
    </div>
  );
}

function Gallery({ mode, setMode, profileId, setProfileId, onPickResume, onPickCover, currentTemplate }) {
  const isAll = profileId === "all";
  const profile = isAll ? ALL_PROFILE : getProfile(profileId);
  const coverDoc = React.useMemo(() => makeCoverDoc(isAll ? "design" : profileId), [profileId, isAll]);

  // résumé designs to show + the data each renders with
  const resumeList = isAll
    ? TEMPLATES.map((t) => ({ tid: t.id, data: (profileForTemplate(t.id) || {}).data || SAMPLE_RESUME, pid: (profileForTemplate(t.id) || {}).id || "design" }))
    : profile.designs.map((tid) => ({ tid, data: profile.data, pid: profile.id }));

  // cover designs to show — each cover matches a résumé, so a profile shows the
  // covers paired to its résumé designs (All shows every cover)
  const coverList = isAll
    ? COVER_TEMPLATES
    : COVER_TEMPLATES.filter((ct) => profile.designs.includes(ct.match));

  const designCount = mode === "covers" ? coverList.length : resumeList.length;

  return (
    <div className="gallery wrap">
      <header className="gal-head">
        <div>
          <div className="eyebrow rise">Template gallery</div>
          <h1 className="gal-title rise" style={{ animationDelay: "0.06s" }}>
            Built for your field.
          </h1>
          <p className="gal-sub rise" style={{ animationDelay: "0.12s" }}>
            Choose your field — each design comes filled in with the right words and
            numbers for your job. Switch the look anytime; your details stay put.
          </p>
        </div>
        <div className="gal-modes rise" style={{ animationDelay: "0.16s" }}>
          <button className={`seg ${mode === "resumes" ? "on" : ""}`} onClick={() => setMode("resumes")}>
            <Icons.grid size={14} /> Résumés
          </button>
          <button className={`seg ${mode === "covers" ? "on" : ""}`} onClick={() => setMode("covers")}>
            <Icons.pen size={14} /> Cover letters
          </button>
        </div>
      </header>

      <ProfileRail profileId={profileId} setProfileId={setProfileId} mode={mode} />

      <div className="prof-banner" style={{ "--pp": profile.accent, "--pp2": profile.accent2 }}>
        <span className="prof-banner-ic">{(() => { const Ic = Icons[profile.icon] || Icons.user; return <Ic size={18} />; })()}</span>
        <div>
          <h2>{isAll ? (mode === "covers" ? "All cover letters" : "All résumé designs") : (profile.name + (mode === "covers" ? " · cover letters" : " résumés"))}</h2>
          <p>{isAll
            ? (mode === "covers" ? "Every cover-letter layout in the studio. Pick one and we'll draft it for you." : "Every layout in the studio. Each preview is filled with sample content for its field.")
            : profile.blurb}</p>
        </div>
        <span className="prof-banner-n">{designCount} designs</span>
      </div>

      {mode === "resumes" ? (
        <div className="gal-grid">
          {resumeList.map(({ tid, data, pid }, i) => {
            const t = TEMPLATES.find((x) => x.id === tid) || TEMPLATES[0];
            return (
              <article className="tpl-card" key={isAll ? tid + i : tid} style={{ animationDelay: `${0.05 + i * 0.04}s` }}>
                <div className="tpl-thumb">
                  <div className="tpl-thumb-inner">
                    <FitPaper data={data} templateId={tid} />
                  </div>
                  {isProTemplate(tid) && <span className="tpl-pro"><Icons.crown size={11} /> PRO</span>}
                  {currentTemplate === tid && <span className="tpl-current"><Icons.check size={12} /> In use</span>}
                  <div className="tpl-hover">
                    <button className="btn btn-primary btn-sm" onClick={() => onPickResume(pid, tid)}>
                      Use this design <Icons.arrow size={15} />
                    </button>
                  </div>
                </div>
                <div className="tpl-meta">
                  <div className="tpl-meta-top">
                    <h3>{t.name}</h3>
                    <span className="tpl-tag">{t.tag}</span>
                  </div>
                  <p>{t.blurb}</p>
                  <div className="tpl-swatches">
                    {t.swatch.map((c, j) => <span key={j} style={{ background: c }} />)}
                  </div>
                </div>
              </article>
            );
          })}
        </div>
      ) : (
        <div className="gal-grid">
          {coverList.map((ct, i) => (
            <article className="tpl-card" key={ct.id} style={{ animationDelay: `${0.05 + i * 0.06}s` }}>
              <div className="tpl-thumb cover-thumb">
                <div className="tpl-thumb-inner">
                  <CoverFit doc={coverDoc} templateId={ct.id} />
                </div>
                <div className="tpl-hover">
                  <button className="btn btn-primary btn-sm" onClick={() => onPickCover(isAll ? "design" : profile.id, ct.id)}>
                    Use this design <Icons.arrow size={15} />
                  </button>
                </div>
              </div>
              <div className="tpl-meta">
                <div className="tpl-meta-top">
                  <h3>{ct.name}</h3>
                  <span className="tpl-tag">{ct.tag}</span>
                </div>
                <p>{ct.blurb}</p>
                <div className="tpl-swatches">
                  {ct.swatch.map((c, j) => <span key={j} style={{ background: c }} />)}
                </div>
              </div>
            </article>
          ))}
        </div>
      )}
    </div>
  );
}

window.Gallery = Gallery;
