/* TDEE Goal — components */

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

// ─── Logo ────────────────────────────────────────────────────────────────
function Logo() {
  return (
    <span className="brand-mark">
      tdee<span className="brand-mark-accent">goal</span><span className="brand-mark-tld">.com</span>
    </span>
  );
}

// ─── Nav ─────────────────────────────────────────────────────────────────
function ThemeToggle({ theme, onToggle }) {
  const dark = theme === "dark";
  return (
    <button
      className="nav-meta-btn nav-theme-btn"
      onClick={onToggle}
      title={dark ? "Switch to light mode" : "Switch to dark mode"}
      aria-label={dark ? "Switch to light mode" : "Switch to dark mode"}
    >
      {dark ? (
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
          <circle cx="8" cy="8" r="3.2" stroke="currentColor" strokeWidth="1.5"/>
          <path d="M8 1.5v1.5M8 13v1.5M1.5 8h1.5M13 8h1.5M3.3 3.3l1 1M11.7 11.7l1 1M3.3 12.7l1-1M11.7 4.3l1-1" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      ) : (
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
          <path d="M13.5 9.5A5.5 5.5 0 0 1 6.5 2.5a5.5 5.5 0 1 0 7 7Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
        </svg>
      )}
    </button>
  );
}

function Nav({ current, onNavigate, mobile, theme, onToggleTheme, onOpenHistory, historyCount }) {
  const links = [
    { id: "/", label: "TDEE" },
    { id: "/weight-loss/", label: "Calorie deficit" },
    { id: "/macros/", label: "Macro split" },
    { id: "/women/", label: "Women's TDEE" },
    { id: "/body-fat/", label: "Body fat %" },
  ];
  const [open, setOpen] = useState(false);

  return (
    <header className="nav">
      <div className="nav-inner">
        <button className="nav-logo" onClick={() => onNavigate("/")}>
          <Logo />
        </button>
        {!mobile && (
          <nav className="nav-links">
            {links.map(l => (
              <button
                key={l.id}
                className={"nav-link" + (current === l.id ? " is-active" : "")}
                onClick={() => onNavigate(l.id)}
              >
                {l.label}
              </button>
            ))}
          </nav>
        )}
        <div className="nav-right">
          <ThemeToggle theme={theme} onToggle={onToggleTheme} />
          {!mobile && (
            <button className="nav-meta-btn" onClick={onOpenHistory} title="History" aria-label="Show saved plans">
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                <circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.5"/>
                <path d="M8 5v3l2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
              <span>History{historyCount > 0 ? ` (${historyCount})` : ""}</span>
            </button>
          )}
          {mobile && (
            <button className="nav-meta-btn" onClick={() => setOpen(!open)}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d={open ? "M3 3l10 10M13 3L3 13" : "M2 4h12M2 8h12M2 12h12"} stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
            </button>
          )}
        </div>
      </div>
      {mobile && open && (
        <nav className="nav-mobile-panel">
          {links.map(l => (
            <button
              key={l.id}
              className={"nav-mobile-link" + (current === l.id ? " is-active" : "")}
              onClick={() => { onNavigate(l.id); setOpen(false); }}
            >
              {l.label}
              <span style={{ color: "var(--text-subtle)" }}>→</span>
            </button>
          ))}
          <button
            className="nav-mobile-link"
            onClick={() => { setOpen(false); onOpenHistory && onOpenHistory(); }}
          >
            History{historyCount > 0 ? ` (${historyCount})` : ""}
            <span style={{ color: "var(--text-subtle)" }}>→</span>
          </button>
        </nav>
      )}
    </header>
  );
}

// ─── Footer ──────────────────────────────────────────────────────────────
function Footer({ onNavigate }) {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-col footer-brand">
          <Logo />
          <p className="t-caption" style={{ marginTop: 12, maxWidth: 320 }}>
            From a number to a plan. Free TDEE calculator with goal-based outputs and full formula transparency.
          </p>
        </div>
        <div className="footer-col">
          <div className="t-label">Calculators</div>
          <button onClick={() => onNavigate("/")}>TDEE</button>
          <button onClick={() => onNavigate("/weight-loss/")}>Calorie deficit</button>
          <button onClick={() => onNavigate("/macros/")}>Macro split</button>
          <button onClick={() => onNavigate("/women/")}>Women's TDEE</button>
          <button onClick={() => onNavigate("/body-fat/")}>Body fat %</button>
        </div>
        <div className="footer-col">
          <div className="t-label">Site</div>
          <button onClick={() => onNavigate("/about/")}>About</button>
          <button onClick={() => onNavigate("/privacy/")}>Privacy</button>
          <button onClick={() => onNavigate("/disclaimer/")}>Disclaimer</button>
        </div>
      </div>
      <div className="footer-fineprint">
        <span className="t-micro">© 2026 TDEE Goal. Estimates are educational, not medical advice.</span>
        <span className="t-micro" style={{ color: "var(--text-subtle)" }}>v0.1 · static · no tracking</span>
      </div>
    </footer>
  );
}

