// ─────────────────────────────────────────────────────────────
// FERRAMENTAS DA SESSÃO PEPTÍDEOS
// Vivem dentro da tela Lista quando type === "peptideo".
// 1. Checklist Pré-Uso (6 itens)
// 2. Guia de Armazenamento (4 regras)
// 3. Calculadora de Diluição (mg + ml + mcg → ml + UI)
// ─────────────────────────────────────────────────────────────

const { useState, useEffect, useMemo } = React;

// ===========================================================
// CHECKLIST PRÉ-USO
// ===========================================================
const CHECKLIST_ITEMS = [
  "Tenho prescrição médica com nome do peptídeo, dose e ciclo",
  "O peptídeo veio de farmácia de manipulação de referência",
  "Tenho seringa de insulina U-100 e água bacteriostática",
  "Sei onde e como armazenar após diluição (geladeira 4°C, não freezer)",
  "Calculei quantas UI na seringa equivalem à minha dose",
  "Sei o que observar nos primeiros dias e quando contactar o médico",
];

function PeptideoChecklist({ t }) {
  const [checked, setChecked] = useState(() => {
    try { return JSON.parse(localStorage.getItem("pept_checklist") || "[]"); }
    catch { return []; }
  });
  useEffect(() => {
    localStorage.setItem("pept_checklist", JSON.stringify(checked));
  }, [checked]);

  const toggle = (i) => {
    setChecked((arr) => arr.includes(i) ? arr.filter(x => x !== i) : [...arr, i]);
  };
  const reset = () => setChecked([]);
  const done = checked.length === CHECKLIST_ITEMS.length;

  return (
    <ToolFrame
      eyebrow="Ferramenta · 01"
      title="Checklist Pré-Uso"
      lede="Estou pronto para começar?"
      desc="Confirme cada item antes da primeira aplicação."
      t={t}
    >
      <ol style={{ listStyle: "none", padding: 0, margin: 0 }}>
        {CHECKLIST_ITEMS.map((item, i) => {
          const on = checked.includes(i);
          return (
            <li key={i}>
              <button onClick={() => toggle(i)} style={{
                width: "100%", textAlign: "left", cursor: "pointer",
                display: "flex", alignItems: "flex-start", gap: 14,
                padding: "14px 0",
                borderTop: i === 0 ? "none" : `1px solid ${t.border}`,
                background: "transparent", border: "none",
                borderTopStyle: i === 0 ? "none" : "solid",
                fontFamily: TYPE.sans,
              }}>
                <span style={{
                  flexShrink: 0, marginTop: 1,
                  width: 22, height: 22, borderRadius: 6,
                  border: `1.5px solid ${on ? t.accent : t.borderStrong}`,
                  background: on ? t.accent : "transparent",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  transition: "background 0.15s ease, border-color 0.15s ease",
                }}>
                  {on && (
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={t.accentInk} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                      <path d="m5 12 5 5 9-11"></path>
                    </svg>
                  )}
                </span>
                <span style={{
                  flex: 1, fontSize: 14, lineHeight: 1.5,
                  color: on ? t.ink3 : t.ink1,
                  textDecoration: on ? "line-through" : "none",
                  textDecorationColor: t.ink4,
                }}>
                  <span style={{
                    fontFamily: TYPE.mono, fontSize: 11,
                    color: t.ink4, marginRight: 10, fontVariantNumeric: "tabular-nums",
                  }}>{String(i + 1).padStart(2, "0")}</span>
                  {item}
                </span>
              </button>
            </li>
          );
        })}
      </ol>

      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginTop: 18, paddingTop: 14, borderTop: `1px solid ${t.border}`,
      }}>
        <span style={{
          fontFamily: TYPE.sans, fontSize: 11, color: done ? t.accent : t.ink3,
          letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 700,
        }}>
          {done ? "✓ Tudo pronto" : `${checked.length} de ${CHECKLIST_ITEMS.length}`}
        </span>
        <button onClick={reset} style={{
          background: "transparent", border: "none", cursor: "pointer",
          fontFamily: TYPE.sans, fontSize: 11, color: t.ink3,
          letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 700,
          padding: 0,
        }}>
          Zerar
        </button>
      </div>
    </ToolFrame>
  );
}

// ===========================================================
// GUIA DE ARMAZENAMENTO
// ===========================================================
const STORAGE_RULES = [
  { code: "01", label: "Frasco lacrado",     where: "Freezer ou geladeira", body: "−20°C a 4°C. Longe de luz. Validade conforme fabricante." },
  { code: "02", label: "Após diluição",      where: "Geladeira a 4°C",      body: "Nunca freezer. Usar em até 30 dias." },
  { code: "03", label: "Em transporte",      where: "Bolsa térmica",        body: "Máximo 8h fora da geladeira. Evite luz solar direta." },
  { code: "04", label: "Descarte imediato",  where: "Cor ou turvação",      body: "Reconstituído é transparente. Cor ou partícula significa descarte." },
];

