const { useState, useEffect } = React;

// ── Theme definitions ──────────────────────────────────────────────────────────

const THEMES = {
  light: {
    bg:             "#ffffff",
    panelBg:        "#f8fafc",
    cardBg:         "#ffffff",
    border:         "#e2e8f0",
    textPrimary:    "#0f172a",
    textSecondary:  "#475569",
    textMuted:      "#94a3b8",
    inputBg:        "#f1f5f9",
    inputBorder:    "#e2e8f0",
    inputColor:     "#059669",
    primary:        "#059669",
    badgeBg:        "#d1fae5",
    badgeText:      "#059669",
    activeBg:       "#d1fae5",
    activeText:     "#059669",
    activeBorder:   "#059669",
    inactiveBorder: "#e2e8f0",
    inactiveText:   "#94a3b8",
    sliderTrack:    "#e2e8f0",
    sliderFill:     "linear-gradient(90deg,#065f46,#059669)",
    insightBg:      "#f8fafc",
    insightBorder:  "#e2e8f0",
    insightAccent:  "#059669",
    insightStrong:  "#0f172a",
    insightBody:    "#475569",
    insightHint:    "#94a3b8",
    disclaimer:     "#94a3b8",
    errorText:      "#dc2626",
    warningText:    "#b45309",
    warningBg:      "#fffbeb",
    toggleBg:       "#f1f5f9",
    toggleBorder:   "#e2e8f0",
    toggleText:     "#475569",
    hintText:       "#94a3b8",
    labelText:      "#475569",
    sectionLabel:   "#94a3b8",
  },
  dark: {
    bg:             "#0F172A",
    panelBg:        "#1E293B",
    cardBg:         "#1E293B",
    border:         "#334155",
    textPrimary:    "#f1f5f9",
    textSecondary:  "#94a3b8",
    textMuted:      "#94a3b8",
    inputBg:        "#0F172A",
    inputBorder:    "#334155",
    inputColor:     "#38BDF8",
    primary:        "#38BDF8",
    badgeBg:        "#0c4a6e",
    badgeText:      "#38BDF8",
    activeBg:       "#0c4a6e",
    activeText:     "#38BDF8",
    activeBorder:   "#38BDF8",
    inactiveBorder: "#334155",
    inactiveText:   "#475569",
    sliderTrack:    "#334155",
    sliderFill:     "linear-gradient(90deg,#0369a1,#38BDF8)",
    insightBg:      "#0F172A",
    insightBorder:  "#334155",
    insightAccent:  "#38BDF8",
    insightStrong:  "#f1f5f9",
    insightBody:    "#94a3b8",
    insightHint:    "#475569",
    disclaimer:     "#475569",
    errorText:      "#f87171",
    warningText:    "#fbbf24",
    warningBg:      "rgba(251,191,36,0.08)",
    toggleBg:       "#1E293B",
    toggleBorder:   "#334155",
    toggleText:     "#94a3b8",
    hintText:       "#94a3b8",
    labelText:      "#94a3b8",
    sectionLabel:   "#475569",
  }
};

// ── Unit helpers ───────────────────────────────────────────────────────────────

const kgToLbs  = kg  => Math.round(kg  * 2.20462);
const lbsToKg  = lbs => Math.round(lbs / 2.20462 * 10) / 10;
const cmToIn   = cm  => Math.round(cm  / 2.54);
const inToCm   = in_ => Math.round(in_ * 2.54);
const inToFtIn = in_ => `${Math.floor(in_ / 12)}'${in_ % 12}"`;

// ── Calculation functions ──────────────────────────────────────────────────────

function calcWHtR(waistCm, heightCm) {
  return waistCm / heightCm;
}

function classifyWHtR(whtr) {
  if (whtr < 0.4) return "very-lean";
  if (whtr < 0.5) return "low";
  if (whtr < 0.6) return "elevated";
  return "high";
}

function calcBRI(waistCm, heightCm) {
  const term = (waistCm / (2 * Math.PI)) / (0.5 * heightCm);
  if (term >= 1) return 364.2;
  return 364.2 - 365.5 * Math.sqrt(1 - term * term);
}

function calcConicity(waistCm, weightKg, heightCm) {
  const waistM  = waistCm  / 100;
  const heightM = heightCm / 100;
  return waistM / (0.109 * Math.sqrt(weightKg / heightM));
}

function calcBMI(weightKg, heightCm) {
  return weightKg / Math.pow(heightCm / 100, 2);
}

function classifyBRI(bri, sex) {
  return bri >= (sex === "female" ? 3.757 : 3.965) ? "elevated" : "low";
}

function classifyCI(ci, sex) {
  return ci >= (sex === "female" ? 1.285 : 1.344) ? "elevated" : "low";
}

function bmiCategory(bmi) {
  if (bmi < 18.5) return "Underweight";
  if (bmi < 25)   return "Normal";
  if (bmi < 30)   return "Overweight";
  return "Obese";
}

// ── Slider ─────────────────────────────────────────────────────────────────────

