// ─────────────────────────────────────────────────────────────
// APP — Clínica Digital · Dr. Ulisses Nakagawa
// Home (carrossel) → Lista → Detalhe
// Mesmo template para Suplementos, Manipulados, Peptídeos
// ─────────────────────────────────────────────────────────────

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

// ───────── STICKY AGENDAR (interno, topo da tela) ─────────
// Aparece no topo da Lista e do Detalhe, sticky no scroll.
// NÃO aparece na home (a carrossel já é a ação principal).
function InlineAgendar({ t }) {
  return (
    <a href={waLink("Olá, gostaria de agendar uma consulta com o Dr. Ulisses Nakagawa.")} target="_blank" rel="noreferrer" className="cta-agendar" style={{
      position: "relative", overflow: "hidden",
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 2,
      background: t.ink1, color: t.bg0,
      borderRadius: 14,
      padding: "11px 18px",
      fontFamily: TYPE.sans,
      textDecoration: "none",
      boxShadow: "0 8px 24px rgba(0,0,0,0.5)",
      width: "100%",
      textAlign: "center",
    }}>
      <span style={{
        fontSize: 14, fontWeight: 800, letterSpacing: "0.10em",
        textTransform: "uppercase", lineHeight: 1.1,
      }}>Agendar Consulta</span>
      <span style={{
        fontSize: 9.5, fontWeight: 700, letterSpacing: "0.16em",
        textTransform: "uppercase", opacity: 0.72, lineHeight: 1.1,
      }}>Com o Dr. Ulisses Nakagawa</span>
      {/* flash de luz que passa na horizontal */}
      <span aria-hidden="true" className="cta-sheen"></span>
    </a>
  );
}

// ───────── BOTTOM NAV ─────────
function BottomNav({ active, onChange, t, isLight, onToggleTheme }) {
  const items = [
    { id: "home",     label: "Início",   icon: "home" },
    { id: "consulta", label: "Consulta", icon: "chat" },
    { id: "social",   label: "Social",   icon: "user" },
  ];
  return (
    <div style={{
      position: "absolute", bottom: 0, left: 0, right: 0,
      paddingTop: 12, paddingBottom: "max(20px, env(safe-area-inset-bottom))",
      background: t.bg0,
      borderTop: `1px solid ${t.border}`,
      display: "flex", justifyContent: "space-around",
      backdropFilter: "blur(20px)",
      zIndex: 50,
    }}>
      {items.map((it) => (
        <button key={it.id} onClick={() => onChange(it.id)} style={{
          background: "transparent", border: "none",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 5,
          color: active === it.id ? t.ink1 : t.ink3,
          cursor: "pointer", padding: "4px 8px",
          fontFamily: TYPE.sans,
        }}>
          <Icon name={it.icon} size={20} stroke="currentColor" />
          <span style={{
            fontSize: 9.5, letterSpacing: "0.12em", textTransform: "uppercase",
            fontWeight: 700,
          }}>{it.label}</span>
        </button>
      ))}

      {/* ───── BOTÃO MODO CLARO / ESCURO — sempre visível ───── */}
      <button
        onClick={onToggleTheme}
        aria-label={isLight ? "Mudar para modo escuro" : "Mudar para modo claro"}
        title={isLight ? "Modo escuro" : "Modo claro"}
        style={{
          background: "transparent", border: "none",
          display: "flex", flexDirection: "column", alignItems: "center", gap: 5,
          color: t.ink3, cursor: "pointer", padding: "4px 8px",
          fontFamily: TYPE.sans,
        }}
      >
        {isLight ? (
          // está no claro → ícone lua (toca para escuro)
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"></path>
          </svg>
        ) : (
          // está no escuro → ícone sol (toca para claro)
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="4"></circle>
            <path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4"></path>
          </svg>
        )}
        <span style={{
          fontSize: 9.5, letterSpacing: "0.12em", textTransform: "uppercase",
          fontWeight: 700,
        }}>{isLight ? "Escuro" : "Claro"}</span>
      </button>
    </div>
  );
}

