// ─────────────────────────────────────────────────────────────
// COMPONENTS — Sistema único de apresentação de produto
// Os MESMOS componentes renderizam Suplemento, Manipulado e Peptídeo.
// O conteúdo é dirigido por dados (sections[]).
// ─────────────────────────────────────────────────────────────

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

// ────────────────────────────────────────
// QUEBRA DE LINHA MANUAL nos nomes/textos
// Escreva <br> (ou quebre a linha de verdade no arquivo) DENTRO do texto
// pra forçar uma quebra exatamente onde você quer. Ex.:
//   name: "Citrulina<br>e Arginina"
// Não usa "/" como separador (vários nomes já usam barra).
// ────────────────────────────────────────
function nl2br(text) {
  if (text == null) return text;
  const parts = String(text).split(/<br\s*\/?>|\n/i);
  if (parts.length === 1) return text;
  const out = [];
  parts.forEach((part, i) => {
    if (i > 0) out.push(React.createElement("br", { key: "br" + i }));
    out.push(part);
  });
  return out;
}
window.nl2br = nl2br;

// ────────────────────────────────────────
// ICONS (de linha, finos — premium)
// ────────────────────────────────────────
const Icon = ({ name, size = 16, stroke = "currentColor", strokeWidth = 1.5 }) => {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke, strokeWidth, strokeLinecap: "round", strokeLinejoin: "round" };
  const PATHS = {
    search:    <><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></>,
    back:      <><path d="M15 6l-6 6 6 6"></path></>,
    close:     <><path d="M6 6l12 12M18 6l-12 12"></path></>,
    share:     <><path d="M12 3v12"></path><path d="m7 8 5-5 5 5"></path><path d="M5 14v5a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-5"></path></>,
    bookmark:  <><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path></>,
    chevR:     <><path d="m9 6 6 6-6 6"></path></>,
    home:      <><path d="m3 11 9-7 9 7v9a2 2 0 0 1-2 2h-3v-7h-8v7H5a2 2 0 0 1-2-2z"></path></>,
    flask:     <><path d="M9 3h6"></path><path d="M10 3v6L4 19a2 2 0 0 0 1.7 3h12.6A2 2 0 0 0 20 19l-6-10V3"></path><path d="M7 14h10"></path></>,
    pill:      <><path d="M14.5 3.5a4.95 4.95 0 0 1 7 7l-10 10a4.95 4.95 0 0 1-7-7z"></path><path d="m9 8 7 7"></path></>,
    drop:      <><path d="M12 3s-6 7-6 12a6 6 0 0 0 12 0c0-5-6-12-6-12z"></path></>,
    user:      <><circle cx="12" cy="8" r="4"></circle><path d="M4 21a8 8 0 0 1 16 0"></path></>,
    clock:     <><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path></>,
    check:     <><path d="m5 12 5 5 9-11"></path></>,
    alert:     <><path d="M12 9v4"></path><path d="M12 17h.01"></path><path d="M10.3 3.6 2.5 18a2 2 0 0 0 1.8 3h15.4a2 2 0 0 0 1.8-3L13.7 3.6a2 2 0 0 0-3.4 0z"></path></>,
    quote:     <><path d="M7 7v6a4 4 0 0 1-4 4"></path><path d="M17 7v6a4 4 0 0 1-4 4"></path></>,
    star:      <><path d="m12 2 3 7 7 .5-5.5 4.5L18 21l-6-4-6 4 1.5-7L2 9.5 9 9z"></path></>,
    filter:    <><path d="M4 5h16"></path><path d="M7 12h10"></path><path d="M10 19h4"></path></>,
    sparkle:   <><path d="M12 3v4"></path><path d="M12 17v4"></path><path d="M3 12h4"></path><path d="M17 12h4"></path><path d="m5.5 5.5 2.8 2.8"></path><path d="m15.7 15.7 2.8 2.8"></path><path d="m5.5 18.5 2.8-2.8"></path><path d="m15.7 8.3 2.8-2.8"></path></>,
    grid:      <><rect x="3" y="3" width="7" height="7" rx="1"></rect><rect x="14" y="3" width="7" height="7" rx="1"></rect><rect x="3" y="14" width="7" height="7" rx="1"></rect><rect x="14" y="14" width="7" height="7" rx="1"></rect></>,
    chat:      <><path d="M21 12c0 4.4-4 8-9 8-1 0-2-.1-2.9-.4L4 21l1.4-4.1A8 8 0 0 1 3 12c0-4.4 4-8 9-8s9 3.6 9 8z"></path></>,
  };
  return <svg {...p}>{PATHS[name]}</svg>;
};

