/* eslint-disable */
// ===========================================================================
// Omnivore UI — Settings (Coach + Goals)
//
// Part of the in-browser (no-build) React app. These files are loaded in order
// as separate <script type="text/babel"> tags (see index.html); Babel compiles
// each as a classic global script, so top-level names declared in earlier files
// are visible here. Depends on ui/base.jsx.
// ===========================================================================

// ── SETTINGS (Coach + Goals tabs) ────────────────────────────────────────────
// The old "Coach" screen is now one tab of a Settings panel. "Goals" shows the
// plan the coach has set (body stats, active goals, per-metric targets and
// priorities); "Coach" is the chat that actually changes them.
function SettingsView({ profile, onApply, toast }) {
  const [sub, setSub] = useState("coach");
  const segBtn = (id, label) => (
    <button key={id} onClick={() => setSub(id)}
      style={{ flex: 1, padding: "8px 0", fontSize: 14, cursor: "pointer", borderRadius: 9,
        border: "none", background: sub === id ? C.bg : "transparent",
        color: sub === id ? C.text : C.dim, fontWeight: sub === id ? 600 : 400,
        boxShadow: sub === id ? "0 1px 3px rgba(60,50,35,0.12)" : "none", transition: "all .15s" }}>
      {label}
    </button>
  );
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", gap: 14 }}>
      <div style={{ display: "flex", gap: 4, background: C.card, border: `1px solid ${C.line}`,
        borderRadius: 12, padding: 4, flexShrink: 0 }}>
        {segBtn("coach", "Coach")}
        {segBtn("goals", "Goals")}
      </div>
      {sub === "coach"
        ? <div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
            <CoachView profile={profile} onApply={onApply} toast={toast} />
          </div>
        : <div style={{ flex: 1, minHeight: 0, overflowY: "auto", overscrollBehavior: "contain" }}>
            <GoalsView profile={profile} onAdjust={() => setSub("coach")} />
          </div>}
    </div>
  );
}

// Read-only view of the current plan. Editing happens through the coach.
function GoalsView({ profile, onAdjust }) {
  const p = (window.OmniProfile ? window.OmniProfile.normalize : (x) => x)(profile);
  const targets = Metrics.resolveTargets(p);
  const stars = Metrics.resolveStars(p);

  const GOAL_LABELS = { nutrition: "General nutrition", weight_loss: "Weight loss", muscle_gain: "Muscle gain" };
  const SEX_LABELS = { male: "Male", female: "Female", unspecified: "Unspecified" };
  const fmtTarget = (m) => {
    const t = targets[m.id];
    const body = t && typeof t === "object" ? `${fmt(t.min)}–${fmt(t.max)}` : fmt(t);
    const dir = m.goalType === "below" ? "≤ " : m.goalType === "range" ? "" : "≥ ";
    return `${dir}${body} ${m.unit}`;
  };
  const starStr = (n) => "★".repeat(n) + "☆".repeat(Metrics.MAX_STARS - n);

  const stat = (label, value) => (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline",
      padding: "9px 4px", borderBottom: `1px solid ${C.line}` }}>
      <span style={{ fontSize: 14, color: C.dim }}>{label}</span>
      <span style={{ fontSize: 14, color: C.text }}>{value}</span>
    </div>
  );
  const heading = (t) => (
    <div style={{ fontSize: 12, color: C.faint, textTransform: "uppercase", letterSpacing: ".06em",
      margin: "18px 4px 4px" }}>{t}</div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", paddingBottom: 8 }}>
      <p style={{ fontSize: 13, color: C.dim, margin: "2px 4px 0", lineHeight: 1.5 }}>
        Your current plan. To change anything, ask the coach.
      </p>

      {heading("Goals")}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, padding: "4px" }}>
        {p.goals.map((g) => (
          <span key={g} style={{ ...pillBtn(true), cursor: "default" }}>{GOAL_LABELS[g] || g}</span>
        ))}
      </div>

      {heading("About you")}
      {stat("Age", `${p.age}`)}
      {stat("Height", `${p.heightCm} cm`)}
      {stat("Weight", `${p.weightKg} kg`)}
      {stat("Sex", SEX_LABELS[p.sex] || p.sex)}
      {p.dietaryPrefs && p.dietaryPrefs.length ? stat("Dietary", p.dietaryPrefs.join(", ")) : null}

      {heading("Daily targets & priority")}
      {Metrics.METRICS.map((m) => (
        <div key={m.id} style={{ display: "flex", alignItems: "baseline", gap: 10,
          padding: "10px 4px", borderBottom: `1px solid ${C.line}` }}>
          <span style={{ flex: 1, fontSize: 14, color: C.text }}>{m.label}</span>
          <span style={{ fontSize: 13, color: C.dim, whiteSpace: "nowrap" }}>{fmtTarget(m)}</span>
          <span title={`Priority ${stars[m.id]}/${Metrics.MAX_STARS}`}
            style={{ fontSize: 12, color: stars[m.id] ? C.watch : C.faint, whiteSpace: "nowrap", width: 58, textAlign: "right" }}>
            {starStr(stars[m.id])}
          </span>
        </div>
      ))}

      <button onClick={onAdjust}
        style={{ ...pillBtn(true), padding: "12px 0", borderRadius: 12, marginTop: 18 }}>
        Adjust with coach
      </button>
    </div>
  );
}