function PeptideoArmazenamento({ t }) {
  return (
    <ToolFrame
      eyebrow="Ferramenta · 02"
      title="Guia de Armazenamento"
      lede="Preserve a potência da molécula"
      desc="Peptídeo guardado errado perde potência. Quatro regras simples."
      t={t}
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 1, background: t.border, borderRadius: RADIUS.md, overflow: "hidden", border: `1px solid ${t.border}` }}>
        {STORAGE_RULES.map((r) => (
          <div key={r.code} style={{
            background: t.bg1, padding: "16px 18px",
            display: "grid", gridTemplateColumns: "auto 1fr", gap: 16, alignItems: "start",
          }}>
            <div style={{
              fontFamily: TYPE.display, fontSize: 22, color: t.ink3,
              lineHeight: 1, letterSpacing: "-0.005em", fontVariantNumeric: "tabular-nums",
            }}>{r.code}</div>
            <div style={{ minWidth: 0 }}>
              <div style={{
                fontFamily: TYPE.sans, fontSize: 9.5, color: t.accent,
                letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700,
                marginBottom: 4,
              }}>{r.where}</div>
              <div style={{
                fontFamily: TYPE.display, fontSize: 18, color: t.ink1,
                letterSpacing: "-0.005em", textTransform: "uppercase",
                marginBottom: 8, lineHeight: 1.05,
              }}>{r.label}</div>
              <div style={{
                fontFamily: TYPE.sans, fontSize: 13, color: t.ink2, lineHeight: 1.55,
              }}>{r.body}</div>
            </div>
          </div>
        ))}
      </div>
    </ToolFrame>
  );
}

