/* NutriDMS, Help & Docs center
   ─────────────────────────────────────────────────────────────
   Role-tailored, searchable help. Each article shows a LIVE preview
   of the real screen (via ?docpreview iframe) and deep-links to it.
   Content + helpers live in help-docs-data.js.
   ───────────────────────────────────────────────────────────── */
const { useState: hUseState, useMemo: hUseMemo, useRef: hUseRef, useEffect: hUseEffect } = React;

function roleLabel(role) {
  try { return (ROLES[role] && ROLES[role].label) || role; } catch (e) { return role; }
}

/* ── Live, non-interactive preview of a real screen ──
   Renders the actual screen component INLINE (same React tree, no iframe,
   no app re-boot) inside a frozen context, scaled to fit. Instantaneous. */
const HD_PREVIEW_BASE_W = 1180; // desktop render width, then scaled down

// Every article preview is a real, full-fidelity screenshot of the live screen
// (inline scaled renders broke on complex layouts). Keyed by the article's preview id.
const HD_PREVIEW_SHOTS = {
  "dashboard": "assets/help-previews/dashboard.png",
  "recipes": "assets/help-previews/recipes.png",
  "ingredients": "assets/help-previews/ingredients.png",
  "my-questions": "assets/help-previews/my-questions.png",
  "published": "assets/help-previews/published.png",
  "review-queue": "assets/help-previews/review-queue.png",
  "nutrition-requests": "assets/help-previews/nutrition-requests.png",
  "qa-review": "assets/help-previews/qa-review.png",
  "compliance-dashboard": "assets/help-previews/compliance-dashboard.png",
  "health-conditions": "assets/help-previews/health-conditions.png",
  "allergen-table": "assets/help-previews/allergen-table.png",
  "audit": "assets/help-previews/audit.png",
  "label-studio": "assets/help-previews/label-studio.png",
  "gs1": "assets/help-previews/gs1.png",
  "offerings": "assets/help-previews/offerings.png",
  "meal-programs": "assets/help-previews/meal-programs.png",
  "calendar": "assets/help-previews/calendar.png",
  "assignments": "assets/help-previews/assignments.png",
  "create-assignment": "assets/help-previews/create-assignment.png",
  "my-assignments": "assets/help-previews/my-assignments.png",
  "reports": "assets/help-previews/reports.png",
  "analytics": "assets/help-previews/analytics.png",
  "nutrition-insights": "assets/help-previews/nutrition-insights.png",
  "workflow": "assets/help-previews/workflow.png",
  "integrations": "assets/help-previews/integrations.png",
  "settings": "assets/help-previews/settings.png",
  "users": "assets/help-previews/users.png",
  "permissions": "assets/help-previews/permissions.png",
  "add-ingredient": "assets/help-previews/add-ingredient.png",
  "upload": "assets/help-previews/upload.png",
};

function hdFrozenCtx(pageId, role) {
  const noop = () => {};
  const sampleRecipe = (typeof RECIPES !== "undefined" && RECIPES[0]) || null;
  return {
    role, setRole: noop,
    lang: "en", setLang: noop,
    page: pageId, setPage: noop,
    activeRecipe: sampleRecipe, setActiveRecipe: noop, openRecipe: noop,
    activeIngredient: null, setActiveIngredient: noop, openIngredient: noop,
    reviewKind: "recipe", setReviewKind: noop, openReview: noop,
    detailFocus: null, setDetailFocus: noop,
    toast: noop, openQuickAssign: noop, openCompliance: noop,
    openCmd: noop, openNotif: noop,
    sidebarCollapsed: false, setSidebarCollapsed: noop,
    mobileNav: false, setMobileNav: noop,
    navLayout: "sidebar", setNavLayout: noop,
  };
}