// ── COACH ────────────────────────────────────────────────────────────────────
function CoachView({ profile, onApply, toast }) {
  const [msgs, setMsgs] = useState(() => Store.getChat());
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const endRef = useRef(null);

  useEffect(() => {
    if (!msgs.length) {
      const greet = {
        role: "assistant",
        content:
          "Hi! I’m your nutrition coach — I set up everything here through chat. Tell me your goal (general nutrition, weight loss, muscle gain, or a mix) and your age, height, weight and sex, and I’ll set your targets and priorities. Ask me to tweak anything anytime.",
      };
      setMsgs([greet]); Store.setChat([greet]);
    }
  }, []);
  useEffect(() => { if (endRef.current) endRef.current.scrollIntoView({ block: "end" }); }, [msgs, busy]);

  async function send() {
    const text = input.trim();
    if (!text || busy) return;
    const next = [...msgs, { role: "user", content: text }];
    setMsgs(next); setInput(""); setBusy(true);
    const r = await Engine.coachChat({ profile, history: msgs, message: text });
    setBusy(false);
    const reply = { role: "assistant", content: r.ok ? r.reply : r.error || "Something went wrong." };
    const after = [...next, reply];
    setMsgs(after); Store.setChat(after);
    if (r.ok && r.updates && Object.keys(r.updates).length) { onApply(r.updates); toast("Plan updated ✓"); }
  }

  const bubble = (role) => ({
    alignSelf: role === "user" ? "flex-end" : "flex-start",
    background: role === "user" ? C.accent : C.card,
    color: role === "user" ? "#fff" : C.text,
    padding: "10px 13px", fontSize: 14, lineHeight: 1.5, maxWidth: "82%",
    borderRadius: role === "user" ? "14px 14px 4px 14px" : "14px 14px 14px 4px",
  });

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", gap: 12 }}>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 10, overflowY: "auto", minHeight: 0 }}>
        {msgs.map((m, i) => (
          <div key={i} style={bubble(m.role)}>
            {m.role === "assistant" ? <Markdown text={m.content} /> : m.content}
          </div>
        ))}
        {busy && <div style={{ alignSelf: "flex-start", color: C.faint, fontSize: 13 }}>Coach is thinking…</div>}
        <div ref={endRef} />
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        <input value={input} onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter") send(); }} placeholder="Message your coach…"
          style={{ ...inputStyle, borderRadius: 22, padding: "12px 16px" }} />
        <button onClick={send} disabled={busy}
          style={{ background: C.accent, border: "none", color: "#fff", borderRadius: 22, width: 44,
            fontSize: 16, cursor: "pointer", flexShrink: 0, opacity: busy ? 0.5 : 1 }}>↑</button>
      </div>
    </div>
  );
}
