/* field consultant: two-path guided flow (Build 5).
   DETERMINISTIC recommendation engine, no live LLM. Reads window.FIELD_PRODUCTS.
   Path A first-timer: experience -> goal -> needle -> composed stack -> intake -> confirm.
   Path B experienced: experience -> library builder -> intake -> confirm.
   Both route to Shayne for review. Copy is vitality register, never longevity. */
const { useState: useStateC } = React;

/* Retatrutide is investigational (flag 'retatrutide-review'). Hidden by default.
   Flip to true only after Sesie clears it. One-line switch, do not surface until then. */
const SHOW_RETATRUTIDE = false;

/* Program metadata mirrors the launch menu. Prices are PLACEHOLDERS (Dan tunes). */
const PROGRAMS = {
  regenerative: { name: "Regenerative", price: 135, tag: "Repair and renewal", blurb: "Peptide protocols that support the body's repair and renewal, so you recover faster and feel restored." },
  strength:     { name: "Strength",     price: 185, tag: "Lean mass and capacity", blurb: "For lean muscle, training capacity, and the strength to move through life fully." },
  immune:       { name: "Immune",       price: 125, tag: "Resilience", blurb: "Foundational support for resilience, so you bounce back and stay well." },
  beauty:       { name: "Beauty",       price: 115, tag: "Glow and radiance", blurb: "Skin, hair, and the radiance that comes from feeling good in your body." },
  reset:        { name: "Reset",        price: 249, tag: "Metabolic reset", blurb: "A physician-guided metabolic reset to feel lighter, more energetic, more yourself." },
};
const PROGRAM_ORDER = ["regenerative", "strength", "immune", "beauty", "reset"];

const OUTCOMES = [
  { k: "recover",    label: "Recover faster, repair, feel restored", pkg: "regenerative" },
  { k: "strength",   label: "Get stronger, build lean muscle", pkg: "strength" },
  { k: "resilience", label: "Resilience, bounce back", pkg: "immune" },
  { k: "beauty",     label: "Skin, hair, radiance, glow", pkg: "beauty" },
  { k: "reset",      label: "Feel lighter, reset my metabolism, more energy", pkg: "reset" },
];

/* A product's primary home is `program`; `also_programs` lists any additional
   programs it belongs to. Overlap is intentional (e.g. glutathione and KPV are
   tagged immune in products.js in addition to their primary program). */
const belongsToProgram = (p, prog) =>
  p.program === prog || (Array.isArray(p.also_programs) && p.also_programs.includes(prog));

const allLaunch = () =>
  (window.FIELD_PRODUCTS || []).filter(
    (p) => p.priority === "Launch" && (SHOW_RETATRUTIDE || p.flag !== "retatrutide-review")
  );

const productsForProgram = (prog) => allLaunch().filter((p) => belongsToProgram(p, prog));

const formatLabel = (p) =>
  p.needle ? "Injectable" : ({ oral: "Oral", sublingual: "Sublingual", nasal: "Nasal spray", topical: "Topical" }[p.format] || p.format);

/* Customer-facing sub-line: actives only. pharmacy_lane is internal vendor taxonomy
   (it carries "Longevity" and other internal terms) and is never shown to users. */
const shortLine = (p) => p.actives || "";

/* Compose a first-timer stack: needle-free forward. */
const composeStack = (prog, needlePref) => {
  const pool = productsForProgram(prog);
  const free = pool.filter((p) => !p.needle);
  const inj = pool.filter((p) => p.needle);
  let core, addons;
  if (needlePref === "needle_free") {
    core = free.slice(0, 4);
    addons = [];
  } else {
    core = free.slice(0, 3);
    addons = inj.slice(0, 2); // gentle-forward: injectables offered as an optional add
  }
  if (core.length < 2) core = pool.slice(0, Math.min(3, pool.length));
  return { core, addons };
};

/* Library groups: a product appears in every program it belongs to (overlap allowed). */
const libraryGroups = () => {
  const grouped = {};
  PROGRAM_ORDER.forEach((prog) => { grouped[prog] = productsForProgram(prog); });
  return grouped;
};