function DocPreview({ pageId, role }) {
  const stageRef = hUseRef(null);
  const scalerRef = hUseRef(null);
  const [scale, setScale] = hUseState(0.55);
  const [stageH, setStageH] = hUseState(460);

  // Some screens are standalone iframe builders that don't render correctly when
  // scaled inline — show a real screenshot of them instead of the live component.
  const shot = HD_PREVIEW_SHOTS[pageId];

  const measure = React.useCallback(() => {
    const stage = stageRef.current, scaler = scalerRef.current;
    if (!stage || !scaler) return;
    const s = stage.clientWidth / HD_PREVIEW_BASE_W;
    setScale(s);
    setStageH(Math.max(300, Math.min(scaler.scrollHeight * s, 540)));
  }, []);

  hUseEffect(() => {
    measure();
    const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : null;
    if (ro && stageRef.current) ro.observe(stageRef.current);
    const t1 = setTimeout(measure, 60);
    const t2 = setTimeout(measure, 320);
    return () => { if (ro) ro.disconnect(); clearTimeout(t1); clearTimeout(t2); };
  }, [pageId, role, measure]);

  const ctx = hUseMemo(() => hdFrozenCtx(pageId, role), [pageId, role]);
  if (!pageId) return null;
  const RouterCmp = typeof Router === "function" ? Router : null;

  if (shot) {
    return (
      <div className="hd-preview">
        <div className="hd-preview-bar">
          <span className="hd-dot"></span><span className="hd-dot"></span><span className="hd-dot"></span>
          <span className="hd-preview-url"><Icon name="eye" size={11} /> preview — exactly what you'll see</span>
        </div>
        <div className="hd-preview-shotwrap">
          <img src={shot} alt="Screen preview" className="hd-preview-shot" loading="lazy" />
        </div>
      </div>);
  }

  return (
    <div className="hd-preview">
      <div className="hd-preview-bar">
        <span className="hd-dot"></span><span className="hd-dot"></span><span className="hd-dot"></span>
        <span className="hd-preview-url"><Icon name="eye" size={11} /> live preview — exactly what you'll see</span>
      </div>
      <div className="hd-preview-stage" ref={stageRef} style={{ height: stageH }}>
        <div
          className="hd-preview-scaler"
          ref={scalerRef}
          style={{ width: HD_PREVIEW_BASE_W, transform: `scale(${scale})`, transformOrigin: "top left" }}>
          <AppCtx.Provider value={ctx}>
            <div className="app doc-preview-app" data-theme="light" data-density="regular">
              <div className="page">{RouterCmp ? <RouterCmp /> : null}</div>
            </div>
          </AppCtx.Provider>
        </div>
        {/* transparent shield so the preview stays non-interactive */}
        <div className="hd-preview-shield"></div>
      </div>
    </div>);
}