// ─── Inputs ──────────────────────────────────────────────────────────────
function NumberInput({ label, value, onChange, suffix, min, max, hint, error, id }) {
  return (
    <label className="field" htmlFor={id}>
      <div className="field-row">
        <span className="t-label">{label}</span>
        {hint && <span className="t-micro" style={{ color: "var(--text-subtle)" }}>{hint}</span>}
      </div>
      <div className={"input-wrap mono" + (error ? " has-error" : "")}>
        <input
          id={id}
          type="number"
          inputMode="decimal"
          value={value ?? ""}
          min={min}
          max={max}
          onChange={(e) => {
            const v = e.target.value;
            onChange(v === "" ? null : Number(v));
          }}
        />
        {suffix && <span className="input-suffix mono">{suffix}</span>}
      </div>
      {error && <div className="t-micro" style={{ color: "var(--destructive)", marginTop: 4 }}>{error}</div>}
    </label>
  );
}

function SegControl({ value, onChange, options, ariaLabel }) {
  return (
    <div className="seg" role="tablist" aria-label={ariaLabel}>
      {options.map(o => (
        <button
          key={o.value}
          role="tab"
          aria-selected={value === o.value}
          className={"seg-btn" + (value === o.value ? " is-active" : "")}
          onClick={() => onChange(o.value)}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

function ActivitySlider({ value, onChange }) {
  const levels = ["sedentary", "light", "moderate", "active", "athlete"];
  const idx = levels.indexOf(value);
  const lev = window.TDEE.ACTIVITY_LEVELS[value];

  return (
    <div className="activity">
      <div className="activity-head">
        <div>
          <div className="t-label" style={{ marginBottom: 2 }}>Activity</div>
          <div style={{ fontSize: 15, fontWeight: 500 }}>{lev.label}</div>
        </div>
        <div className="mono activity-mult">×{lev.multiplier}</div>
      </div>
      <input
        type="range"
        min="0"
        max="4"
        step="1"
        value={idx}
        onChange={(e) => onChange(levels[Number(e.target.value)])}
        className="activity-slider"
      />
      <div className="activity-ticks">
        {levels.map((l, i) => (
          <button
            key={l}
            className={"activity-tick" + (i === idx ? " is-active" : "")}
            onClick={() => onChange(l)}
          >
            <span>{["Sed", "Light", "Mod", "Active", "Athl"][i]}</span>
          </button>
        ))}
      </div>
      <div className="t-caption" style={{ marginTop: 10, color: "var(--text-muted)" }}>
        {lev.help}
      </div>
    </div>
  );
}

// ─── Result display ──────────────────────────────────────────────────────
function ResultDisplay({ result, units }) {
  if (!result) {
    return (
      <div className="result-card empty">
        <div className="t-label">Your TDEE</div>
        <div className="result-big mono">—</div>
        <div className="t-caption">Fill in inputs to see results</div>
      </div>
    );
  }
  const bmrPct = (result.bmr / result.tdee) * 100;
  return (
    <div className="result-card">
      <div className="result-head">
        <div className="t-label">Your TDEE</div>
        <div className="result-formula mono">{formulaLabel(result.formula)}</div>
      </div>
      <div className="result-big mono">{result.tdee.toLocaleString()}</div>
      <div className="t-caption">calories per day</div>

      <div className="stack-bar" aria-hidden="true">
        <div className="stack-bar-bmr" style={{ width: bmrPct + "%" }}></div>
        <div className="stack-bar-act" style={{ width: (100 - bmrPct) + "%" }}></div>
      </div>
      <div className="stack-legend">
        <div className="stack-row">
          <span className="stack-dot stack-dot-bmr"></span>
          <span className="t-caption">BMR (resting burn)</span>
          <span className="mono stack-val">{result.bmr.toLocaleString()}</span>
        </div>
        <div className="stack-row">
          <span className="stack-dot stack-dot-act"></span>
          <span className="t-caption">Activity (×{result.multiplier})</span>
          <span className="mono stack-val">+{result.activityCalories.toLocaleString()}</span>
        </div>
      </div>
    </div>
  );
}

function formulaLabel(f) {
  return f === "mifflin" ? "Mifflin-St Jeor"
       : f === "katch-mcardle" ? "Katch-McArdle"
       : "Cunningham";
}

// ─── Goal cards ──────────────────────────────────────────────────────────
const GOALS = [
  { id: "cut", label: "Lose fat", desc: "Cut 0.5–2 lb/wk", glyph: "↘" },
  { id: "maintain", label: "Maintain", desc: "Keep current weight", glyph: "→" },
  { id: "recomp", label: "Recomp", desc: "Build muscle, lose fat", glyph: "⇄" },
  { id: "reverse", label: "Reverse", desc: "Increase after a cut", glyph: "↗" },
];

function GoalGrid({ value, onChange }) {
  return (
    <div className="goal-grid">
      {GOALS.map(g => (
        <button
          key={g.id}
          className={"goal-card" + (value === g.id ? " is-active" : "")}
          onClick={() => onChange(g.id)}
        >
          <span className="goal-glyph mono">{g.glyph}</span>
          <span className="goal-label">{g.label}</span>
          <span className="goal-desc t-micro">{g.desc}</span>
        </button>
      ))}
    </div>
  );
}

// ─── Plan timeline ───────────────────────────────────────────────────────
function PlanTimeline({ currentWeightLb, goalWeightLb, weeksToGoal, goalDate, weeklyLossLb }) {
  if (!weeksToGoal || weeksToGoal <= 0) return null;
  const checkpoints = 4;
  const points = [];
  for (let i = 0; i <= checkpoints; i++) {
    const w = Math.round((weeksToGoal / checkpoints) * i);
    const wt = currentWeightLb - weeklyLossLb * w;
    points.push({ week: w, weight: wt });
  }
  const fmtDate = (d) => d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  const today = new Date();
  return (
    <div className="timeline">
      <div className="t-label" style={{ marginBottom: 14 }}>Plan timeline</div>
      <div className="timeline-track">
        <div className="timeline-line"></div>
        <div className="timeline-line-fill"></div>
        {points.map((p, i) => {
          const d = new Date(today);
          d.setDate(d.getDate() + p.week * 7);
          const isFirst = i === 0;
          const isLast = i === points.length - 1;
          return (
            <div key={i} className={"timeline-pt" + (isLast ? " is-goal" : "") + (isFirst ? " is-start" : "")}>
              <div className="timeline-dot"></div>
              <div className="timeline-label">
                <div className="mono timeline-wt">{p.weight.toFixed(1)} lb</div>
                <div className="t-micro">{isFirst ? "Today" : isLast ? "Goal · " + fmtDate(d) : "Wk " + p.week}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Macro chart ─────────────────────────────────────────────────────────
function MacroChart({ macros, dailyCalories }) {
  if (!macros) return null;
  const total = macros.protein.calories + macros.carbs.calories + macros.fat.calories;
  const pP = (macros.protein.calories / total) * 100;
  const pC = (macros.carbs.calories / total) * 100;
  const pF = (macros.fat.calories / total) * 100;
  return (
    <div className="macro-chart">
      <div className="macro-bar" aria-hidden="true">
        <div className="macro-seg macro-protein" style={{ width: pP + "%" }}></div>
        <div className="macro-seg macro-carbs" style={{ width: pC + "%" }}></div>
        <div className="macro-seg macro-fat" style={{ width: pF + "%" }}></div>
      </div>
      <div className="macro-grid">
        <MacroCell color="protein" label="Protein" g={macros.protein.grams} cal={macros.protein.calories} pct={pP} />
        <MacroCell color="carbs" label="Carbs" g={macros.carbs.grams} cal={macros.carbs.calories} pct={pC} />
        <MacroCell color="fat" label="Fat" g={macros.fat.grams} cal={macros.fat.calories} pct={pF} />
      </div>
    </div>
  );
}

function MacroCell({ color, label, g, cal, pct }) {
  return (
    <div className={"macro-cell macro-cell-" + color}>
      <div className="macro-cell-head">
        <span className={"macro-dot macro-dot-" + color}></span>
        <span className="t-label">{label}</span>
        <span className="mono macro-pct">{pct.toFixed(0)}%</span>
      </div>
      <div className="macro-cell-g mono">{g}<span className="macro-unit">g</span></div>
      <div className="t-micro mono">{cal} cal</div>
    </div>
  );
}

// ─── Tag/chip ────────────────────────────────────────────────────────────
function Chip({ children, tone = "default" }) {
  return <span className={"chip chip-" + tone}>{children}</span>;
}

// ─── Disclaimer ──────────────────────────────────────────────────────────
function Disclaimer() {
  return (
    <div className="disclaimer">
      <span className="disclaimer-mark">!</span>
      <span className="t-micro">
        Estimates based on validated formulas. Individual metabolism varies ±10%. Not medical advice — consult a registered dietitian or doctor before significant calorie changes.
      </span>
    </div>
  );
}

// ─── History drawer ──────────────────────────────────────────────────────
function HistoryDrawer({ open, onClose, onNavigate }) {
  const [items, setItems] = useState(() => window.TDEE.loadHistory());

  useEffect(() => {
    const refresh = () => setItems(window.TDEE.loadHistory());
    window.addEventListener("tdee:history-changed", refresh);
    if (open) refresh();
    return () => window.removeEventListener("tdee:history-changed", refresh);
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;

  const onRestore = (item) => {
    const route = item.variant === "weight-loss" ? "/weight-loss/"
      : item.variant === "macros" ? "/macros/"
      : item.variant === "women" ? "/women/"
      : item.variant === "body-fat" ? "/body-fat/"
      : "/";
    onNavigate(route);
    setTimeout(() => {
      window.dispatchEvent(new CustomEvent("tdee:restore", { detail: { inputs: item.inputs, units: item.units } }));
      onClose();
    }, 50);
  };

  const onDelete = (e, id) => {
    e.stopPropagation();
    window.TDEE.deletePlan(id);
    setItems(window.TDEE.loadHistory());
    window.dispatchEvent(new CustomEvent("tdee:history-changed"));
  };

  const onClearAll = () => {
    if (!confirm("Clear all saved plans? This can't be undone.")) return;
    window.TDEE.clearHistory();
    setItems([]);
    window.dispatchEvent(new CustomEvent("tdee:history-changed"));
  };

  return (
    <div className="drawer-backdrop" onClick={onClose}>
      <aside className="drawer" onClick={(e) => e.stopPropagation()} role="dialog" aria-label="Saved plans">
        <header className="drawer-head">
          <div>
            <div className="t-label">Saved plans</div>
            <h2 className="t-h3" style={{ margin: "4px 0 0" }}>History {items.length > 0 && <span className="mono" style={{ color: "var(--text-subtle)" }}>({items.length})</span>}</h2>
          </div>
          <button className="drawer-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M3 3l10 10M13 3L3 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
          </button>
        </header>
        {items.length === 0 ? (
          <div className="drawer-empty">
            <p className="t-body" style={{ color: "var(--text-muted)", margin: 0 }}>
              No saved plans yet. Hit <strong>Save plan</strong> on any calculator to keep it here.
            </p>
          </div>
        ) : (
          <>
            <ul className="history-list">
              {items.map((it) => {
                const date = new Date(it.savedAt).toLocaleDateString(undefined, { month: "short", day: "numeric" });
                const time = new Date(it.savedAt).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
                const variantLabel = it.variant === "weight-loss" ? "Cut"
                  : it.variant === "macros" ? "Macros"
                  : it.variant === "women" ? "Women"
                  : it.variant === "body-fat" ? "Body fat"
                  : "TDEE";
                return (
                  <li key={it.id}>
                    <button className="history-item" onClick={() => onRestore(it)}>
                      <div className="history-item-head">
                        <span className="t-label">{variantLabel} · {it.goal}</span>
                        <span className="t-micro" style={{ color: "var(--text-subtle)" }}>{date} {time}</span>
                      </div>
                      <div className="history-item-row">
                        <span className="mono history-item-tdee">{it.tdee?.toLocaleString() ?? "—"}</span>
                        <span className="t-caption" style={{ color: "var(--text-muted)" }}>cal/day · {formulaLabel(it.formula)}</span>
                      </div>
                      <span
                        className="history-item-del"
                        role="button"
                        tabIndex={0}
                        aria-label="Delete"
                        onClick={(e) => onDelete(e, it.id)}
                        onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") onDelete(e, it.id); }}
                      >×</span>
                    </button>
                  </li>
                );
              })}
            </ul>
            <footer className="drawer-foot">
              <button className="btn btn-ghost" onClick={onClearAll}>Clear all</button>
            </footer>
          </>
        )}
      </aside>
    </div>
  );
}

Object.assign(window, {
  Logo, Nav, Footer, HistoryDrawer,
  NumberInput, SegControl, ActivitySlider,
  ResultDisplay, GoalGrid, PlanTimeline, MacroChart,
  Chip, Disclaimer, GOALS, formulaLabel,
});