function ProductRow({ p, action, actionLabel, selected }) {
  return (
    <div className={"prodrow" + (selected ? " sel" : "")}>
      <div className="prodrow__thumb" aria-hidden="true">image</div>
      <div className="prodrow__body">
        <div className="prodrow__name">{p.name}</div>
        {shortLine(p) ? <div className="prodrow__sub">{shortLine(p)}</div> : null}
        <span className={"badge " + (p.needle ? "badge--inj" : "badge--free")}>
          {p.needle ? "Injectable" : "Needle-free · " + formatLabel(p)}
        </span>
      </div>
      {action ? (
        <button className={"prodrow__act" + (selected ? " on" : "")} onClick={() => action(p)}>
          {selected ? "Remove" : actionLabel}
        </button>
      ) : null}
    </div>
  );
}

function Consultant({ open, onClose }) {
  const [view, setView] = useStateC("experience"); // experience|goal|needle|stack|library|intake|confirm
  const [experience, setExperience] = useStateC(null); // first_timer|experienced
  const [goal, setGoal] = useStateC(null); // program key (first-timer)
  const [needle, setNeedle] = useStateC(null); // needle_free|open_to_injections
  const [stack, setStack] = useStateC([]); // array of product objects
  const [progFilter, setProgFilter] = useStateC("all");
  const [fmtFilter, setFmtFilter] = useStateC("all"); // all|needle_free|injectable

  const [name, setName] = useStateC("");
  const [email, setEmail] = useStateC("");
  const [phone, setPhone] = useStateC("");
  const [ageOk, setAgeOk] = useStateC(false);
  const [inHawaii, setInHawaii] = useStateC(false);
  const [pregnant, setPregnant] = useStateC(false);
  const [saving, setSaving] = useStateC(false);
  const [outcome, setOutcome] = useStateC(null); // joined|waitlist

  const reset = () => {
    setView("experience"); setExperience(null); setGoal(null); setNeedle(null); setStack([]);
    setProgFilter("all"); setFmtFilter("all");
    setName(""); setEmail(""); setPhone(""); setAgeOk(false); setInHawaii(false); setPregnant(false);
    setSaving(false); setOutcome(null);
  };
  const close = () => { onClose(); setTimeout(reset, 300); };

  const inStack = (p) => stack.some((s) => s.name === p.name && s.size === p.size);
  const toggleStack = (p) => setStack((prev) => inStack(p) ? prev.filter((s) => !(s.name === p.name && s.size === p.size)) : [...prev, p]);

  const composed = goal ? composeStack(goal, needle) : { core: [], addons: [] };

  // What products are captured for this lead.
  const selectedProducts = experience === "first_timer"
    ? composed.core.map((p) => p.name)
    : stack.map((p) => p.name);

  const canSubmit = name.trim() && email.trim() && ageOk;

  const saveLead = async (kind) => {
    if (saving) return;
    setSaving(true);
    const pkgName = experience === "first_timer"
      ? (goal ? PROGRAMS[goal].name : null)
      : (progFilter !== "all" ? PROGRAMS[progFilter].name : "Custom");
    const goalStr = experience === "first_timer" ? (goal || "") : (progFilter !== "all" ? progFilter : "");
    try {
      if (window.supabaseClient) {
        await window.supabaseClient.from("intake_leads").insert({
          first_name: name,
          email,
          phone: phone || null,
          goal: goalStr,
          package: pkgName,
          source: "website",
          eligibility: { age_ok: ageOk, in_hawaii: inHawaii, pregnant_nursing: pregnant },
          experience_level: experience,
          needle_preference: needle, // null for experienced path
          selected_products: selectedProducts,
        });
      }
    } catch (e) { console.warn("intake submit", e); }
    setSaving(false);
    setOutcome(kind);
    setView("confirm");
  };

  const groups = libraryGroups();
  const activePkg = goal ? PROGRAMS[goal] : null;

  const libVisible = (p) => {
    if (fmtFilter === "needle_free" && p.needle) return false;
    if (fmtFilter === "injectable" && !p.needle) return false;
    return true;
  };

  return (
    <div className={"overlay" + (open ? " open" : "")} onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div className={"modal" + (view === "library" ? " modal--wide" : "")} role="dialog" aria-modal="true" aria-label="field consultant">
        <button className="modal__close" onClick={close} aria-label="Close"><Icon d={Icons.close} size={20} sw={1.6} /></button>
        <img className="modal__mark" src="/assets/field-wordmark-graphite.svg" alt="field" />

        {view === "experience" && (
          <div>
            <span className="modal__eyebrow">field consultant</span>
            <h3 className="modal__title">Have you done peptide or GLP-1 therapy before?</h3>
            <p className="modal__desc">This just tailors the experience. A licensed provider reviews and finalizes every stack either way.</p>
            <div className="choices">
              <button className="choice" onClick={() => { setExperience("first_timer"); setView("goal"); }}>
                <span className="choice__k">New to this</span>
                <span className="choice__v">Guide me. Recommend a starting stack for my goal.</span>
              </button>
              <button className="choice" onClick={() => { setExperience("experienced"); setView("library"); }}>
                <span className="choice__k">I've done this before</span>
                <span className="choice__v">Let me browse the full library and build my own stack.</span>
              </button>
            </div>
          </div>
        )}

        {view === "goal" && (
          <div>
            <span className="modal__eyebrow">Guided · step 1 of 3</span>
            <h3 className="modal__title">What do you want more of?</h3>
            <p className="modal__desc">Pick the one that fits best. Your provider tailors the rest.</p>
            <div className="outcomes">
              {OUTCOMES.map((o) => (
                <div key={o.k} className={"goal" + (goal === o.pkg ? " sel" : "")} onClick={() => setGoal(o.pkg)}>
                  <span className="dot" /> {o.label}
                </div>
              ))}
            </div>
            <div className="modal__actions">
              <button className="modal__back" onClick={() => setView("experience")}>← back</button>
              <button className="btn btn--primary" disabled={!goal} style={{ opacity: goal ? 1 : 0.45 }} onClick={() => goal && setView("needle")}>continue</button>
            </div>
          </div>
        )}

        {view === "needle" && (
          <div>
            <span className="modal__eyebrow">Guided · step 2 of 3</span>
            <h3 className="modal__title">How do you feel about a small self-injection?</h3>
            <p className="modal__desc">Many protocols work needle-free. We lead with the gentler formats either way.</p>
            <div className="choices">
              <button className="choice" onClick={() => { setNeedle("needle_free"); setView("stack"); }}>
                <span className="choice__k">Prefer needle-free</span>
                <span className="choice__v">Nasal, oral, and sublingual formats only.</span>
              </button>
              <button className="choice" onClick={() => { setNeedle("open_to_injections"); setView("stack"); }}>
                <span className="choice__k">Open to a small injection</span>
                <span className="choice__v">Start gentle, with injectable options available if your provider suggests them.</span>
              </button>
            </div>
            <div className="modal__actions" style={{ justifyContent: "flex-start" }}>
              <button className="modal__back" onClick={() => setView("goal")}>← back</button>
            </div>
          </div>
        )}

        {view === "stack" && activePkg && (
          <div>
            <span className="modal__eyebrow">Guided · step 3 of 3</span>
            <h3 className="modal__title">Your recommended starting point.</h3>
            <p className="modal__desc">A starting point your provider confirms. They finalize the protocol and dosing, and can adjust or decline.</p>

            <div className="stack">
              <div className="stack__head">
                <div>
                  <span className="stack__tag">{activePkg.tag}</span>
                  <h4 className="stack__name">{activePkg.name}</h4>
                </div>
                <div className="stack__price">${activePkg.price}<span>/mo</span></div>
              </div>
              <p className="stack__blurb">{activePkg.blurb}</p>
              <div className="stack__products">
                {composed.core.map((p) => <ProductRow key={p.name + p.size} p={p} />)}
              </div>
              {composed.addons.length > 0 && (
                <div className="stack__addons">
                  <span className="stack__addons-label">Optional add-ons, if your provider suggests</span>
                  {composed.addons.map((p) => <ProductRow key={p.name + p.size} p={p} />)}
                </div>
              )}
            </div>

            <div className="modal__actions">
              <button className="modal__back" onClick={() => setView("needle")}>← back</button>
              <button className="btn btn--primary" onClick={() => setView("intake")}>continue</button>
            </div>
          </div>
        )}

        {view === "library" && (
          <div>
            <span className="modal__eyebrow">Build your own stack</span>
            <h3 className="modal__title">The full library.</h3>
            <p className="modal__desc">Add what you want. Your provider reviews and finalizes every stack, confirms dosing, and can decline.</p>

            <div className="lib__filters">
              <select className="lib__sel" value={progFilter} onChange={(e) => setProgFilter(e.target.value)}>
                <option value="all">All programs</option>
                {PROGRAM_ORDER.map((k) => <option key={k} value={k}>{PROGRAMS[k].name}</option>)}
              </select>
              <select className="lib__sel" value={fmtFilter} onChange={(e) => setFmtFilter(e.target.value)}>
                <option value="all">All formats</option>
                <option value="needle_free">Needle-free</option>
                <option value="injectable">Injectable</option>
              </select>
            </div>

            <div className="lib__scroll">
              {PROGRAM_ORDER.filter((prog) => progFilter === "all" || progFilter === prog).map((prog) => {
                const items = (groups[prog] || []).filter(libVisible);
                if (!items.length) return null;
                return (
                  <div className="lib__group" key={prog}>
                    <div className="lib__grouphead">{PROGRAMS[prog].name}</div>
                    {items.map((p) => (
                      <ProductRow key={p.name + p.size} p={p} action={toggleStack} actionLabel="Add" selected={inStack(p)} />
                    ))}
                  </div>
                );
              })}
            </div>

            <div className="stackbar">
              <span className="stackbar__count">Your stack: {stack.length} {stack.length === 1 ? "product" : "products"}</span>
              <div className="modal__actions" style={{ margin: 0 }}>
                <button className="modal__back" onClick={() => setView("experience")}>← back</button>
                <button className="btn btn--primary" disabled={!stack.length} style={{ opacity: stack.length ? 1 : 0.45 }} onClick={() => stack.length && setView("intake")}>continue</button>
              </div>
            </div>
          </div>
        )}

        {view === "intake" && (
          <div>
            <span className="modal__eyebrow">Almost there</span>
            <h3 className="modal__title">Where do we send your review?</h3>
            <p className="modal__desc">A licensed provider reviews every intake. If a prescription is appropriate, they design your protocol.</p>
            <div className="field-row"><label>First name</label><input value={name} onChange={(e) => setName(e.target.value)} placeholder="Dana" /></div>
            <div className="field-row"><label>Email</label><input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" type="email" /></div>
            <div className="field-row"><label>Phone (optional)</label><input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="(808) 555-0100" type="tel" /></div>

            <label className="check-row"><input type="checkbox" checked={ageOk} onChange={(e) => setAgeOk(e.target.checked)} /><span>I am 18 years of age or older</span></label>
            <label className="check-row"><input type="checkbox" checked={inHawaii} onChange={(e) => setInHawaii(e.target.checked)} /><span>I'm located in Hawaii</span></label>
            <label className="check-row"><input type="checkbox" checked={pregnant} onChange={(e) => setPregnant(e.target.checked)} /><span>I am currently pregnant or nursing</span></label>

            {!inHawaii && <div className="notice">We're starting in Hawaii. Not there yet? Join the waitlist and we'll reach out when field arrives in your state.</div>}
            {pregnant && <div className="notice">Thanks for letting us know. Your provider will discuss the right options with you in review.</div>}

            <p className="modal__fine">Your provider reviews and finalizes every stack. Prescriptions are dispensed only if clinically appropriate, by a LegitScript-certified compounding pharmacy. A prescription is never guaranteed. This is not medical advice.</p>
            <div className="modal__actions">
              <button className="modal__back" onClick={() => setView(experience === "first_timer" ? "stack" : "library")}>← back</button>
              <button className="btn btn--primary" disabled={!canSubmit || saving} style={{ opacity: canSubmit && !saving ? 1 : 0.45 }}
                onClick={() => canSubmit && saveLead(inHawaii ? "joined" : "waitlist")}>
                {saving ? "saving…" : (inHawaii ? "submit intake" : "join the waitlist")}
              </button>
            </div>
          </div>
        )}

        {view === "confirm" && (
          <div className="confirm">
            <div className="confirm__seal"><Icon d={Icons.check} size={30} /></div>
            {outcome === "waitlist" ? (
              <React.Fragment>
                <h3 className="confirm__title">You're on the list{name ? `, ${name}` : ""}.</h3>
                <p className="confirm__body">We're starting in Hawaii and expanding from there. We'll reach out at {email || "your email"} as soon as field arrives in your state.</p>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <h3 className="confirm__title">You're in the field{name ? `, ${name}` : ""}.</h3>
                <p className="confirm__body">Your provider reviews and finalizes every stack. A licensed provider will review your intake and reach out at {email || "your email"} within one business day.</p>
                <div className="confirm__next">
                  <span>Next: provider review</span><span className="sep">·</span>
                  <span>invoice on approval</span><span className="sep">·</span>
                  <span>your protocol ships after payment</span>
                </div>
              </React.Fragment>
            )}
            <button className="btn btn--primary" onClick={close}>done</button>
          </div>
        )}
      </div>
    </div>
  );
}
Object.assign(window, { Consultant });