/* ── One article, full view ── */
function DocArticle({ article, role, onOpenPage, onSelect, onBack }) {
  const a = article;
  const [openP, setOpenP] = hUseState(0);
  const [helpful, setHelpful] = hUseState(null);
  const [q, setQ] = hUseState("");
  const [sent, setSent] = hUseState(false);
  const canUse = helpRoleCan(a, role);
  hUseEffect(() => { setOpenP(0); setHelpful(null); setQ(""); setSent(false); }, [a.id]);

  return (
    <article className="hd-article">
      <button className="hd-back" onClick={onBack}><Icon name="arrow-left" size={15} /> All help</button>

      <div className="hd-art-head">
        <div className="hd-art-ic"><Icon name={a.icon} size={22} /></div>
        <div>
          <h1>{a.title}</h1>
          <p className="hd-art-sum">{a.summary}</p>
        </div>
      </div>

      {!canUse &&
        <div className="hd-locked-note">
          <Icon name="lock" size={15} />
          <span>This feature isn't in your access right now. You can still read how it works — ask an Admin if you need it turned on.</span>
        </div>}

      {a.page && canUse &&
        <div className="hd-openbar">
          <button className="btn primary" onClick={() => onOpenPage(a.page)}>
            <Icon name="external-link" size={15} /> Open this page
          </button>
          <span className="hd-openbar-hint">Takes you straight to the real screen.</span>
        </div>}

      {a.preview && <DocPreview pageId={a.preview} role={role} />}

      <section className="hd-block">
        <h2><Icon name="info" size={16} /> What it is</h2>
        <p>{a.what}</p>
      </section>

      {a.steps && a.steps.length > 0 &&
        <section className="hd-block">
          <h2><Icon name="list-checks" size={16} /> How to use it</h2>
          <ol className="hd-steps">
            {a.steps.map((s, i) => <li key={i}><span className="hd-step-n">{i + 1}</span><span>{s}</span></li>)}
          </ol>
        </section>}

      {a.tips && a.tips.length > 0 &&
        <section className="hd-block hd-tips">
          <h2><Icon name="lightbulb" size={16} /> Handy tips</h2>
          <ul>{a.tips.map((t, i) => <li key={i}><Icon name="check" size={13} /><span>{t}</span></li>)}</ul>
        </section>}

      {a.problems && a.problems.length > 0 &&
        <section className="hd-block">
          <h2><Icon name="life-buoy" size={16} /> Stuck? Common questions</h2>
          <div className="hd-faq">
            {a.problems.map((p, i) => (
              <div key={i} className={`hd-faq-item ${openP === i ? "open" : ""}`}>
                <button className="hd-faq-q" onClick={() => setOpenP(openP === i ? -1 : i)}>
                  <span>{p.q}</span><Icon name="chevron-down" size={16} />
                </button>
                <div className="hd-faq-a"><p>{p.a}</p></div>
              </div>
            ))}
          </div>
        </section>}

      {a.related && a.related.length > 0 &&
        <section className="hd-block">
          <h2><Icon name="link" size={16} /> Related help</h2>
          <div className="hd-related">
            {a.related.map((id) => {
              const r = helpDocsById(id);
              if (!r) return null;
              return (
                <button key={id} className="hd-related-item" onClick={() => onSelect(r)}>
                  <Icon name={r.icon} size={16} /><span>{r.title}</span><Icon name="chevron-right" size={14} />
                </button>);
            })}
          </div>
        </section>}

      {/* Was this helpful */}
      <div className="hd-helpful">
        {helpful === null ? (
          <React.Fragment>
            <span>Was this helpful?</span>
            <button className="btn ghost sm" onClick={() => setHelpful(true)}><Icon name="thumbs-up" size={14} /> Yes</button>
            <button className="btn ghost sm" onClick={() => setHelpful(false)}><Icon name="thumbs-down" size={14} /> Not really</button>
          </React.Fragment>
        ) : helpful ? (
          <span className="hd-helpful-done"><Icon name="check-circle" size={15} /> Thanks for the feedback!</span>
        ) : (
          <span className="hd-helpful-done"><Icon name="heart" size={15} /> Thanks — we'll make this clearer.</span>
        )}
      </div>

      {/* Ask a question */}
      <div className="hd-ask">
        <h3><Icon name="message-circle-question" size={16} /> Still need help?</h3>
        {sent ? (
          <div className="hd-ask-sent"><Icon name="check-circle" size={16} /> Sent. Our team will get back to you.</div>
        ) : (
          <React.Fragment>
            <textarea placeholder={`Ask about "${a.title}"…`} value={q} onChange={(e) => setQ(e.target.value)}></textarea>
            <button className="btn primary" disabled={!q.trim()} onClick={() => setSent(true)}>
              <Icon name="send" size={14} /> Send question
            </button>
          </React.Fragment>
        )}
      </div>
    </article>);
}

/* ── Card in the hub grid ── */
function DocCard({ article, role, onSelect }) {
  const canUse = helpRoleCan(article, role);
  return (
    <button className={`hd-card ${canUse ? "" : "locked"}`} onClick={() => onSelect(article)}>
      <div className="hd-card-ic"><Icon name={article.icon} size={18} /></div>
      <div className="hd-card-body">
        <div className="hd-card-title">{article.title}{!canUse && <Icon name="lock" size={12} className="hd-card-lock" />}</div>
        <div className="hd-card-sum">{article.summary}</div>
      </div>
      <Icon name="chevron-right" size={16} className="hd-card-arrow" />
    </button>);
}