function Slider({ label, value, min, max, step = 1, unit = "", onChange, hint, warning, theme: t }) {
  const [inputVal, setInputVal] = useState(String(value));

  useEffect(() => { setInputVal(String(value)); }, [value]);

  const handleInputChange = (e) => {
    setInputVal(e.target.value);
    const n = Number(e.target.value);
    if (!isNaN(n) && n >= min && n <= max) onChange(n);
  };

  const handleBlur = () => {
    const n = Number(inputVal);
    if (isNaN(n)) {
      setInputVal(String(value));
    } else {
      const clamped = Math.max(min, Math.min(max, n));
      onChange(clamped);
      setInputVal(String(clamped));
    }
  };

  const pct       = ((value - min) / (max - min)) * 100;
  const unitLabel = unit.trim();

  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
        <span style={{ fontSize: 13, color: t.labelText, fontFamily: "'DM Sans', sans-serif" }}>
          {label}
        </span>
        <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
          <input
            type="number"
            value={inputVal}
            min={min} max={max} step={step}
            onChange={handleInputChange}
            onBlur={handleBlur}
            style={{
              width: 62, padding: "3px 6px", borderRadius: 6,
              border: `1px solid ${t.inputBorder}`,
              background: t.inputBg, color: t.inputColor,
              fontSize: 13, fontWeight: 600,
              fontFamily: "monospace", textAlign: "right", outline: "none",
              WebkitAppearance: "none", MozAppearance: "textfield"
            }}
          />
          {unitLabel && (
            <span style={{ fontSize: 12, color: t.textMuted, minWidth: 20 }}>{unitLabel}</span>
          )}
        </div>
      </div>

      <div style={{ position: "relative", height: 6, background: t.sliderTrack, borderRadius: 3 }}>
        <div style={{
          position: "absolute", left: 0, width: `${pct}%`,
          height: "100%", background: t.sliderFill,
          borderRadius: 3, pointerEvents: "none"
        }} />
        <input
          type="range" min={min} max={max} step={step} value={value}
          onChange={e => onChange(Number(e.target.value))}
          style={{
            position: "absolute", top: -5, left: 0,
            width: "100%", height: 16,
            opacity: 0, cursor: "pointer", zIndex: 2
          }}
        />
      </div>

      {hint && (
        <p style={{ fontSize: 13, color: t.hintText, margin: "4px 0 0", fontFamily: "'DM Sans', sans-serif" }}>
          {hint}
        </p>
      )}
      {warning && (
        <div style={{
          marginTop: 8, padding: "8px 10px", borderRadius: 6,
          background: t.warningBg, border: `1px solid ${t.warningText}44`,
          fontSize: 12, color: t.warningText, lineHeight: 1.6,
          fontFamily: "'DM Sans', sans-serif"
        }}>
          ⚠ {warning}
        </div>
      )}
    </div>
  );
}

// ── Risk Gauge ─────────────────────────────────────────────────────────────────

function RiskGauge({ whtr, heightCm, isImperial, theme: t }) {
  const zone = classifyWHtR(whtr);
  const pct  = Math.min(100, (whtr / 0.8) * 100);

  const zoneInfo = {
    "very-lean": { label: "Very Lean",     bg: t.inputBg,               text: t.textSecondary },
    "low":       { label: "Low Risk",      bg: t.activeBg,              text: t.primary },
    "elevated":  { label: "Elevated Risk", bg: t.warningBg,             text: t.warningText },
    "high":      { label: "High Risk",     bg: "rgba(239,68,68,0.12)",  text: t.errorText },
  };

  const info    = zoneInfo[zone];
  const ceilCm  = Math.round(0.5 * heightCm);
  const ceilIn  = cmToIn(0.5 * heightCm);

  return (
    <div style={{
      background: t.cardBg, border: `1px solid ${t.border}`,
      borderRadius: 12, padding: "20px 20px 16px", marginBottom: 16
    }}>
      {/* WHtR value + risk badge */}
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
        <div>
          <div style={{
            fontSize: 11, color: t.textMuted,
            textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 2
          }}>WHtR</div>
          <div style={{
            fontSize: 38, fontWeight: 700,
            fontFamily: "'DM Mono', monospace", color: t.textPrimary, lineHeight: 1
          }}>
            {whtr.toFixed(3)}
          </div>
        </div>
        <div style={{
          padding: "6px 16px", borderRadius: 20,
          background: info.bg, color: info.text,
          fontSize: 13, fontWeight: 700, letterSpacing: "0.05em",
          textTransform: "uppercase"
        }}>
          {info.label}
        </div>
      </div>

      {/* Gauge bar */}
      <div style={{ position: "relative", marginBottom: 4 }}>
        {/* Pointer circle */}
        <div style={{
          position: "absolute",
          left: `${pct}%`,
          top: "50%",
          transform: "translate(-50%, -50%)",
          width: 14, height: 14, borderRadius: "50%",
          background: t.textPrimary,
          border: `2px solid ${t.bg}`,
          zIndex: 2
        }} />
        {/* Coloured segments */}
        <div style={{ display: "flex", height: 10, borderRadius: 5, overflow: "hidden" }}>
          <div style={{ width: "62.5%", background: "#10b981" }} />
          <div style={{ width: "12.5%", background: "#f59e0b" }} />
          <div style={{ width: "25%",   background: "#ef4444" }} />
        </div>
      </div>

      {/* Zone labels */}
      <div style={{ display: "flex", fontSize: 11, color: t.textMuted, marginBottom: 14 }}>
        <div style={{ width: "62.5%", textAlign: "left" }}>Low (&lt;0.5)</div>
        <div style={{ width: "12.5%", textAlign: "center", whiteSpace: "nowrap" }}>Elevated</div>
        <div style={{ width: "25%",   textAlign: "right" }}>High (≥0.6)</div>
      </div>

      {/* Healthy waist ceiling */}
      <div style={{ fontSize: 13, color: t.textMuted }}>
        Healthy waist ceiling:{" "}
        <strong style={{ color: t.textSecondary }}>
          {isImperial ? `${ceilIn} in` : `${ceilCm} cm`}
        </strong>
        {isImperial
          ? <span> ({ceilCm} cm)</span>
          : <span> ({ceilIn} in)</span>
        }
      </div>
    </div>
  );
}