// ────────────────────────────────────────
// PRIMITIVES
// ────────────────────────────────────────

const Pill = ({ children, tone = "neutral", t }) => {
  const map = {
    positive: { bg: "rgba(120,200,140,0.10)", fg: t.success, bd: "rgba(120,200,140,0.35)" },
    neutral:  { bg: "transparent",            fg: t.ink2,    bd: t.border },
    negative: { bg: "rgba(220,90,90,0.10)",   fg: t.danger,  bd: "rgba(220,90,90,0.40)" },
    premium:  { bg: t.accentMuted,            fg: t.ink1,    bd: t.borderStrong },
    caution:  { bg: "rgba(220,180,90,0.10)",  fg: t.warn,    bd: "rgba(220,180,90,0.40)" },
  }[tone];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      fontSize: 10.5, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase",
      padding: "4px 10px", borderRadius: RADIUS.pill,
      background: map.bg, color: map.fg, border: `1px solid ${map.bd}`,
      fontFamily: TYPE.sans,
      whiteSpace: "nowrap",
    }}>{children}</span>
  );
};

const SectionLabel = ({ children, t, num }) => (
  <div style={{
    display: "flex", alignItems: "center", gap: 12,
    fontFamily: TYPE.sans,
    fontSize: 10.5, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase",
    color: t.ink1, marginBottom: 14,
  }}>
    {num != null && <span style={{ color: t.ink4, fontVariantNumeric: "tabular-nums", fontWeight: 700, flexShrink: 0 }}>{String(num).padStart(2,"0")}</span>}
    <span style={{ whiteSpace: "nowrap", flexShrink: 0 }}>{children}</span>
    <span style={{ flex: 1, height: 1, background: t.border, minWidth: 12 }}></span>
  </div>
);

// product visual — placeholder padronizado (substituível por foto real)
const ProductVisual = ({ product, size = 64, t }) => {
  return (
    <div style={{
      width: size, height: size, flexShrink: 0,
      borderRadius: RADIUS.md,
      background: `linear-gradient(140deg, ${t.bg2}, ${t.bg1})`,
      border: `1px solid ${t.border}`,
      display: "flex", alignItems: "center", justifyContent: "center",
      overflow: "hidden", position: "relative",
    }}>
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: `repeating-linear-gradient(135deg, transparent 0 6px, ${t.border} 6px 7px)`,
        opacity: 0.5,
      }}></div>
      <span style={{
        position: "relative",
        fontFamily: TYPE.display,
        fontSize: size * 0.34,
        color: t.ink2,
        letterSpacing: "-0.01em",
        textTransform: "uppercase",
      }}>{product.visualCode || product.name.slice(0,2)}</span>
    </div>
  );
};

// ────────────────────────────────────────
// PRODUCT CARD (lista) — minimalista
// Só nome + tagline. Sem siglas, sem subtítulo, sem tags.
// As classificações aparecem só DENTRO do detalhe (gaveta).
// ────────────────────────────────────────
const ProductCard = ({ product, t, onOpen, showVisual = false, density = "spacious" }) => {
  const isCompact = density === "compact";
  const padding = isCompact ? "16px 18px" : "20px 22px";
  return (
    <button onClick={onOpen} style={{
      width: "100%", textAlign: "left", padding,
      display: "flex", alignItems: "center", gap: 14,
      background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.lg,
      cursor: "pointer", fontFamily: TYPE.sans, color: t.ink1,
      transition: "transform 0.15s ease, border-color 0.2s ease",
      WebkitTapHighlightColor: "transparent",
    }}
    onMouseDown={(e) => e.currentTarget.style.transform = "scale(0.99)"}
    onMouseUp={(e) => e.currentTarget.style.transform = "scale(1)"}
    onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
    >
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: TYPE.display, fontSize: isCompact ? 19 : 22, lineHeight: 1.05,
          letterSpacing: "-0.005em", color: t.ink1, textTransform: "uppercase",
          marginBottom: 6,
          overflow: "hidden",
          display: "-webkit-box",
          WebkitLineClamp: 2,
          WebkitBoxOrient: "vertical",
        }}>{nl2br(product.name)}</div>
        <div style={{
          fontSize: isCompact ? 12 : 13, color: t.ink2, lineHeight: 1.4,
          overflow: "hidden", textOverflow: "ellipsis",
          display: "-webkit-box", WebkitLineClamp: 1, WebkitBoxOrient: "vertical",
        }}>{product.tagline}</div>
      </div>
      <Icon name="chevR" size={14} stroke={t.ink4} />
    </button>
  );
};

// ────────────────────────────────────────
// SECTION BLOCKS — uma função por "kind"
// ────────────────────────────────────────