// ───────── HOME SCREEN ─────────
function HomeScreen({ t, onOpenModule, onBuyModule, onRedeemCode, isUnlocked, frameWidth, frameHeight }) {
  return (
    <div style={{
      position: "absolute", inset: 0,
      background: t.bg0, color: t.ink1,
      paddingTop: 56, paddingBottom: 84, // status bar + bottom nav
      overflowY: "auto", overflowX: "hidden",
      WebkitOverflowScrolling: "touch",
    }}>
      {/* HEADER editorial */}
      <div style={{ padding: "20px 24px 16px" }}>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 800,
          marginBottom: 10,
        }}>Clínica Digital</div>
        <div style={{
          fontFamily: TYPE.display, fontSize: 38, lineHeight: 0.95,
          color: t.ink1, letterSpacing: "-0.01em",
          marginBottom: 12, textTransform: "uppercase",
          display: "inline-block",
        }}>
          <span style={{ display: "block", textAlign: "justify", textAlignLast: "justify" }}>
            Dr.&nbsp;Ulisses
          </span>
          <span style={{ display: "block", textAlign: "justify", textAlignLast: "justify" }}>
            Nakagawa
          </span>
        </div>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 11.5, color: t.ink2, fontWeight: 600,
          letterSpacing: "0.02em", marginBottom: 4,
        }}>Médico e Farmacêutico</div>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 10.5, color: t.ink3,
          letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 700,
          marginBottom: 4,
        }}>CRM-MS 16293</div>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 11.5, color: t.ink3, lineHeight: 1.5,
          marginBottom: 18,
        }}>Conteúdo educativo · Não substitui consulta médica</div>

        {/* Acesso para quem JÁ comprou — discreto, fora do caminho da venda */}
        <button onClick={onRedeemCode} style={{
          marginTop: 16,
          display: "inline-flex", alignItems: "center", gap: 8,
          background: "transparent", border: `1px solid ${t.border}`,
          borderRadius: 999, padding: "9px 15px", cursor: "pointer",
          fontFamily: TYPE.sans, fontSize: 10.5, color: t.ink2,
          letterSpacing: "0.10em", textTransform: "uppercase", fontWeight: 700,
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <rect x="4" y="11" width="16" height="9" rx="2"></rect>
            <path d="M8 11V8a4 4 0 0 1 8 0v3"></path>
          </svg>
          Já tenho código · Acessar
        </button>
      </div>

      {/* CARROSSEL */}
      <div style={{ marginTop: 8, marginBottom: 22 }}>
        <PosterCarousel
          modules={MODULES}
          t={t}
          onOpenModule={onOpenModule}
          onBuyModule={onBuyModule}
          isUnlocked={isUnlocked}
          frameWidth={frameWidth}
          frameHeight={frameHeight - 90}
        />
      </div>

    </div>
  );
}