// ── Metric Card ────────────────────────────────────────────────────────────────

function MetricCard({ label, score, unit, riskLevel, riskLabel, description, theme: t }) {
  const riskColors = {
    "very-lean": { bg: t.inputBg,              text: t.textSecondary },
    "low":       { bg: t.activeBg,             text: t.primary },
    "elevated":  { bg: t.warningBg,            text: t.warningText },
    "high":      { bg: "rgba(239,68,68,0.12)", text: t.errorText },
    "reference": { bg: t.inputBg,              text: t.textSecondary },
  };
  const colors = riskColors[riskLevel] || riskColors.reference;

  return (
    <div style={{
      flex: 1, minWidth: 0,
      background: t.cardBg, border: `1px solid ${t.border}`,
      borderRadius: 10, padding: "14px 14px 12px"
    }}>
      <div style={{
        fontSize: 11, color: t.textMuted,
        textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 5
      }}>{label}</div>
      <div style={{
        fontSize: 22, fontWeight: 700,
        fontFamily: "'DM Mono', monospace", color: t.textPrimary, marginBottom: 6, lineHeight: 1.1
      }}>
        {score}
        {unit && <span style={{ fontSize: 12, color: t.textMuted, marginLeft: 3 }}>{unit}</span>}
      </div>
      <div style={{
        display: "inline-block", padding: "3px 10px", borderRadius: 20,
        background: colors.bg, color: colors.text,
        fontSize: 11, fontWeight: 600, marginBottom: 8
      }}>
        {riskLabel}
      </div>
      <div style={{ fontSize: 12, color: t.textSecondary, lineHeight: 1.55 }}>
        {description}
      </div>
    </div>
  );
}

// ── App ────────────────────────────────────────────────────────────────────────

function parseUrlParams() {
  try {
    const p      = new URLSearchParams(window.location.search);
    const sex    = ["female", "male"].includes(p.get("sex")) ? p.get("sex") : null;
    const height = parseInt(p.get("height"), 10);
    const weight = parseInt(p.get("weight"), 10);
    const waist  = parseInt(p.get("waist"),  10);
    return {
      sex,
      height: height >= 140 && height <= 220 ? height : null,
      weight: weight >= 40  && weight <= 250 ? weight : null,
      waist:  waist  >= 50  && waist  <= 180 ? waist  : null,
    };
  } catch (e) {
    return { sex: null, height: null, weight: null, waist: null };
  }
}