const SBList = ({ items, t, tone }) => {
  const isCaution = tone === "caution";
  const isNeutral = tone === "neutral";
  // Os check/marcadores ficam BRANCOS (ink2) por padrão.
  // Tons amarelo/vermelho são reservados para verdict.
  // Triângulos e marcadores acompanham a cor do texto (branco em modo escuro, preto em claro)
  const markColor = isCaution ? t.ink1 : (isNeutral ? t.ink3 : t.ink2);
  return (
    <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
      {items.map((it, i) => (
        <li key={i} style={{
          display: "flex", gap: 12, padding: "12px 0",
          borderBottom: i < items.length - 1 ? `1px solid ${t.border}` : "none",
          fontFamily: TYPE.sans, fontSize: 14, lineHeight: 1.55, color: t.ink2,
        }}>
          <span style={{
            flexShrink: 0, marginTop: 2, width: 16, height: 16,
            display: "flex", alignItems: "center", justifyContent: "center",
            color: markColor,
          }}>
            {isCaution ? (
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 9v4M12 17h.01M10.3 3.6 2.5 18a2 2 0 0 0 1.8 3h15.4a2 2 0 0 0 1.8-3L13.7 3.6a2 2 0 0 0-3.4 0z"/></svg>
            ) : isNeutral ? (
              <span style={{ fontSize: 14, fontWeight: 300 }}>·</span>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5 9-11"/></svg>
            )}
          </span>
          <span style={{ flex: 1 }}>{it}</span>
        </li>
      ))}
    </ul>
  );
};

const SBProtocol = ({ grid, t }) => {
  const entries = Object.entries(grid);
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
      {entries.map(([k, v], i) => (
        <div key={i} style={{
          background: t.bg0, border: `1px solid ${t.border}`,
          borderRadius: RADIUS.md, padding: "14px 16px",
        }}>
          <div style={{
            fontFamily: TYPE.sans, fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase",
            color: t.ink3, marginBottom: 8, fontWeight: 600,
          }}>{k}</div>
          <div style={{ fontFamily: TYPE.sans, fontSize: 14, color: t.ink1, lineHeight: 1.4, fontWeight: 500 }}>{v}</div>
        </div>
      ))}
    </div>
  );
};

const SBParagraph = ({ body, t }) => (
  <p style={{
    fontFamily: TYPE.sans, fontSize: 14.5, lineHeight: 1.7, color: t.ink2,
    margin: 0, textAlign: "justify",
  }}>{body}</p>
);

const SBQuote = ({ body, t }) => (
  <div style={{ position: "relative", paddingLeft: 20 }}>
    <div style={{
      position: "absolute", left: 0, top: 4, bottom: 4, width: 2,
      background: t.borderStrong,
    }}></div>
    <Icon name="quote" size={20} stroke={t.ink2} />
    <div style={{
      fontFamily: TYPE.sans, fontSize: 16, lineHeight: 1.55,
      color: t.ink1, fontStyle: "italic", margin: "12px 0 14px",
      letterSpacing: "-0.005em", fontWeight: 400,
      textAlign: "justify", textJustify: "inter-word",
    }}>"{body}"</div>
    <div style={{
      fontFamily: TYPE.sans, fontSize: 11.5, color: t.ink3,
      letterSpacing: "0.08em", textTransform: "uppercase", fontWeight: 600,
    }}>Dr. Ulisses Nakagawa · CRM-MS 16293</div>
  </div>
);