// ===========================================================
// CALCULADORA DE DILUIÇÃO
// ===========================================================
function PeptideoCalculadora({ t }) {
  const [mg, setMg]       = useState("");      // mg no frasco
  const [ml, setMl]       = useState("");      // ml de água bact.
  const [dose, setDose]   = useState("");      // valor numérico da dose
  const [doseUnit, setDoseUnit] = useState("mcg"); // "mcg" | "mg"

  const calc = useMemo(() => {
    const mgN   = parseFloat(mg);
    const mlN   = parseFloat(ml);
    const doseN = parseFloat(dose);
    if (!mgN || !mlN || !doseN) return null;
    // Normaliza a dose para mcg
    const doseMcg     = doseUnit === "mg" ? doseN * 1000 : doseN;
    const totalMcg    = mgN * 1000;
    const concPorMl   = totalMcg / mlN;
    const volumeMl    = doseMcg / concPorMl;
    const ui          = volumeMl * 100;
    const aplicacoes  = Math.floor(totalMcg / doseMcg);
    return {
      totalMcg, concPorMl, volumeMl, ui, aplicacoes,
    };
  }, [mg, ml, dose, doseUnit]);

  return (
    <ToolFrame
      eyebrow="Ferramenta · 03"
      title="Calculadora de Diluição"
      lede="Quanto coloco na seringa?"
      desc="Preencha os 3 campos e o resultado aparece automático."
      t={t}
    >

      {/* Inputs */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <CalcInput
          label="Apresentação do frasco"
          sub="Dose do peptídeo no frasco"
          placeholder="ex: 10"
          unit="mg"
          value={mg}
          onChange={setMg}
          t={t}
        />
        <CalcInput
          label="Água bacteriostática"
          sub="Quanto você adicionou"
          placeholder="ex: 2"
          unit="ml"
          value={ml}
          onChange={setMl}
          t={t}
        />
        <CalcDoseInput
          label="Dose prescrita"
          sub="Valor por aplicação"
          placeholder={doseUnit === "mcg" ? "ex: 200" : "ex: 0,5"}
          unit={doseUnit}
          onUnitChange={setDoseUnit}
          value={dose}
          onChange={setDose}
          t={t}
        />
      </div>

      {/* Resultado */}
      <div style={{
        marginTop: 18, padding: 18, borderRadius: RADIUS.md,
        background: calc ? t.ink1 : t.bg0,
        color: calc ? t.bg0 : t.ink3,
        border: `1px solid ${calc ? t.ink1 : t.border}`,
        transition: "all 0.2s ease",
      }}>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 10, letterSpacing: "0.18em",
          textTransform: "uppercase", fontWeight: 700,
          color: calc ? t.bg1 : t.ink4, marginBottom: 12,
        }}>Resultado</div>

        {calc ? (
          <>
            <div style={{ display: "flex", alignItems: "baseline", gap: 18, marginBottom: 14, flexWrap: "wrap" }}>
              <div>
                <div style={{
                  fontFamily: TYPE.display, fontSize: 48, lineHeight: 0.95,
                  letterSpacing: "-0.02em", color: calc ? t.bg0 : t.ink1,
                }}>{calc.ui.toFixed(0)}</div>
                <div style={{
                  fontFamily: TYPE.sans, fontSize: 10.5, letterSpacing: "0.16em",
                  textTransform: "uppercase", fontWeight: 700,
                  color: calc ? t.bg1 : t.ink3, marginTop: 4,
                }}>UI na seringa U-100</div>
              </div>
              <div style={{ width: 1, height: 44, background: calc ? t.ink3 : t.border }}></div>
              <div>
                <div style={{
                  fontFamily: TYPE.display, fontSize: 30, lineHeight: 0.95,
                  letterSpacing: "-0.01em", color: calc ? t.bg0 : t.ink1,
                }}>{calc.volumeMl.toFixed(2)}<span style={{ fontSize: 16, opacity: 0.7 }}> ml</span></div>
                <div style={{
                  fontFamily: TYPE.sans, fontSize: 10.5, letterSpacing: "0.16em",
                  textTransform: "uppercase", fontWeight: 700,
                  color: calc ? t.bg1 : t.ink3, marginTop: 4,
                }}>Volume por aplicação</div>
              </div>
            </div>
            <div style={{
              fontFamily: TYPE.sans, fontSize: 12, color: calc ? t.bg1 : t.ink3,
              lineHeight: 1.55, paddingTop: 10, borderTop: `1px solid ${calc ? t.ink3 : t.border}`,
              opacity: 0.85,
            }}>
              Concentração de <strong>{Math.round(calc.concPorMl)} mcg/ml</strong>. Rende aproximadamente <strong>{calc.aplicacoes} aplicações</strong> por frasco.
            </div>
          </>
        ) : (
          <div style={{
            fontFamily: TYPE.sans, fontSize: 13, color: t.ink3, lineHeight: 1.55,
          }}>
            Preencha os três campos acima para ver o cálculo.
          </div>
        )}
      </div>

      {/* Como funciona */}
      <details style={{ marginTop: 16, cursor: "pointer" }}>
        <summary style={{
          fontFamily: TYPE.sans, fontSize: 11, color: t.ink3,
          letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 700,
          listStyle: "none", paddingTop: 12, borderTop: `1px solid ${t.border}`,
        }}>Como o cálculo funciona</summary>
        <ol style={{ paddingLeft: 22, margin: "14px 0 0", color: t.ink2 }}>
          {[
            <>1 mg do frasco equivale a <strong>1.000 mcg</strong>.</>,
            <>Total de mcg dividido por ml de água é a <strong>concentração por ml</strong>.</>,
            <>Dose dividida pela concentração é o <strong>volume em ml</strong>.</>,
            <>Volume vezes 100 é a <strong>UI na seringa U-100</strong> (UI não é dose, é volume).</>,
          ].map((step, i) => (
            <li key={i} style={{
              fontFamily: TYPE.sans, fontSize: 13, lineHeight: 1.6,
              paddingBottom: 6,
            }}>{step}</li>
          ))}
        </ol>
      </details>
    </ToolFrame>
  );
}

// ===========================================================
// PRIMITIVES DAS FERRAMENTAS
// ===========================================================

