/* BioReveal — Medical screening step.
 *
 * Captures the clinical truth a prescriber needs before any peptide can be
 * approved: current meds, conditions, allergies, family history, prior peptide
 * use, pregnancy/breastfeeding. Uses pill-style toggles + autocomplete-ish
 * tag input for max speed (4 min total intake budget).
 */

const COMMON_MEDS = [
  "Lisinopril", "Atorvastatin", "Metformin", "Levothyroxine", "Sertraline",
  "Escitalopram", "Bupropion", "Adderall", "Vyvanse", "Wellbutrin",
  "Ozempic", "Mounjaro", "Wegovy", "Zepbound", "Testosterone", "Estrogen",
  "Birth control pill", "Thyroid medication", "Beta blocker", "Statin",
  "Rapamycin", "Metformin (off-label)",
];

const CONDITIONS = [
  { id: "hypertension", label: "High blood pressure" },
  { id: "diabetes", label: "Diabetes (any type)" },
  { id: "thyroid", label: "Thyroid disorder" },
  { id: "kidney", label: "Kidney disease" },
  { id: "liver", label: "Liver disease" },
  { id: "heart", label: "Heart disease" },
  { id: "cancer_history", label: "Cancer (current or past)" },
  { id: "autoimmune", label: "Autoimmune condition" },
  { id: "depression", label: "Depression / anxiety" },
  { id: "seizure", label: "Seizure disorder" },
  { id: "pituitary", label: "Pituitary tumor / disorder" },
  { id: "mental", label: "Bipolar / schizophrenia" },
  { id: "none", label: "None of the above" },
];

const FAMILY_FLAGS = [
  { id: "fh_cancer", label: "Cancer (any)" },
  { id: "fh_heart", label: "Heart disease" },
  { id: "fh_thyroid", label: "Thyroid cancer" },
  { id: "fh_men2", label: "MEN-2 syndrome" },
  { id: "fh_diabetes", label: "Type 2 diabetes" },
  { id: "fh_none", label: "None known" },
];

const PRIOR_PEPS = [
  "Sermorelin", "Ipamorelin", "CJC-1295", "BPC-157", "TB-500",
  "NAD+", "GHK-Cu", "Glutathione", "Selank", "Semax",
  "Semaglutide", "Tirzepatide", "Other",
];

const TagInput = ({ label, suggestions, value = [], onChange, placeholder }) => {
  const [input, setInput] = React.useState("");
  const add = (v) => {
    const t = v.trim();
    if (!t) return;
    if (!value.includes(t)) onChange([...value, t]);
    setInput("");
  };
  const remove = (t) => onChange(value.filter(x => x !== t));
  const filtered = suggestions.filter(s => s.toLowerCase().includes(input.toLowerCase()) && !value.includes(s)).slice(0, 6);
  return (
    <div style={{ marginBottom: 22 }}>
      <div className="br-eyebrow" style={{ marginBottom: 8 }}>{label}</div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 8 }}>
        {value.map(t => (
          <span key={t} style={{
            background: "var(--ink)", color: "var(--paper)", padding: "5px 10px",
            borderRadius: 999, fontSize: 12, fontFamily: "var(--font-mono)", letterSpacing: "0.05em",
            display: "inline-flex", alignItems: "center", gap: 6,
          }}>
            {t}
            <button onClick={() => remove(t)} style={{ background: "none", border: "none", color: "var(--paper)", cursor: "pointer", padding: 0, fontSize: 14, lineHeight: 1 }}>×</button>
          </span>
        ))}
      </div>
      <input
        type="text" placeholder={placeholder} value={input}
        onChange={(e) => setInput(e.target.value)}
        onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(input); } }}
        style={{
          width: "100%", boxSizing: "border-box", padding: "12px 14px",
          background: "var(--paper-2)", border: "1.5px solid var(--paper-3)",
          borderRadius: "var(--r-md)", fontSize: 14, fontFamily: "inherit", color: "var(--ink)",
        }}
      />
      {input && filtered.length > 0 && (
        <div style={{ marginTop: 6, display: "flex", flexWrap: "wrap", gap: 6 }}>
          {filtered.map(s => (
            <button key={s} onClick={() => add(s)} style={{
              background: "var(--paper-2)", border: "1px solid var(--paper-3)", padding: "5px 10px",
              borderRadius: 999, fontSize: 12, cursor: "pointer", color: "var(--ink)",
            }}>+ {s}</button>
          ))}
        </div>
      )}
    </div>
  );
};