const SBAtivos = ({ items, t }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 1, background: t.border, borderRadius: RADIUS.md, overflow: "hidden", border: `1px solid ${t.border}` }}>
    {items.map((it, i) => (
      <div key={i} style={{
        display: "flex", alignItems: "baseline", justifyContent: "space-between",
        padding: "14px 16px", background: t.bg1,
        fontFamily: TYPE.sans,
      }}>
        <span style={{ fontSize: 14, color: t.ink1, fontWeight: 500, paddingRight: 12 }}>{it.name}</span>
        <span style={{ fontSize: 12, color: t.ink3, fontFamily: TYPE.mono, fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap", flexShrink: 0 }}>{it.dose}</span>
      </div>
    ))}
  </div>
);

const SBPhase = ({ phase, notes, t }) => {
  // Labels conforme padrão de estudos clínicos
  const phases = ["Animal", "Fase I", "Pilotos humanos", "Fase III", "Aprovado"];
  return (
    <div>
      <div style={{ display: "flex", gap: 4, marginBottom: 10 }}>
        {phases.map((p, i) => (
          <div key={i} style={{ flex: 1 }}>
            <div style={{
              height: 4, borderRadius: 2,
              background: i + 1 <= phase ? t.ink1 : t.border,
              opacity: i + 1 <= phase ? 1 : 0.6,
            }}></div>
            <div style={{
              fontFamily: TYPE.sans, fontSize: 9.5, letterSpacing: "0.06em", textTransform: "uppercase",
              color: i + 1 === phase ? t.ink1 : t.ink4, marginTop: 8,
              textAlign: "center", fontWeight: i + 1 === phase ? 700 : 500,
            }}>{p}</div>
          </div>
        ))}
      </div>
      {notes && (
        <p style={{ fontFamily: TYPE.sans, fontSize: 13, color: t.ink2, lineHeight: 1.6, margin: "16px 0 0", textAlign: "justify" }}>{notes}</p>
      )}
    </div>
  );
};

// SBCost — agora só mostra o veredict do produto, grande e colorido.
// Sem régua, sem "Veredito", sem subtexto.
const SBCost = ({ verdict, t }) => {
  if (!verdict) return null;
  const map = {
    positive: t.success,
    caution:  t.warn,
    negative: t.danger,
    neutral:  t.ink2,
    premium:  t.accent,
  };
  const color = map[verdict.tone] || t.ink1;
  // Escala a tipografia para rótulos longos não quebrarem em linhas estranhas
  const len = (verdict.label || "").length;
  const fontSize = len > 22 ? 30 : len > 14 ? 36 : 44;
  // Respeita \n explícito no rótulo para forçar a quebra exatamente onde queremos
  const lines = (verdict.label || "").split("\n");
  return (
    <div style={{
      fontFamily: TYPE.display,
      fontSize, lineHeight: 1.02,
      letterSpacing: "-0.01em",
      color, textTransform: "uppercase",
      textWrap: "balance",
    }}>
      {lines.map((ln, i) => (
        <React.Fragment key={i}>
          {i > 0 && <br/>}
          {ln}
        </React.Fragment>
      ))}
    </div>
  );
};

const SBSocial = ({ patientCount, timeToEffect, citation, t }) => (
  <div>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 16 }}>
      <div style={{ background: t.bg0, border: `1px solid ${t.border}`, borderRadius: RADIUS.md, padding: "16px" }}>
        <div style={{ fontFamily: TYPE.display, fontSize: 32, color: t.ink1, lineHeight: 1, marginBottom: 6 }}>{patientCount}</div>
        <div style={{ fontFamily: TYPE.sans, fontSize: 11, color: t.ink3, lineHeight: 1.4 }}>pacientes em uso desta fórmula</div>
      </div>
      <div style={{ background: t.bg0, border: `1px solid ${t.border}`, borderRadius: RADIUS.md, padding: "16px" }}>
        <div style={{ fontFamily: TYPE.display, fontSize: 32, color: t.ink1, lineHeight: 1, marginBottom: 6 }}>{timeToEffect}</div>
        <div style={{ fontFamily: TYPE.sans, fontSize: 11, color: t.ink3, lineHeight: 1.4 }}>tempo médio até o primeiro sinal</div>
      </div>
    </div>
    {citation && (
      <div style={{
        fontFamily: TYPE.sans, fontSize: 14, lineHeight: 1.55, color: t.ink2,
        fontStyle: "italic", paddingLeft: 14, borderLeft: `2px solid ${t.border}`,
      }}>"{citation}"</div>
    )}
  </div>
);

// ────────────────────────────────────────
// RELATOS — depoimentos de pacientes (positivo + negativo)
// ────────────────────────────────────────
const SBRelatos = ({ items, t }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
    {items.map((r, i) => {
      const pos = r.tone === "positivo";
      const bg = pos ? "rgba(90,154,90,0.08)" : "rgba(191,122,122,0.08)";
      const bd = pos ? "rgba(90,154,90,0.30)" : "rgba(191,122,122,0.30)";
      const fg = pos ? "rgb(122,191,122)" : "rgb(191,122,122)";
      return (
        <div key={i} style={{
          background: bg, border: `1px solid ${bd}`,
          borderRadius: RADIUS.md, padding: "14px 16px",
        }}>
          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "flex-start",
            gap: 8, marginBottom: 10,
          }}>
            <span style={{
              fontFamily: TYPE.sans, fontSize: 11, fontWeight: 600,
              color: t.ink2, lineHeight: 1.4,
            }}>{r.pessoa}</span>
            <span style={{
              fontFamily: TYPE.sans, fontSize: 9.5, fontWeight: 700,
              letterSpacing: "0.10em", textTransform: "uppercase",
              padding: "4px 9px", borderRadius: 4,
              background: pos ? "rgba(90,154,90,0.15)" : "rgba(191,122,122,0.15)",
              color: fg, border: `1px solid ${bd}`,
              whiteSpace: "nowrap", flexShrink: 0,
            }}>{pos ? "Positivo" : "Sem resultado"}</span>
          </div>
          <div style={{
            fontFamily: TYPE.sans, fontSize: 13.5, lineHeight: 1.65,
            fontStyle: "italic", color: t.ink2, textAlign: "justify",
          }}>"{r.texto}"</div>
        </div>
      );
    })}
    <div style={{
      fontFamily: TYPE.sans, fontSize: 11, color: t.ink3, lineHeight: 1.55,
      marginTop: 4, paddingTop: 10, borderTop: `1px solid ${t.border}`,
    }}>
      Relatos individuais não garantem resultado. Respostas variam conforme saúde geral, qualidade do produto e protocolo. Sem avaliação médica, o risco de não resultado é alto.
    </div>
  </div>
);