// Frame editorial usado pelas 3 ferramentas — agora gaveta (drawer) recolhida por padrão
function ToolFrame({ eyebrow, title, lede, desc, children, t }) {
  const [open, setOpen] = useState(false);
  return (
    <section style={{
      background: t.bg1, border: `1px solid ${t.border}`,
      borderRadius: RADIUS.lg,
      marginBottom: 10,
      overflow: "hidden",
    }}>
      <button
        type="button"
        onClick={() => setOpen(v => !v)}
        style={{
          width: "100%", textAlign: "left", cursor: "pointer",
          padding: "18px 22px",
          background: "transparent", border: "none",
          display: "flex", alignItems: "center", gap: 14,
          fontFamily: TYPE.sans, color: t.ink1,
          WebkitTapHighlightColor: "transparent",
        }}
      >
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: TYPE.sans, fontSize: 10, color: t.accent,
            letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 700,
            marginBottom: 8,
          }}>{eyebrow}</div>
          <h3 style={{
            fontFamily: TYPE.display, fontSize: 22, color: t.ink1,
            letterSpacing: "-0.005em", lineHeight: 1.05, textTransform: "uppercase",
            margin: 0,
          }}>{title}</h3>
        </div>
        <span style={{
          flexShrink: 0,
          width: 32, height: 32, borderRadius: 999,
          background: t.bg0, border: `1px solid ${t.border}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.ink2,
          transform: open ? "rotate(180deg)" : "rotate(0deg)",
          transition: "transform 0.25s ease",
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="m6 9 6 6 6-6"></path>
          </svg>
        </span>
      </button>

      {open && (
        <div style={{
          padding: "0 22px 22px",
          borderTop: `1px solid ${t.border}`,
        }}>
          {lede && (
            <div style={{
              fontFamily: TYPE.sans, fontSize: 14, color: t.ink2,
              fontStyle: "italic", margin: "16px 0 10px",
            }}>{lede}</div>
          )}
          {desc && (
            <p style={{
              fontFamily: TYPE.sans, fontSize: 12.5, color: t.ink3,
              lineHeight: 1.55, margin: "0 0 18px",
            }}>{desc}</p>
          )}
          {children}
        </div>
      )}
    </section>
  );
}

// Input numérico com label, sub e unidade
function CalcInput({ label, sub, placeholder, unit, value, onChange, t }) {
  return (
    <label style={{ display: "block" }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "baseline",
        marginBottom: 6,
      }}>
        <span style={{
          fontFamily: TYPE.sans, fontSize: 12, color: t.ink1, fontWeight: 600,
        }}>{label}</span>
        <span style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 700,
        }}>{unit}</span>
      </div>
      {sub && (
        <div style={{
          fontFamily: TYPE.sans, fontSize: 11, color: t.ink3,
          marginBottom: 8,
        }}>{sub}</div>
      )}
      <div style={{ position: "relative" }}>
        <input
          type="number" inputMode="decimal"
          value={value} onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          style={{
            width: "100%", padding: "13px 56px 13px 14px",
            background: t.bg0, border: `1px solid ${t.border}`,
            borderRadius: RADIUS.md, color: t.ink1,
            fontFamily: TYPE.mono, fontSize: 16, fontVariantNumeric: "tabular-nums",
            outline: "none", appearance: "textfield",
          }}
        />
        <span style={{
          position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)",
          fontFamily: TYPE.sans, fontSize: 11, color: t.ink3,
          letterSpacing: "0.08em", textTransform: "uppercase", fontWeight: 700,
          pointerEvents: "none",
        }}>{unit}</span>
      </div>
    </label>
  );
}

// Input numérico com toggle de unidade (mcg / mg)
function CalcDoseInput({ label, sub, placeholder, unit, onUnitChange, value, onChange, t }) {
  return (
    <label style={{ display: "block" }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "baseline",
        marginBottom: 6,
      }}>
        <span style={{
          fontFamily: TYPE.sans, fontSize: 12, color: t.ink1, fontWeight: 600,
        }}>{label}</span>
      </div>
      {sub && (
        <div style={{
          fontFamily: TYPE.sans, fontSize: 11, color: t.ink3,
          marginBottom: 8,
        }}>{sub}</div>
      )}
      <div style={{ position: "relative", display: "flex", gap: 0 }}>
        <input
          type="number" inputMode="decimal"
          value={value} onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          style={{
            flex: 1, padding: "13px 14px",
            background: t.bg0, border: `1px solid ${t.border}`,
            borderRadius: `${RADIUS.md}px 0 0 ${RADIUS.md}px`,
            borderRight: "none",
            color: t.ink1,
            fontFamily: TYPE.mono, fontSize: 16, fontVariantNumeric: "tabular-nums",
            outline: "none", appearance: "textfield",
          }}
        />
        <div style={{
          display: "flex", flexShrink: 0,
          border: `1px solid ${t.border}`,
          borderRadius: `0 ${RADIUS.md}px ${RADIUS.md}px 0`,
          overflow: "hidden",
        }}>
          {["mcg", "mg"].map((u, i) => (
            <button key={u} type="button" onClick={() => onUnitChange(u)} style={{
              padding: "0 14px", minWidth: 52, cursor: "pointer",
              background: unit === u ? t.ink1 : "transparent",
              color: unit === u ? t.bg0 : t.ink3,
              border: "none",
              borderLeft: i > 0 ? `1px solid ${t.border}` : "none",
              fontFamily: TYPE.sans, fontSize: 12, fontWeight: 700,
              letterSpacing: "0.08em", textTransform: "uppercase",
            }}>{u}</button>
          ))}
        </div>
      </div>
    </label>
  );
}

// ===========================================================
// WRAPPER — todas as 3 ferramentas empilhadas
// ===========================================================
function PeptideoFerramentas({ t }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
      <PeptideoChecklist t={t} />
      <PeptideoArmazenamento t={t} />
      <PeptideoCalculadora t={t} />
    </div>
  );
}

Object.assign(window, {
  PeptideoChecklist, PeptideoArmazenamento, PeptideoCalculadora,
  PeptideoFerramentas, CalcDoseInput,
});
