/* =========================================================================
   Emerge Profit — Centro de Ayuda · plugin
   Body-only React app. Embebido entre el header y footer del sitio.
   ========================================================================= */

const { useState, useMemo, useEffect, useRef } = React;

/* ---------------- Icons (Lucide-style, inline SVG) ---------------- */
const Ico = {
  Book:     (p) => <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>,
  Search:   (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>,
  X:        (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 6 6 18M6 6l12 12"/></svg>,
  Plus:     (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 5v14M5 12h14"/></svg>,
  Help:     (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10"/><path d="M9.1 9a3 3 0 0 1 5.8 1c0 2-3 3-3 3"/><path d="M12 17h.01"/></svg>,
  Arrow:    (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  Grid:     (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
  Trend:    (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>,
  Shield:   (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3v8z"/></svg>,
  Cal:      (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
  Wallet:   (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 7H5a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/><path d="M16 14h.01"/><path d="M3 9a2 2 0 0 1 2-2h12V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v4z"/></svg>,
  Target:   (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>,
  Split:    (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M16 3h5v5"/><path d="M8 3H3v5"/><path d="m21 3-8.5 8.5L12 12l-.5.5L3 21"/><path d="m21 21-6.5-6.5"/><path d="m3 21 6.5-6.5"/></svg>,
  Rocket:   (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>,
  Risk:     (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 2v6M12 16v6M2 12h6M16 12h6"/><circle cx="12" cy="12" r="3"/></svg>,
  Op:       (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="3 17 9 11 13 15 21 7"/><polyline points="14 7 21 7 21 14"/></svg>,
  Ok:       (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3v8z"/><path d="m9 12 2 2 4-4"/></svg>,
  Wd:       (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 7H5a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/><circle cx="16" cy="13" r="1.2" fill="currentColor"/></svg>,
  Sparkle:  (p) => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3l1.9 5.6 5.6 1.9-5.6 1.9L12 18l-1.9-5.6L4.5 10.5l5.6-1.9z"/></svg>,
  Info:     (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>,
  Warn:     (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><path d="M12 9v4M12 17h.01"/></svg>,
  Check:    (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>,
};

const KPI_ICONS = {
  trend: Ico.Trend, shield: Ico.Shield, calendar: Ico.Cal, wallet: Ico.Wallet,
  target: Ico.Target, split: Ico.Split, rocket: Ico.Rocket,
};

const CAT_META = {
  all:        { label: "Todo",       icon: Ico.Grid },
  operativa:  { label: "Operativa",  icon: Ico.Op },
  riesgo:     { label: "Riesgo",     icon: Ico.Risk },
  aprobacion: { label: "Aprobación", icon: Ico.Ok },
  retiros:    { label: "Retiros",    icon: Ico.Wd },
};

const CAT_FAQ_ICON = {
  operativa:  Ico.Op,
  riesgo:     Ico.Risk,
  aprobacion: Ico.Ok,
  retiros:    Ico.Wd,
};

const SECTIONS = ["emergefx", "futuros", "pases"];

/* ---------------- KPI card ---------------- */
function KPI({ icon, title, value, desc }) {
  const Icon = KPI_ICONS[icon] || Ico.Trend;
  // Bold the first numeric/highlight token in desc for hierarchy
  const renderDesc = () => {
    // We accept inline <strong> by re-parsing simple markers: words ending in % or like "10 días"
    // For simplicity, return raw text; the design system handles colors at .ep-kpi__desc strong
    return desc;
  };
  return (
    <div className="ep-kpi">
      <div className="ep-kpi__head">
        <div className="ep-kpi__icon"><Icon /></div>
        <div className="ep-kpi__title">{title}</div>
      </div>
      <div className="ep-kpi__value">{value}</div>
      <div className="ep-kpi__desc">{renderDesc()}</div>
    </div>
  );
}

/* ---------------- FAQ item ---------------- */
function FAQItem({ faq, open, onToggle }) {
  const Icon = CAT_FAQ_ICON[faq.cat] || Ico.Op;
  const renderBody = () => {
    // Plugin renders rich HTML; static data uses plain string with \n\n separators.
    if (faq.aHtml) {
      return <div className="ep-faq__html" dangerouslySetInnerHTML={{ __html: faq.aHtml }} />;
    }
    return (faq.a || "").split(/\n\n+/).map((para, i) => <p key={i}>{para}</p>);
  };
  return (
    <article className="ep-faq" data-open={open}>
      <button className="ep-faq__head" onClick={onToggle} aria-expanded={open}>
        <span className="ep-faq__icon"><Icon /></span>
        <span className="ep-faq__cat" data-cat={faq.cat}>{CAT_META[faq.cat]?.label || faq.cat}</span>
        <span className="ep-faq__q">
          {faq.q}
          {faq.flag && <span className="ep-faq__flag">{faq.flag}</span>}
        </span>
        <span className="ep-faq__chev"><Ico.Plus /></span>
      </button>
      <div className="ep-faq__body">
        <div>
          <div className="ep-faq__inner">
            {renderBody()}
            {faq.highlight && (
              <div className="ep-callout" data-type={faq.highlight.type}>
                {faq.highlight.type === "info" && <Ico.Info />}
                {faq.highlight.type === "warn" && <Ico.Warn />}
                {faq.highlight.type === "success" && <Ico.Check />}
                <span>{faq.highlight.text}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </article>
  );
}

/* ---------------- Sidebar ---------------- */
function Sidebar({ cat, setCat, counts, ui }) {
  return (
    <aside className="ep-side">
      <div>
        <p className="ep-cats__title">{ui.cats_title || "Categorías"}</p>
        <div className="ep-cats__list">
          {Object.entries(CAT_META).map(([key, meta]) => {
            const Icon = meta.icon;
            const labels = (window.EPHC_DATA && window.EPHC_DATA.ui && window.EPHC_DATA.ui.cat_labels) || {};
            const label = labels[key] || meta.label;
            return (
              <button
                key={key}
                className="ep-cat"
                data-active={cat === key}
                onClick={() => setCat(key)}
              >
                <Icon />
                <span>{label}</span>
                <span className="ep-cat__count">{counts[key] ?? 0}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="ep-help-card">
        <div className="ep-help-card__icon"><Ico.Help /></div>
        <p className="ep-help-card__title">{ui.help_title || "¿Tienes dudas?"}</p>
        <p className="ep-help-card__text">{ui.help_text || ""}</p>
        <a className="ep-help-card__btn" href={ui.help_url || "#"}>
          {ui.help_button || "Abrir ticket"} <Ico.Arrow />
        </a>
      </div>
    </aside>
  );
}

/* ---------------- Highlighted rules ---------------- */
function HighlightedRules({ section, onSeeAll, ui }) {
  // Pull highlighted from EPHC_DATA so the user can edit it from the plugin admin.
  const sec = (window.EPHC_DATA && window.EPHC_DATA.sections) ? window.EPHC_DATA.sections[section] : null;
  const items = (sec && Array.isArray(sec.highlighted)) ? sec.highlighted : [];
  if (items.length === 0) return null;
  const iconMap = { trend: Ico.Trend, shield: Ico.Shield, sparkle: Ico.Sparkle, target: Ico.Target, split: Ico.Split, rocket: Ico.Rocket, calendar: Ico.Cal, wallet: Ico.Wallet };
  return (
    <section className="ep-highlighted">
      <div className="ep-highlighted__head">
        <h3 className="ep-highlighted__title"><Ico.Sparkle /> {ui.highlighted_title || "Reglas destacadas"}</h3>
        <button className="ep-link" onClick={onSeeAll}>{ui.highlighted_link || "Ver todas las reglas"} <Ico.Arrow /></button>
      </div>
      <div className="ep-highlighted__grid">
        {items.map((it, i) => {
          const I = iconMap[it.icon] || Ico.Trend;
          return (
            <div className="ep-feature" key={i}>
              <div className="ep-feature__icon"><I /></div>
              <div>
                <h4 className="ep-feature__title">{it.title}</h4>
                <p className="ep-feature__text">{it.text}</p>
                {it.pill && <span className="ep-feature__pill"><Ico.Check />{it.pill}</span>}
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

/* ---------------- App ---------------- */
function HelpCenter() {
  const [section, setSection] = useState("emergefx");
  const [cat, setCat] = useState("all");
  const [openId, setOpenId] = useState(null);
  const faqsRef = useRef(null);

  const data = (window.EPHC_DATA && window.EPHC_DATA.sections) ? window.EPHC_DATA.sections[section] : null;
  const UI   = (window.EPHC_DATA && window.EPHC_DATA.ui) ? window.EPHC_DATA.ui : {};
  if (!data) return null;
  const allFaqs = data.faqs || [];

  // Counts per category for current section
  const counts = useMemo(() => {
    const c = { all: allFaqs.length };
    for (const k of Object.keys(CAT_META)) if (k !== "all") c[k] = 0;
    for (const f of allFaqs) c[f.cat] = (c[f.cat] || 0) + 1;
    return c;
  }, [allFaqs]);

  // Reset cat & open state when switching tab
  useEffect(() => { setCat("all"); setOpenId(null); }, [section]);

  // Filtered list
  const filtered = useMemo(() => {
    if (cat === "all") return allFaqs;
    return allFaqs.filter(f => f.cat === cat);
  }, [allFaqs, cat]);

  const scrollToFAQs = () => {
    if (!faqsRef.current) return;
    const r = faqsRef.current.getBoundingClientRect();
    const y = window.pageYOffset + r.top - 24;
    window.scrollTo({ top: y, behavior: "smooth" });
  };

  return (
    <div className="ep-help">
      <div className="ep-help__wrap">

        {/* ----- Tabs (primer elemento — sin hero) ----- */}
        <div className="ep-tabs" role="tablist">
          <div className="ep-tabs__row">
            {SECTIONS.map(key => {
              const s = window.EPHC_DATA.sections[key];
              return (
                <button
                  key={key}
                  role="tab"
                  className="ep-tab"
                  data-active={section === key}
                  onClick={() => setSection(key)}
                >
                  {s.label}
                  <span className="ep-tab__sub">{s.sublabel}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* ----- KPIs ----- */}
        <div className="ep-kpis">
          {data.kpis.map((k, i) => <KPI key={section + "-" + i} {...k} />)}
        </div>

        {/* ----- Body: sidebar + FAQs ----- */}
        <div className="ep-body" ref={faqsRef}>
          <Sidebar
            cat={cat} setCat={setCat}
            counts={counts}
            ui={UI.sidebar || {}}
          />

          <div className="ep-faqs">
            {filtered.length === 0 ? (
              <div className="ep-empty">
                <Ico.Search />
                <div className="ep-empty__title">Sin resultados</div>
                <div className="ep-empty__sub">No hay reglas en esta categoría todavía.</div>
              </div>
            ) : filtered.map((f, i) => {
              const id = section + "-" + cat + "-" + i + "-" + f.q;
              return (
                <FAQItem
                  key={id}
                  faq={f}
                  open={openId === id}
                  onToggle={() => setOpenId(openId === id ? null : id)}
                />
              );
            })}
          </div>
        </div>

        {/* ----- Highlighted rules ----- */}
        <HighlightedRules section={section} onSeeAll={scrollToFAQs} ui={UI} />

      </div>
    </div>
  );
}

window.HelpCenter = HelpCenter;

/* Auto-mount: render into #ephc-root (plugin) or #ep-help-root (static preview). */
(function () {
  const mount = function () {
    const targets = [document.getElementById('ephc-root'), document.getElementById('ep-help-root')].filter(Boolean);
    targets.forEach(el => {
      if (el.dataset.ephcMounted) return;
      el.dataset.ephcMounted = '1';
      ReactDOM.createRoot(el).render(<HelpCenter />);
    });
  };
  if (document.readyState !== 'loading') { mount(); }
  else { document.addEventListener('DOMContentLoaded', mount); }
})();