// Section renderer — escolhe o bloco certo
const Section = ({ section, t, num, product }) => {
  let body;
  switch (section.kind) {
    case "list":      body = <SBList items={section.items} tone={section.tone} t={t} />; break;
    case "protocol":  body = <SBProtocol grid={section.grid} t={t} />; break;
    case "paragraph": body = <SBParagraph body={section.body} t={t} />; break;
    case "quote":     body = <SBQuote body={section.body} t={t} />; break;
    case "ativos":    body = <SBAtivos items={section.items} t={t} />; break;
    case "phase":     body = <SBPhase phase={section.phase} notes={section.notes} t={t} />; break;
    case "cost":      body = <SBCost verdict={product?.verdict} t={t} />; break;
    case "social":    body = <SBSocial {...section} t={t} />; break;
    case "relatos":   body = <SBRelatos items={section.items} t={t} />; break;
    default: body = null;
  }
  return (
    <section style={{ marginBottom: 36 }}>
      <SectionLabel num={num} t={t}>{section.title}</SectionLabel>
      {body}
    </section>
  );
};

Object.assign(window, {
  Icon, Pill, SectionLabel, ProductVisual, ProductCard, Section, LegalDisclaimer,
});

// ────────────────────────────────────────
// DISCLAIMER LEGAL — usado em todas as telas
// (mesmo texto que o usuário usa nas legendas do Instagram)
// ────────────────────────────────────────
function LegalDisclaimer({ t, compact = false }) {
  return (
    <div style={{
      margin: compact ? "0 20px 12px" : "0 20px 24px",
      padding: "16px 18px",
      background: t.bg1,
      border: `1px solid ${t.border}`,
      borderRadius: RADIUS.md,
      fontFamily: TYPE.sans,
    }}>
      <div style={{
        fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
        color: t.ink3, fontWeight: 700, marginBottom: 10,
      }}>Dr. Ulisses Nakagawa · CRM-MS 16293</div>

      <p style={{
        fontSize: 12.5, lineHeight: 1.65, color: t.ink2, margin: "0 0 10px",
        textAlign: "justify",
      }}>
        Se você busca uma avaliação médica individualizada, com abordagem clínica global e responsável, fale "consulta" no WhatsApp para receber as informações.
      </p>

      <div style={{
        display: "flex", alignItems: "flex-start", gap: 8,
        padding: "10px 12px", margin: "0 0 10px",
        background: t.bg0, border: `1px solid ${t.border}`,
        borderRadius: 8,
      }}>
        <span style={{ flexShrink: 0, color: t.ink1, marginTop: 1 }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 9v4M12 17h.01M10.3 3.6 2.5 18a2 2 0 0 0 1.8 3h15.4a2 2 0 0 0 1.8-3L13.7 3.6a2 2 0 0 0-3.4 0z"></path></svg>
        </span>
        <p style={{
          fontSize: 11.5, lineHeight: 1.6, color: t.ink2, margin: 0,
          textAlign: "justify",
        }}>
          Conteúdo informativo. Busque sempre informações médicas qualificadas, individualizadas e sem julgamento. Toda substância capaz de alterar funções fisiológicas envolve riscos e deve ser avaliada caso a caso, com acompanhamento médico adequado.
        </p>
      </div>

      <p style={{
        fontSize: 11.5, lineHeight: 1.6, color: t.ink3, margin: 0,
        textAlign: "justify",
      }}>
        O papel do médico é realizar uma avaliação clínica ampla, iniciar investigações diagnósticas e conduzir o caso com responsabilidade clínica, realizando encaminhamentos quando indicados.
      </p>
    </div>
  );
}