function App() {
  const urlP     = parseUrlParams();
  const fromUrl  = !!(urlP.sex || urlP.height || urlP.weight);

  const [isDark,     setIsDark]     = useState(false);
  const [isImperial, setIsImperial] = useState(false);
  const [sex,        setSex]        = useState(urlP.sex    || "female");
  const [height,     setHeight]     = useState(urlP.height || 168);  // cm
  const [weight,     setWeight]     = useState(urlP.weight || 75);   // kg
  const [waist,      setWaist]      = useState(urlP.waist  || 88);   // cm

  const t = THEMES[isDark ? "dark" : "light"];

  // ── Derived calculations ───────────────────────────────────────────────────
  const whtr     = calcWHtR(waist, height);
  const bri      = calcBRI(waist, height);
  const ci       = calcConicity(waist, weight, height);
  const bmi      = calcBMI(weight, height);
  const whtrZone = classifyWHtR(whtr);
  const briZone  = classifyBRI(bri, sex);
  const ciZone   = classifyCI(ci, sex);

  // ── Imperial display values ────────────────────────────────────────────────
  const dispHeight = isImperial ? cmToIn(height) : height;
  const dispWeight = isImperial ? kgToLbs(weight) : weight;
  const dispWaist  = isImperial ? cmToIn(waist)  : waist;
  const hUnit      = isImperial ? " in"  : " cm";
  const wUnit      = isImperial ? " lbs" : " kg";

  // ── Warnings ───────────────────────────────────────────────────────────────
  const waistWarning = waist >= 150
    ? "This is an unusually large measurement. Please double-check."
    : null;
  const bmiWarning = bmi < 18.5
    ? "Your BMI suggests underweight. These indices are less reliable at very low body weights."
    : null;

  // ── Interpretation text ────────────────────────────────────────────────────
  const interpretations = {
    "very-lean": "Your WHtR is below 0.4 — in the very lean range. While low central adiposity is generally positive, very low body fat can carry its own health risks. Ensure adequate nutrition and consider speaking with a healthcare provider.",
    "low":       "Your waist is well within the healthy range. Research covering over 300,000 people finds a WHtR below 0.5 is associated with significantly lower cardiometabolic risk. Maintain regular physical activity and a balanced diet to stay here.",
    "elevated":  "Research in 300,000+ people shows a WHtR between 0.5 and 0.6 is linked to elevated cardiometabolic risk. The public health message: keep your waist to less than half your height. Increasing aerobic exercise and reducing refined carbohydrates can help reduce visceral fat.",
    "high":      "A WHtR above 0.6 is associated with substantially elevated insulin resistance risk. This level of central adiposity is strongly linked to metabolic syndrome, type 2 diabetes, and cardiovascular disease. Consult a healthcare professional about targeted interventions.",
  };

  return (
    <div style={{
      background: t.bg, minHeight: "100vh",
      color: t.textPrimary, fontFamily: "'DM Sans', sans-serif",
      padding: "0 0 60px"
    }}>
      <style>{`
        body { background: ${t.bg}; }
        input[type=number]::-webkit-inner-spin-button,
        input[type=number]::-webkit-outer-spin-button { opacity: 0.4; }
        @media (max-width: 767px) {
          .irr-layout   { flex-direction: column !important; }
          .irr-sidebar  { width: 100% !important; border-right: none !important; border-bottom: 1px solid ${t.border} !important; }
          .irr-badge    { display: none !important; }
          input[type=range] { height: 44px !important; top: -19px !important; }
          .irr-sex-toggle button { padding-top: 12px !important; padding-bottom: 12px !important; font-size: 15px !important; }
          .irr-sidebar span              { font-size: 15px !important; }
          .irr-sidebar p                 { font-size: 14px !important; }
          .irr-sidebar input[type=number] { font-size: 15px !important; width: 70px !important; }
          .irr-mode-toggle { padding-top: 10px !important; padding-bottom: 10px !important; }
          .irr-seo { padding-top: 32px !important; }
          .irr-nav-links { display: none !important; }
        }
      `}</style>

      {/* ── Header / Nav ── */}
      <div style={{ borderBottom: `1px solid ${t.border}`, background: t.panelBg }}>
        <div style={{ display: "flex", alignItems: "center", height: 52, padding: "0 24px", gap: 24 }}>
          <a href="./" style={{
            fontSize: 16, fontWeight: 700, color: t.primary,
            textDecoration: "none", letterSpacing: "-0.01em"
          }}>InResRisk</a>

          <div className="irr-nav-links" style={{ display: "flex", gap: 24 }}>
            <a href="./" style={{
              fontSize: 14, color: t.primary, fontWeight: 500, textDecoration: "none"
            }}>IR Risk Calculator</a>
            <a href="about" style={{ fontSize: 14, color: t.textSecondary, textDecoration: "none" }}
              onMouseOver={e => e.target.style.color = t.primary}
              onMouseOut={e => e.target.style.color = t.textSecondary}
            >About</a>
            <a href="privacy" style={{ fontSize: 14, color: t.textSecondary, textDecoration: "none" }}
              onMouseOver={e => e.target.style.color = t.primary}
              onMouseOut={e => e.target.style.color = t.textSecondary}
            >Privacy</a>
          </div>

          <div style={{ flex: 1 }} />

          <button
            onClick={() => setIsDark(d => !d)}
            className="irr-mode-toggle"
            style={{
              padding: "5px 14px", borderRadius: 20, cursor: "pointer",
              border: `1px solid ${t.toggleBorder}`,
              background: t.toggleBg, color: t.toggleText,
              fontSize: 12, fontFamily: "'DM Sans', sans-serif",
              fontWeight: 500, display: "flex", alignItems: "center", gap: 6
            }}
          >
            <span style={{
              display: "inline-block", width: 10, height: 10, borderRadius: "50%",
              background: isDark ? "#38BDF8" : "#059669",
              boxShadow: isDark ? "0 0 6px #38BDF8" : "0 0 6px #059669"
            }} />
            {isDark ? "Light mode" : "Dark mode"}
          </button>
        </div>
      </div>

      {/* ── Two-column layout ── */}
      <div style={{ display: "flex", flexWrap: "wrap" }} className="irr-layout">

        {/* ── Left: inputs ── */}
        <div className="irr-sidebar" style={{
          width: 284, flexShrink: 0,
          padding: "22px 20px",
          borderRight: `1px solid ${t.border}`,
          background: t.panelBg
        }}>
          {/* Header row */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
            <p style={{ fontSize: 11, color: t.sectionLabel, textTransform: "uppercase", letterSpacing: "0.07em", margin: 0 }}>
              Your measurements
            </p>
            <div style={{ display: "flex", gap: 2 }}>
              {[["kg/cm", false], ["lbs/in", true]].map(([lbl, imp]) => (
                <button key={lbl} onClick={() => setIsImperial(imp)} style={{
                  padding: "3px 9px", borderRadius: 4, cursor: "pointer",
                  border: `1px solid ${isImperial === imp ? t.activeBorder : t.inactiveBorder}`,
                  background: isImperial === imp ? t.activeBg : "transparent",
                  color: isImperial === imp ? t.activeText : t.inactiveText,
                  fontSize: 11, fontFamily: "'DM Sans', sans-serif", fontWeight: 500
                }}>{lbl}</button>
              ))}
            </div>
          </div>

          {/* Sex toggle */}
          <div style={{ marginBottom: 20 }}>
            <p style={{ fontSize: 13, color: t.labelText, marginBottom: 8 }}>Sex</p>
            <div style={{ display: "flex", gap: 8 }} className="irr-sex-toggle">
              {["female", "male"].map(s => (
                <button key={s} onClick={() => setSex(s)} style={{
                  flex: 1, padding: "8px 0", borderRadius: 6, cursor: "pointer",
                  border: `1px solid ${sex === s ? t.activeBorder : t.inactiveBorder}`,
                  background: sex === s ? t.activeBg : "transparent",
                  color: sex === s ? t.activeText : t.inactiveText,
                  fontSize: 13, fontFamily: "'DM Sans', sans-serif",
                  fontWeight: sex === s ? 600 : 400
                }}>
                  {s.charAt(0).toUpperCase() + s.slice(1)}
                </button>
              ))}
            </div>
          </div>

          <Slider
            label="Height"
            value={dispHeight}
            min={isImperial ? 55 : 140}
            max={isImperial ? 87 : 220}
            unit={hUnit}
            hint={isImperial ? inToFtIn(dispHeight) : undefined}
            onChange={v => setHeight(isImperial ? inToCm(v) : v)}
            theme={t}
          />

          <Slider
            label="Weight"
            value={dispWeight}
            min={isImperial ? 88 : 40}
            max={isImperial ? 551 : 250}
            unit={wUnit}
            warning={bmiWarning}
            onChange={v => setWeight(isImperial ? lbsToKg(v) : v)}
            theme={t}
          />

          <Slider
            label="Waist circumference"
            value={dispWaist}
            min={isImperial ? 20 : 50}
            max={isImperial ? 71 : 180}
            unit={isImperial ? " in" : " cm"}
            warning={waistWarning}
            onChange={v => setWaist(isImperial ? inToCm(v) : v)}
            theme={t}
          />
        </div>

        {/* ── Right: results ── */}
        <div style={{ flex: 1, minWidth: 0, padding: "22px 20px", background: t.bg }}>

          <RiskGauge whtr={whtr} heightCm={height} isImperial={isImperial} theme={t} />

          {/* Metric cards */}
          <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
            <MetricCard
              label="BRI"
              score={bri.toFixed(2)}
              riskLevel={briZone}
              riskLabel={briZone === "elevated" ? "⚠ Elevated" : "✓ OK"}
              description="Body Roundness Index"
              theme={t}
            />
            <MetricCard
              label="Conicity Index"
              score={ci.toFixed(2)}
              riskLevel={ciZone}
              riskLabel={ciZone === "elevated" ? "⚠ Elevated" : "✓ OK"}
              description="Shape index"
              theme={t}
            />
            <MetricCard
              label="BMI"
              score={bmi.toFixed(1)}
              riskLevel="reference"
              riskLabel={bmiCategory(bmi)}
              description="Reference only"
              theme={t}
            />
          </div>

          {/* Interpretation box */}
          <div style={{
            background: t.insightBg, border: `1px solid ${t.insightBorder}`,
            borderRadius: 10, padding: "14px 16px", marginBottom: 14
          }}>
            <p style={{ fontSize: 13, color: t.insightBody, margin: 0, lineHeight: 1.8 }}>
              <span style={{ color: t.insightAccent, fontWeight: 600 }}>What this means: </span>
              {interpretations[whtrZone]}
            </p>
          </div>

          {/* Disclaimer */}
          <p style={{ fontSize: 12, color: t.disclaimer, lineHeight: 1.6, marginBottom: 14 }}>
            This tool uses published anthropometric indices validated in population studies.
            It is not a clinical diagnosis. Consult a healthcare professional for personalised advice.
          </p>

          {/* Coffee link + cross-app link */}
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            <a
              href="https://buymeacoffee.com/Wolfy82"
              target="_blank"
              rel="noopener noreferrer"
              style={{
                fontSize: 12, color: t.textMuted, textDecoration: "none",
                padding: "5px 12px", borderRadius: 6, border: `1px solid ${t.border}`,
                display: "flex", alignItems: "center", gap: 5
              }}
            >☕ Buy me a coffee</a>
            <a
              href={`https://honestslim.com/?sex=${sex}&height=${height}&weight=${weight}`}
              style={{
                fontSize: 12, color: t.textMuted, textDecoration: "none",
                padding: "5px 12px", borderRadius: 6, border: `1px solid ${t.border}`,
                display: "flex", alignItems: "center", gap: 5
              }}
            >→ Plan your weight loss on HonestSlim</a>
          </div>
        </div>
      </div>

      {/* ── SEO section ── */}
      <div className="irr-seo" style={{ maxWidth: 760, margin: "0 auto", padding: "56px 24px 0" }}>

        <h1 style={{
          fontSize: 26, fontWeight: 700, color: t.textPrimary,
          letterSpacing: "-0.02em", marginBottom: 10, lineHeight: 1.3
        }}>
          Insulin Resistance Risk Calculator
        </h1>
        <p style={{ fontSize: 15, color: t.textSecondary, marginBottom: 44, lineHeight: 1.75 }}>
          Most people wait for a blood test to find out about insulin resistance — but research shows your
          waist-to-height ratio predicts risk just as well for population screening. InResRisk calculates
          your WHtR and two supporting indices from measurements you can take at home.
        </p>

        <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 18, letterSpacing: "-0.01em" }}>
          How your scores are calculated
        </h2>

        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.85, marginBottom: 18 }}>
          The primary score is <strong style={{ color: t.textPrimary }}>WHtR (Waist-to-Height Ratio)</strong> — simply your
          waist circumference divided by your height, both in the same unit. A landmark 2010 systematic review by Browning,
          Hsieh and Ashwell analysed 31 studies covering around 300,000 subjects and found WHtR outperformed BMI for
          predicting cardiometabolic disease (AUC 0.704 vs 0.671).<sup style={{ fontSize: 10, color: t.primary, fontWeight: 600 }}> [1]</sup>{" "}
          The threshold of 0.5 — keep your waist to less than half your height — was validated by Ashwell in 2014
          using actuarial data, establishing 0.4, 0.5, and 0.6 as the three meaningful boundary values.<sup style={{ fontSize: 10, color: t.primary, fontWeight: 600 }}> [2]</sup>
        </p>

        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.85, marginBottom: 18 }}>
          The <strong style={{ color: t.textPrimary }}>BRI (Body Roundness Index)</strong> adds a geometric refinement,
          modelling the torso as an ellipse. Sex-specific cutoffs validated in Brazilian adults are BRI ≥ 3.757
          for women and ≥ 3.965 for men, identifying metabolic syndrome with AUCs of 0.833 and 0.906
          respectively.<sup style={{ fontSize: 10, color: t.primary, fontWeight: 600 }}> [3]</sup>{" "}
          A 2024 analysis in <em>Metabolism</em> further confirmed BRI slightly outperforms WHtR for insulin
          sensitivity correlation in middle-aged cohorts.<sup style={{ fontSize: 10, color: t.primary, fontWeight: 600 }}> [4]</sup>{" "}
          Both metrics use only waist circumference and height — no additional inputs required.
        </p>

        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.85, marginBottom: 44 }}>
          The <strong style={{ color: t.textPrimary }}>Conicity Index (CI)</strong> adds weight to the equation,
          modelling the body as a double cone to capture the "apple shape" more precisely. Originally derived
          by Valdez (1991),<sup style={{ fontSize: 10, color: t.primary, fontWeight: 600 }}> [5]</sup>{" "}
          sex-specific cutoffs (women ≥ 1.285, men ≥ 1.344) have since been validated in large adult populations.
          CI is primarily a cardiovascular risk marker shown as supporting context alongside WHtR and BRI.
        </p>

        <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 18, letterSpacing: "-0.01em" }}>
          Why waist-to-height ratio beats BMI
        </h2>

        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.85, marginBottom: 18 }}>
          BMI tells you how heavy you are relative to your height — but says nothing about <em>where</em> that weight
          is stored. Two people with the same BMI can have radically different fat distributions, and where fat sits
          changes everything for metabolic health. Visceral fat — packed around the abdominal organs — releases free
          fatty acids and inflammatory cytokines directly into the portal circulation, driving hepatic insulin resistance
          and systemic metabolic dysfunction.
        </p>

        <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.85, marginBottom: 44 }}>
          WHtR directly captures central adiposity. A large waist relative to height is a proxy for visceral fat
          accumulation — something BMI cannot detect. This is why someone can be "normal" BMI but carry dangerous
          visceral fat (a pattern known as normal-weight obesity), and why people with high BMI but proportionally
          small waists may have better metabolic profiles than expected. A 2021 study in <em>Scientific Reports</em>{" "}
          found WHtR combined with sex predicted insulin resistance (Matsuda index) with AUC 0.765 in non-diabetic
          adults — substantially outperforming BMI alone.<sup style={{ fontSize: 10, color: t.primary, fontWeight: 600 }}> [6]</sup>
        </p>

        <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 28, letterSpacing: "-0.01em" }}>
          Frequently asked questions
        </h2>

        {[
          {
            q: "What is a healthy waist-to-height ratio?",
            a: "A WHtR below 0.5 is considered healthy for most adults — your waist circumference should be less than half your height. Ashwell's 2014 actuarial validation [2] established three boundaries: below 0.4 is very lean, 0.4–0.5 is the healthy range, 0.5–0.6 is elevated risk, and 0.6 or above is high risk. The simple message: keep your waist to less than half your height."
          },
          {
            q: "Is WHtR the same as waist-to-hip ratio?",
            a: "No. Waist-to-hip ratio (WHR) compares waist to hip circumference and requires measuring both. WHtR only needs waist and height — measurements most people already know. Research [1] suggests WHtR is at least as good a predictor of cardiometabolic risk as WHR, and simpler to use. WHtR also has a universal 0.5 threshold that doesn't vary by sex, unlike WHR."
          },
          {
            q: "How is central fat linked to insulin resistance?",
            a: "Visceral fat releases free fatty acids and pro-inflammatory cytokines directly into the portal circulation, triggering hepatic insulin resistance. This leads to elevated fasting glucose and, over time, reduced insulin sensitivity throughout the body. Subcutaneous fat is far less metabolically active. Because WHtR is a proxy for central adiposity, it captures this visceral fat signal in a way weight or BMI alone cannot [6]."
          },
          {
            q: "Can I use this instead of a blood test?",
            a: "No — this tool screens, it does not diagnose. A fasting blood test measuring insulin and glucose (HOMA-IR) or an oral glucose tolerance test (Matsuda index) is required for a clinical diagnosis of insulin resistance. What WHtR and the supporting indices can do is identify people at elevated risk who should prioritise getting a clinical assessment. A normal result does not rule out insulin resistance, especially in lean individuals with significant metabolic dysfunction."
          },
        ].map(({ q, a }) => (
          <div key={q} style={{ padding: "20px 0", borderTop: `1px solid ${t.border}` }}>
            <h3 style={{
              fontSize: 15, fontWeight: 600, color: t.textPrimary,
              marginBottom: 10, lineHeight: 1.45
            }}>{q}</h3>
            <p style={{ fontSize: 15, color: t.textSecondary, lineHeight: 1.85, margin: 0 }}>{a}</p>
          </div>
        ))}

        {/* Thresholds at a glance */}
        <div style={{ borderTop: `1px solid ${t.border}`, paddingTop: 28, marginBottom: 0 }}>
          <h2 style={{ fontSize: 19, fontWeight: 700, color: t.textPrimary, marginBottom: 20, letterSpacing: "-0.01em" }}>
            Risk thresholds at a glance
          </h2>

          <p style={{ fontSize: 12, color: t.textMuted, marginBottom: 8 }}>WHtR — sex-universal</p>
          <div style={{ overflowX: "auto", marginBottom: 24 }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <thead>
                <tr>
                  {["Range", "Zone", "Risk interpretation"].map(h => (
                    <th key={h} style={{
                      background: t.panelBg, color: t.textMuted,
                      fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em",
                      padding: "8px 12px", border: `1px solid ${t.border}`,
                      textAlign: "left", fontWeight: 600
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {[
                  { range: "< 0.40",      zone: "Very lean", risk: "Very low central fat; extremely low body fat carries its own risks", rowBg: t.inputBg,               cellText: t.textSecondary },
                  { range: "0.40 – 0.49", zone: "Healthy",   risk: "Low risk — the target range for most adults",                       rowBg: t.activeBg,              cellText: t.activeText },
                  { range: "0.50 – 0.59", zone: "Elevated",  risk: "Elevated cardiometabolic and insulin resistance risk",              rowBg: t.warningBg,             cellText: t.warningText },
                  { range: "≥ 0.60",      zone: "High",      risk: "Strongly associated with metabolic syndrome and T2DM",             rowBg: "rgba(239,68,68,0.08)", cellText: t.errorText },
                ].map(row => (
                  <tr key={row.range} style={{ background: row.rowBg }}>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, color: row.cellText, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.range}</td>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, color: row.cellText, fontWeight: 600 }}>{row.zone}</td>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, color: t.textSecondary }}>{row.risk}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <p style={{ fontSize: 12, color: t.textMuted, marginBottom: 8 }}>
            BRI & CI — sex-specific cutoffs
            <sup style={{ fontSize: 10, color: t.primary, fontWeight: 600 }}> [3][5]</sup>
          </p>
          <div style={{ overflowX: "auto", marginBottom: 24 }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <thead>
                <tr>
                  {["Index", "Women — Normal", "Women — Elevated", "Men — Normal", "Men — Elevated"].map(h => (
                    <th key={h} style={{
                      background: t.panelBg, color: t.textMuted,
                      fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em",
                      padding: "8px 12px", border: `1px solid ${t.border}`,
                      textAlign: "left", fontWeight: 600
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {[
                  { index: "BRI", fNorm: "< 3.757", fElev: "≥ 3.757 (AUC 0.833)", mNorm: "< 3.965", mElev: "≥ 3.965 (AUC 0.906)" },
                  { index: "CI",  fNorm: "< 1.285", fElev: "≥ 1.285",              mNorm: "< 1.344", mElev: "≥ 1.344" },
                ].map(row => (
                  <tr key={row.index} style={{ background: t.cardBg }}>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, color: t.textPrimary, fontWeight: 600 }}>{row.index}</td>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, background: t.activeBg, color: t.activeText, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.fNorm}</td>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, background: t.warningBg, color: t.warningText, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.fElev}</td>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, background: t.activeBg, color: t.activeText, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.mNorm}</td>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, background: t.warningBg, color: t.warningText, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.mElev}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <p style={{ fontSize: 12, color: t.textMuted, marginBottom: 8 }}>BMI — reference only (WHO standard, sex-universal)</p>
          <div style={{ overflowX: "auto", marginBottom: 32 }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <thead>
                <tr>
                  {["BMI range", "Category"].map(h => (
                    <th key={h} style={{
                      background: t.panelBg, color: t.textMuted,
                      fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em",
                      padding: "8px 12px", border: `1px solid ${t.border}`,
                      textAlign: "left", fontWeight: 600
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {[
                  { range: "< 18.5",      cat: "Underweight", rowBg: t.inputBg,                cellText: t.textSecondary },
                  { range: "18.5 – 24.9", cat: "Normal",      rowBg: t.activeBg,               cellText: t.activeText },
                  { range: "25.0 – 29.9", cat: "Overweight",  rowBg: t.warningBg,              cellText: t.warningText },
                  { range: "≥ 30.0",      cat: "Obese",       rowBg: "rgba(239,68,68,0.08)",   cellText: t.errorText },
                ].map(row => (
                  <tr key={row.range} style={{ background: row.rowBg }}>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, color: row.cellText, fontWeight: 600, fontFamily: "'DM Mono', monospace" }}>{row.range}</td>
                    <td style={{ padding: "8px 12px", border: `1px solid ${t.border}`, color: row.cellText, fontWeight: 600 }}>{row.cat}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* References */}
        <div style={{ borderTop: `1px solid ${t.border}`, paddingTop: 20, marginTop: 0 }}>
          <p style={{
            fontSize: 11, color: t.textMuted, fontWeight: 600,
            textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 12
          }}>Key references</p>
          {[
            "[1] Browning LM, Hsieh SD, Ashwell M. A systematic review of waist-to-height ratio as a screening tool for cardiovascular disease and diabetes. Obesity Reviews. 2010;11(3):165–178. PMID 20819243",
            "[2] Ashwell M. Waist-to-height ratio as a screening tool for cardiovascular risk. Nutrition Today. 2014;49(2):63–67. PMC4800150",
            "[3] Rodrigues AM et al. Sex-specific body roundness index cutpoints for metabolic syndrome in Brazilian adults. Scientific Reports. 2025. PMC12003638",
            "[4] Murai J et al. Body roundness index outperforms WHtR for insulin sensitivity correlation in middle-aged cohorts. Metabolism. 2024. PMC10951619",
            "[5] Valdez R. A simple model-based index of abdominal adiposity. J Clin Epidemiol. 1991;44(9):955–956. PMID 1890438",
            "[6] Waist-to-height ratio and sex as independent predictors of insulin resistance in non-diabetic adults. Scientific Reports. 2021. PMC8050044",
          ].map(ref => (
            <p key={ref} style={{ fontSize: 12, color: t.textMuted, lineHeight: 1.7, marginBottom: 5, fontFamily: "'DM Mono', monospace" }}>{ref}</p>
          ))}
        </div>

      </div>

      {/* ── Footer ── */}
      <div style={{
        maxWidth: 760, margin: "0 auto", padding: "24px 24px 40px",
        display: "flex", justifyContent: "space-between", alignItems: "center",
        flexWrap: "wrap", gap: 12
      }}>
        <span style={{ fontSize: 13, color: t.textMuted }}>© {new Date().getFullYear()} InResRisk — All rights reserved</span>
        <div style={{ display: "flex", gap: 20 }}>
          {[
            { label: "About",          href: "about" },
            { label: "Privacy Policy", href: "privacy" },
          ].map(({ label, href }) => (
            <a key={href} href={href} style={{ fontSize: 13, color: t.textMuted, textDecoration: "none" }}
              onMouseOver={e => e.target.style.color = t.primary}
              onMouseOut={e => e.target.style.color = t.textMuted}
            >{label}</a>
          ))}
        </div>
      </div>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