// ───────── LIST SCREEN ─────────
function ListScreen({ t, type, onBack, onOpenProduct, density, showVisual }) {
  const meta = PRODUCT_TYPES[type];
  const products = useMemo(() => PRODUCTS.filter(p => p.type === type), [type]);

  const [query, setQuery] = useState("");
  const [activeCat, setActiveCat] = useState("Todos");

  // Filtros por sessão:
  //  · Suplementos: Todos · ★ Eu uso · (sem categorias, suplemento age em vários sistemas)
  //  · Manipulados: Todos · categorias funcionais
  //  · Peptídeos:   Todos · Aprovados · categorias funcionais
  const showCats = type !== "suplemento";
  const cats = useMemo(() => {
    const out = ["Todos"];
    if (type === "suplemento" && products.some(p => p.eu_uso)) out.push("★ Eu uso");
    if (type === "suplemento") out.push("Referências");
    if (type === "peptideo"   && products.some(p => p.aprovado))   out.push("Aprovados");
    if (showCats) {
      const seen = new Set();
      products.forEach(p => {
        if (!seen.has(p.category)) { seen.add(p.category); out.push(p.category); }
      });
    }
    return out;
  }, [products, type, showCats]);

  const filtered = useMemo(() => {
    return products.filter(p => {
      const q = query.toLowerCase().trim();
      const matchQ = !q || p.name.toLowerCase().includes(q) || p.tagline.toLowerCase().includes(q);
      let matchC = true;
      if (activeCat === "Todos") matchC = true;
      else if (activeCat === "★ Eu uso") matchC = !!p.eu_uso;
      else if (activeCat === "Aprovados") matchC = !!p.aprovado;
      else matchC = p.category === activeCat;
      return matchQ && matchC;
    });
  }, [products, query, activeCat]);

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: t.bg0, color: t.ink1,
      paddingTop: 56, paddingBottom: 100,
      overflowY: "auto", overflowX: "hidden",
      WebkitOverflowScrolling: "touch",
    }}>
      {/* TOPO STICKY — Back + Agendar Consulta */}
      <div style={{
        position: "sticky", top: 0, zIndex: 20,
        background: t.bg0,
        backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
        padding: "10px 14px 12px",
        borderBottom: `1px solid ${t.border}`,
        display: "flex", alignItems: "center", gap: 10,
        boxShadow: `0 6px 16px ${t.bg0}`,
      }}>
        <button onClick={onBack} style={{
          flexShrink: 0,
          width: 38, height: 38, borderRadius: 999,
          background: t.bg1, border: `1px solid ${t.border}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.ink2, cursor: "pointer",
        }}>
          <Icon name="back" size={16} stroke="currentColor" />
        </button>
        <div style={{ flex: 1 }}>
          <InlineAgendar t={t} />
        </div>
      </div>

      {/* HEADER (não sticky) */}
      <div style={{ padding: "20px 20px 14px" }}>
        <div style={{
          fontFamily: TYPE.display, fontSize: 46, lineHeight: 0.95, color: t.ink1,
          letterSpacing: "-0.01em", marginBottom: 12, textTransform: "uppercase",
        }}>{meta.label}</div>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 13, color: t.ink2, lineHeight: 1.55,
          maxWidth: "94%",
        }}>{meta.description}</div>
      </div>

      {/* SEARCH + CATEGORIAS */}
      <div style={{ padding: "0 20px 8px" }}>
        <div style={{ position: "relative", marginBottom: 14 }}>
          <div style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }}>
            <Icon name="search" size={15} stroke={t.ink3} />
          </div>
          <input
            type="text" value={query} onChange={(e) => setQuery(e.target.value)}
            placeholder={`Buscar em ${meta.label.toLowerCase()}…`}
            style={{
              width: "100%", padding: "12px 14px 12px 38px",
              background: t.bg1, border: `1px solid ${t.border}`,
              borderRadius: 12,
              color: t.ink1, fontFamily: TYPE.sans, fontSize: 14,
              outline: "none",
            }}
          />
        </div>

        <MomentumChipRow t={t} items={cats} active={activeCat} onPick={setActiveCat} />
      </div>

      {/* COUNT — escondido na aba de Referências */}
      {activeCat !== "Referências" && (
        <div style={{
          padding: "16px 24px 10px",
          fontFamily: TYPE.sans, fontSize: 11, color: t.ink3,
          letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 600,
          display: "flex", justifyContent: "space-between",
        }}>
          <span>{filtered.length} {filtered.length === 1 ? "registro" : "registros"}</span>
          <span style={{ color: t.ink4 }}>de {products.length}</span>
        </div>
      )}

      {/* CONTEÚDO — lista de produtos OU vista de referências */}
      {activeCat === "Referências" ? (
        <ReferencesView t={t} query={query} />
      ) : (
        <div style={{ padding: "0 16px", display: "flex", flexDirection: "column", gap: 10 }}>
          {filtered.map((p) => (
            <ProductCard
              key={p.id} product={p} t={t}
              density={density}
              showVisual={showVisual}
              onOpen={() => onOpenProduct(p)}
            />
          ))}
          {filtered.length === 0 && (
            <div style={{
              padding: "60px 20px", textAlign: "center",
              fontFamily: TYPE.sans, fontSize: 13, color: t.ink3,
            }}>Nenhum resultado para "{query}"</div>
          )}
        </div>
      )}

      {/* FERRAMENTAS — só em Peptídeos */}
      {type === "peptideo" && (
        <div style={{ marginTop: 36 }}>
          <div style={{ padding: "0 24px 4px" }}>
            <SectionLabel t={t}>Ferramentas</SectionLabel>
          </div>
          <div style={{ padding: "0 16px" }}>
            <PeptideoFerramentas t={t} />
          </div>
        </div>
      )}

      {/* DISCLAIMER LEGAL */}
      <div style={{ marginTop: 36 }}>
        <LegalDisclaimer t={t} />
      </div>
    </div>
  );
}

// ───────── DETAIL SCREEN ─────────
function DetailScreen({ t, product, onBack }) {
  const meta = PRODUCT_TYPES[product.type];

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: t.bg0, color: t.ink1,
      paddingTop: 56, paddingBottom: 110,
      overflowY: "auto", overflowX: "hidden",
      WebkitOverflowScrolling: "touch",
    }}>
      {/* TOPO STICKY — Back + Agendar Consulta */}
      <div style={{
        position: "sticky", top: 0, zIndex: 20,
        background: t.bg0,
        backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
        padding: "10px 14px 12px",
        borderBottom: `1px solid ${t.border}`,
        display: "flex", alignItems: "center", gap: 10,
        boxShadow: `0 6px 16px ${t.bg0}`,
      }}>
        <button onClick={onBack} style={{
          flexShrink: 0,
          width: 38, height: 38, borderRadius: 999,
          background: t.bg1, border: `1px solid ${t.border}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.ink2, cursor: "pointer",
        }}>
          <Icon name="back" size={16} stroke="currentColor" />
        </button>
        <div style={{ flex: 1 }}>
          <InlineAgendar t={t} />
        </div>
      </div>

      {/* HERO */}
      <div style={{ padding: "20px 24px 28px" }}>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 10.5, color: t.ink3,
          letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 700,
          marginBottom: 14,
        }}>
          {meta.breadcrumb} · {product.category}
        </div>

        <h1 style={{
          fontFamily: TYPE.display, fontSize: 38, lineHeight: 0.95,
          letterSpacing: "-0.01em", color: t.ink1, fontWeight: 400,
          margin: "0 0 14px", textTransform: "uppercase",
        }}>{nl2br(product.name)}</h1>

        <p style={{
          fontFamily: TYPE.sans, fontSize: 15.5, lineHeight: 1.55,
          color: t.ink2, margin: "0 0 18px",
        }}>{product.tagline}</p>

        {/* Apenas o badge "Eu uso" no hero para suplementos (sem pills de classificação aqui — só no rodapé) */}
        {product.eu_uso && product.type === "suplemento" && (
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 4,
              fontSize: 10.5, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase",
              padding: "5px 12px", borderRadius: 999,
              background: t.accent, color: t.accentInk,
              fontFamily: TYPE.sans,
              whiteSpace: "nowrap",
            }}>★ Eu uso</span>
          </div>
        )}

        {/* STATS GRID removido para Manipulados — informação já vive em "Como usar" */}
        {false && product.stats && product.type === "manipulado" && (
          <div style={{
            marginTop: 22,
            display: "grid", gridTemplateColumns: `repeat(${product.stats.length}, 1fr)`,
            background: t.bg1, border: `1px solid ${t.border}`,
            borderRadius: 14, overflow: "hidden",
          }}>
            {product.stats.map((s, i) => (
              <div key={i} style={{
                padding: "14px 14px",
                borderRight: i < product.stats.length - 1 ? `1px solid ${t.border}` : "none",
              }}>
                <div style={{
                  fontFamily: TYPE.sans, fontSize: 9.5,
                  letterSpacing: "0.12em", textTransform: "uppercase",
                  color: t.ink3, fontWeight: 600, marginBottom: 6,
                }}>{s.k}</div>
                <div style={{
                  fontFamily: TYPE.display, fontSize: 18, color: t.ink1,
                  lineHeight: 1.1, letterSpacing: "-0.005em", textTransform: "uppercase",
                }}>{s.v}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* SEPARADOR EDITORIAL */}
      <div style={{
        height: 1, background: t.border, margin: "0 24px 32px",
      }}></div>

      {/* SEÇÕES */}
      <div style={{ padding: "0 24px" }}>
        {product.sections.map((s, i) => (
          <Section key={i} section={s} num={i + 1} t={t} product={product} />
        ))}
      </div>

      {/* CTA FINAL — Agendar Consulta */}
      <div style={{ padding: "8px 24px 24px" }}>
        <a href={waLink(`Olá, gostaria de agendar uma consulta com o Dr. Ulisses.`)} target="_blank" rel="noreferrer" className="cta-agendar" style={{
          position: "relative", overflow: "hidden",
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 4,
          padding: "18px 20px",
          background: t.ink1, color: t.bg0,
          borderRadius: 14, textDecoration: "none",
          fontFamily: TYPE.sans,
          textAlign: "center",
          boxShadow: "0 10px 28px rgba(0,0,0,0.4)",
        }}>
          <span style={{
            fontSize: 15, fontWeight: 800, letterSpacing: "0.10em",
            textTransform: "uppercase", lineHeight: 1.1,
          }}>Agendar Consulta</span>
          <span style={{
            fontSize: 10.5, fontWeight: 700, letterSpacing: "0.16em",
            textTransform: "uppercase", opacity: 0.72, lineHeight: 1.1,
          }}>Com o Dr. Ulisses Nakagawa</span>
          <span aria-hidden="true" className="cta-sheen"></span>
        </a>
      </div>
    </div>
  );
}

// ───────── APP ROOT ─────────
function App() {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "theme": "editorial",
    "density": "spacious",
    "showVisual": true,
    "viewAs": "real"
  }/*EDITMODE-END*/;

  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const t = THEMES[tweaks.theme] || THEMES.editorial;

  // navegação
  const [screen, setScreen] = useState("home"); // home | list | detail | consulta | habitos | social | analise
  const [listType, setListType] = useState(null);
  const [product, setProduct] = useState(null);
  const [deepToken, setDeepToken] = useState(null); // token vindo de link (?token=...)
  const [acessoLivre, setAcessoLivre] = useState(false); // entrou pelo link público (sem palavra)

  // ROTAS por URL (funciona com .htaccess de redirect ou rewrite):
  //  • ?token=XXX  ou  /comportamentos/analise/XXX  → abre a Análise já com o token
  //  • ?area=criador  ou  /admin                     → abre a Área do Criador (pede senha)
  useEffect(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      const path = window.location.pathname || "";

      // token: query (?token= / ?analise=) ou caminho /comportamentos/analise/<token>
      let tk = (p.get("token") || p.get("analise") || "").trim();
      let linkPublico = false;
      if (!tk) {
        const m = path.match(/\/comportamentos\/analise\/([^\/?#]+)/i);
        if (m) tk = decodeURIComponent(m[1]).trim();
        // caminho público SEM token (/comportamentos/analise) → acesso livre por LINK
        else if (/\/comportamentos\/analise\/?$/i.test(path) || p.get("acesso") === "publico") {
          linkPublico = true;
        }
      }

      // área do criador: ?area=criador / ?admin  ou caminho /admin
      const isAdmin = p.get("area") === "criador" || p.has("admin") || /\/admin\/?$/i.test(path);

      // Subpastas dos módulos (vitrine): /suplementos /manipulados /peptideos /caneta /combo
      // /comportamentos /gestao  — também aceita ?p=<id>. Abre direto na seção certa.
      let modId = (p.get("p") || "").trim().toLowerCase();
      if (!modId) {
        const mm = path.match(/^\/(suplementos|manipulados|peptideos|caneta|combo|comportamentos|gestao)\/?$/i);
        if (mm) modId = mm[1].toLowerCase();
      }
      if (modId === "comportamentos") modId = "habitos"; // alias bonito → módulo

      if (isAdmin) { setScreen("admin"); }
      else if (linkPublico) { setAcessoLivre(true); setScreen("analise"); }
      else if (tk) { setDeepToken(tk); setScreen("analise"); }
      else if (modId) {
        const m = MODULES.find((x) => x.id === modId);
        if (m) {
          if (m.type === "gestao") { window.location.replace(encodeURI("gestao-tempo/Gestão de Tempo.html")); return; }
          else if (m.type === "habitos") { setScreen("habitos"); }
          else { setListType(m.type); setScreen("list"); }
        }
      }
    } catch (e) {}
  }, []);

  // ─── ACESSO (desbloqueio por código, sem login, sem servidor) ───
  const [unlocked, setUnlocked] = useState(() => getUnlocked());
  const [accessModule, setAccessModule] = useState(null); // módulo aberto no modal de código
  const viewAs = tweaks.viewAs || "real";
  const isCreator = viewAs === "creator" || unlocked.has("creator");
  const moduleUnlocked = (m) => {
    if (m.free || m.id === "habitos") return true;   // produto grátis: aberto pra todos
    if (viewAs === "creator") return true;   // criador vê tudo
    if (viewAs === "visitor") return false;  // simula quem não comprou
    if (m.isCombo) return unlocked.has("all");
    return unlocked.has("all") || unlocked.has(m.id);
  };
  const handleRedeemed = (scope) => {
    setUnlocked(getUnlocked());
    setAccessModule(null);
    if (scope && scope !== "all") {
      const m = MODULES.find(x => x.id === scope);
      if (m) { setListType(m.type); setScreen("list"); }
    }
  };

  // tab ativa no bottom nav (derivado do screen)
  const activeTab = (screen === "consulta" || screen === "atendimento")
    ? "consulta"
    : (screen === "social")
    ? "social"
    : "home";

  // dimensões reais da janela (app preenche a tela — SEM moldura de iPhone)
  const [vw, setVw] = useState(typeof window !== "undefined" ? window.innerWidth : 390);
  const [vh, setVh] = useState(typeof window !== "undefined" ? window.innerHeight : 844);
  useEffect(() => {
    const on = () => { setVw(window.innerWidth); setVh(window.innerHeight); };
    window.addEventListener("resize", on);
    window.addEventListener("orientationchange", on);
    return () => {
      window.removeEventListener("resize", on);
      window.removeEventListener("orientationchange", on);
    };
  }, []);
  const FW = Math.min(vw, 480);   // coluna do app (centralizada no desktop)
  const FH = vh;

  const openModule = (m) => {
    if (m.id === "habitos") { setScreen("habitos"); return; }   // produto grátis → abre o tracker
    if (m.id === "gestao") { window.location.href = encodeURI("gestao-tempo/Gestão de Tempo.html"); return; } // app de gestão de tempo
    if (moduleUnlocked(m)) {
      if (m.isCombo) return;               // combo já é acesso total
      setListType(m.type); setScreen("list"); return;
    }
    buyModule(m);                          // bloqueado / combo / em breve → direto pra venda
  };

  // Botão "Comprar" do pôster — vai direto pro Hotmart (ou WhatsApp como fallback)
  const buyModule = (m) => {
    // Funciona mesmo para módulos "soon" — usa o link da Hotmart se houver,
    // ou cai no WhatsApp como fallback (mensagem adequada para cada caso).
    if (m.status === "soon") {
      const url = (typeof HOTMART_LINKS !== "undefined" && HOTMART_LINKS[m.id]?.link) || "";
      window.open(
        url || waLink(`Olá, quero ser avisado quando ${m.name} estiver disponível.`),
        "_blank"
      );
      return;
    }
    const url = buyLink(m.id, m.name);
    window.open(url, "_blank");
  };

  // debug nav (apenas para teste rápido)
  useEffect(() => {
    window.__nav = (type) => { setListType(type); setScreen("list"); };
    window.__detail = (id) => { const p = PRODUCTS.find(x => x.id === id); if (p) { setProduct(p); setScreen("detail"); } };
  }, []);
  const openProduct = (p) => {
    setProduct(p);
    setScreen("detail");
  };

  return (
    <>
      {/* Tweaks panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Estética">
          <TweakRadio
            label="Modo visual"
            value={tweaks.theme}
            options={[
              { value: "editorial", label: "Editorial" },
              { value: "clinical",  label: "Clínica" },
              { value: "luxe",      label: "Luxe" },
            ]}
            onChange={(v) => setTweak("theme", v)}
          />
        </TweakSection>

        <TweakSection label="Acesso (pré-visualização)">
          <TweakRadio
            label="Ver como"
            value={tweaks.viewAs || "real"}
            options={[
              { value: "real",    label: "Real" },
              { value: "creator", label: "Criador" },
              { value: "visitor", label: "Visitante" },
            ]}
            onChange={(v) => setTweak("viewAs", v)}
          />
          <TweakButton
            label="Zerar desbloqueios (teste)"
            secondary
            onClick={() => { resetAccess(); setUnlocked(new Set()); }}
          />
        </TweakSection>

        <TweakSection label="Cards">
          <TweakRadio
            label="Densidade"
            value={tweaks.density}
            options={[
              { value: "compact",  label: "Compacto" },
              { value: "spacious", label: "Espaçoso" },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
          <TweakToggle
            label="Visual do produto"
            value={tweaks.showVisual}
            onChange={(v) => setTweak("showVisual", v)}
          />
        </TweakSection>
      </TweaksPanel>

      {/* STAGE — app preenche a tela inteira, sem moldura de protótipo */}
      <div style={{
        position: "fixed", inset: 0,
        background: t.bg0,
        display: "flex", justifyContent: "center",
      }}>
        <div style={{
          position: "relative",
          width: "100%", maxWidth: FW, height: "100%",
          overflow: "hidden", background: t.bg0,
        }}>
        <div style={{
          position: "absolute", inset: 0,
          background: t.bg0,
          fontFamily: TYPE.sans,
          color: t.ink1,
        }}>
          {screen === "home" && (
            <HomeScreen
              t={t}
              frameWidth={FW} frameHeight={FH}
              onOpenModule={openModule}
              onBuyModule={buyModule}
              isUnlocked={moduleUnlocked}
              onRedeemCode={() => setAccessModule({ generic: true })}
            />
          )}
          {screen === "list" && listType && (
            <ListScreen
              t={t} type={listType}
              density={tweaks.density}
              showVisual={tweaks.showVisual}
              onBack={() => setScreen("home")}
              onOpenProduct={openProduct}
            />
          )}
          {screen === "detail" && product && (
            <DetailScreen
              t={t} product={product}
              onBack={() => setScreen("list")}
            />
          )}
          {screen === "consulta" && <ConsultaScreen t={t} onSaibaMais={() => setScreen("atendimento")} />}
          {screen === "atendimento" && <AtendimentoScreen t={t} onBack={() => setScreen("consulta")} />}
          {screen === "habitos"  && <HabitosScreen  t={t} onBack={() => { setScreen("home"); setListType(null); setProduct(null); }} onIniciarAnalise={() => setScreen("analise")} />}
          {screen === "analise"  && <AnaliseScreen  t={t} initialToken={deepToken} acessoLivre={acessoLivre} onBack={() => { setDeepToken(null); setAcessoLivre(false); setScreen("habitos"); }} />}
          {screen === "social"   && <SocialScreen   t={t} />}
          {screen === "admin"    && <AdminScreen    t={t} onBack={() => setScreen("home")} />}

          {/* BOTTOM NAV — sempre visível (oculto na Análise e no Admin, fluxos focados) */}
          {screen !== "analise" && screen !== "admin" && (
          <BottomNav
            active={activeTab}
            isLight={tweaks.theme === "clinical"}
            onToggleTheme={() => setTweak("theme", tweaks.theme === "clinical" ? "editorial" : "clinical")}
            onChange={(id) => {
              if (id === "home") {
                setScreen("home"); setListType(null); setProduct(null);
              } else {
                setScreen(id);
              }
            }}
            t={t}
          />
          )}

          {/* MODAL DE ACESSO — resgate de código / comprar */}
          {accessModule && (
            <AccessModal
              module={accessModule}
              t={t}
              onClose={() => setAccessModule(null)}
              onRedeemed={handleRedeemed}
            />
          )}
        </div>
        </div>
      </div>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