const ToggleGrid = ({ items, value = [], onChange, max = 0 }) => {
  const toggle = (id) => {
    if (value.includes(id)) {
      onChange(value.filter(x => x !== id));
    } else {
      const next = [...value, id];
      if (max > 0 && next.length > max) return;
      onChange(next);
    }
  };
  return (
    <div className="br-grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))" }}>
      {items.map(it => (
        <button key={it.id}
          className={"br-tile " + (value.includes(it.id) ? "selected" : "")}
          onClick={() => toggle(it.id)}
          style={{ minHeight: 64, padding: "12px 14px" }}
        >
          <div className="br-tile-label" style={{ fontSize: 13 }}>{it.label}</div>
        </button>
      ))}
    </div>
  );
};

const StepMedical = ({ value = {}, onChange }) => {
  const v = {
    current_meds: [],
    conditions: [],
    allergies: [],
    family_history: [],
    prior_peptides: [],
    pregnant: null,
    ...value,
  };
  const set = (k, val) => onChange({ ...v, [k]: val });
  return (
    <>
      <div className="br-eyebrow">07 / 08 · Clinical screen · Required</div>
      <h2 className="br-question">Tell us the truth.</h2>
      <p className="br-sub">Every order is reviewed by a licensed clinician. They need this to clear your protocol — wrong answers here can block fulfillment or cause harm.</p>

      <TagInput
        label="Current medications & supplements"
        suggestions={COMMON_MEDS}
        value={v.current_meds}
        onChange={(x) => set("current_meds", x)}
        placeholder="Type a med name + Enter, or pick from suggestions…"
      />

      <div style={{ marginBottom: 22 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>Existing conditions</div>
        <ToggleGrid items={CONDITIONS} value={v.conditions} onChange={(x) => set("conditions", x.includes("none") && x.length > 1 ? x.filter(i => i !== "none") : x)}/>
      </div>

      <TagInput
        label="Allergies (drugs, foods, materials)"
        suggestions={["Penicillin","Sulfa drugs","Shellfish","Latex","Eggs","Soy","Nuts","Aspirin","NSAIDs","Bee stings"]}
        value={v.allergies}
        onChange={(x) => set("allergies", x)}
        placeholder="Type an allergy + Enter…"
      />

      <div style={{ marginBottom: 22 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>Family history (1st-degree relatives)</div>
        <ToggleGrid items={FAMILY_FLAGS} value={v.family_history} onChange={(x) => set("family_history", x)}/>
      </div>

      <div style={{ marginBottom: 22 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>Have you used peptides before?</div>
        <div className="br-grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))" }}>
          {PRIOR_PEPS.map(p => (
            <button key={p}
              className={"br-tile " + (v.prior_peptides.includes(p) ? "selected" : "")}
              onClick={() => set("prior_peptides", v.prior_peptides.includes(p) ? v.prior_peptides.filter(x => x !== p) : [...v.prior_peptides, p])}
              style={{ minHeight: 56, padding: "10px 12px" }}
            >
              <div className="br-tile-label" style={{ fontSize: 13 }}>{p}</div>
            </button>
          ))}
        </div>
      </div>

      <div style={{ marginBottom: 14 }}>
        <div className="br-eyebrow" style={{ marginBottom: 10 }}>Are you pregnant, breastfeeding, or trying to conceive?</div>
        <div style={{ display: "flex", gap: 10 }}>
          {[{ k: false, l: "No" }, { k: true, l: "Yes" }, { k: "na", l: "Not applicable" }].map(o => (
            <button key={String(o.k)}
              className={"br-option " + (v.pregnant === o.k ? "selected" : "")}
              style={{ flex: 1, justifyContent: "center" }}
              onClick={() => set("pregnant", o.k)}
            >{o.l}</button>
          ))}
        </div>
      </div>

      <div style={{ marginTop: 14, fontSize: 11, color: "var(--muted)", lineHeight: 1.5, fontFamily: "var(--font-mono)", letterSpacing: "0.05em" }}>
        🔒 <strong>HIPAA-ALIGNED</strong> · Only the reviewing clinician sees the full record. Stack matching uses anonymized signal vectors.
      </div>
    </>
  );
};

window.BR_STEPS = window.BR_STEPS || {};
window.BR_STEPS.StepMedical = StepMedical;