/* ── Main screen ── */
function HelpDocsScreen() {
  const { role, setPage } = useApp();
  const [query, setQuery] = hUseState("");
  const [selected, setSelected] = hUseState(null);
  const [showOther, setShowOther] = hUseState(false);
  const scrollRef = hUseRef(null);

  const results = hUseMemo(() => helpDocsSearch(query, role), [query, role]);
  const searching = query.trim().length > 0;

  const select = (a) => { setSelected(a); if (scrollRef.current) scrollRef.current.scrollTop = 0; window.scrollTo(0, 0); };
  const openPage = (pid) => setPage(pid);

  // Deep-link: global search can request a specific article via window.__helpOpenDoc
  hUseEffect(() => {
    const id = window.__helpOpenDoc; window.__helpOpenDoc = null;
    if (id && window.helpDocsById) { const d = window.helpDocsById(id); if (d) setSelected(d); }
  }, []);

  // categories, split by what this role can use
  const cats = hUseMemo(() => HELP_CATS.map((c) => ({
    ...c,
    mine: helpDocsByCat(c.id, role).filter((a) => helpRoleCan(a, role)),
    other: helpDocsByCat(c.id, role).filter((a) => !helpRoleCan(a, role)),
  })).filter((c) => c.mine.length || c.other.length), [role]);

  const otherCount = hUseMemo(() => HELP_DOCS.filter((a) => !helpRoleCan(a, role)).length, [role]);

  return (
    <div className="hd-wrap" ref={scrollRef}>
      <Crumbs path={[{ label: "Help & Docs" }]} />

      {/* header + search */}
      <div className="hd-hero">
        <div className="hd-hero-top">
          <div>
            <h1 className="page-title">Help &amp; Docs</h1>
            <p className="page-sub">Simple, step-by-step guides — showing help for your account.</p>
          </div>
          <span className="hd-role-chip"><Icon name="user" size={13} /> {roleLabel(role)}</span>
        </div>
        <div className="hd-search">
          <Icon name="search" size={18} />
          <input
            placeholder="Search help — try “new recipe”, “label”, “barcode”…"
            value={query}
            onChange={(e) => { setQuery(e.target.value); setSelected(null); }}
          />
          {query && <button className="hd-search-clear" onClick={() => setQuery("")}><Icon name="x" size={15} /></button>}
        </div>
      </div>

      {/* SEARCH RESULTS */}
      {searching ? (
        <div className="hd-results">
          <p className="hd-results-count">{results.length} result{results.length === 1 ? "" : "s"} for “{query}”</p>
          {results.length === 0 ? (
            <div className="hd-empty">
              <Icon name="search-x" size={28} />
              <p>No help found. Try simpler words, or ask us below.</p>
            </div>
          ) : (
            <div className="hd-card-grid">
              {results.map((a) => <DocCard key={a.id} article={a} role={role} onSelect={select} />)}
            </div>
          )}
        </div>
      ) : selected ? (
        /* ARTICLE VIEW */
        <div className="hd-body single">
          <DocArticle article={selected} role={role} onOpenPage={openPage} onSelect={select} onBack={() => setSelected(null)} />
        </div>
      ) : (
        /* HUB */
        <div className="hd-hub">
          {/* getting started strip */}
          <div className="hd-start">
            {helpDocsByCat("start", role).map((a) => (
              <button key={a.id} className="hd-start-tile" onClick={() => select(a)}>
                <div className="hd-start-ic"><Icon name={a.icon} size={20} /></div>
                <div className="hd-start-title">{a.title}</div>
                <div className="hd-start-sum">{a.summary}</div>
              </button>
            ))}
          </div>

          {cats.filter((c) => c.id !== "start").map((c) => (
            c.mine.length ? (
              <section key={c.id} className="hd-cat">
                <div className="hd-cat-head"><Icon name={c.icon} size={17} /><h2>{c.label}</h2></div>
                <div className="hd-card-grid">
                  {c.mine.map((a) => <DocCard key={a.id} article={a} role={role} onSelect={select} />)}
                </div>
              </section>
            ) : null
          ))}

          {/* other features (not in this role's access) */}
          {otherCount > 0 && (
            <section className="hd-cat hd-other">
              <button className="hd-other-toggle" onClick={() => setShowOther(!showOther)}>
                <Icon name={showOther ? "chevron-down" : "chevron-right"} size={16} />
                <span>Other features ({otherCount}) — not in your access, but here's how they work</span>
              </button>
              {showOther && (
                <div className="hd-card-grid" style={{ marginTop: 12 }}>
                  {HELP_DOCS.filter((a) => !helpRoleCan(a, role)).map((a) => (
                    <DocCard key={a.id} article={a} role={role} onSelect={select} />
                  ))}
                </div>
              )}
            </section>
          )}
        </div>
      )}
    </div>);
}

if (typeof window !== "undefined") window.HelpDocsScreen = HelpDocsScreen;
