/* UI primitives — Ring, Pill, Placeholder, Logo, etc. */
const { useState, useEffect, useRef, useMemo } = React;

/* ------------------- Brand ------------------- */
function BrandMark({ size = 28 }) {
  return (
    <div className="brand-mark" style={{ width: size, height: size, borderRadius: Math.round(size * 0.28) }}>
      <div style={{
        position: "absolute",
        inset: "auto " + Math.round(size * 0.14) + "px " + Math.round(size * 0.14) + "px auto",
        width: Math.round(size * 0.28),
        height: Math.round(size * 0.28),
        background: "var(--accent)",
        borderRadius: "50%",
      }} />
    </div>
  );
}

function Brand({ size = "md" }) {
  const cfg = size === "lg" ? { mark: 44, big: 22, small: 11 }
            : size === "sm" ? { mark: 22, big: 11, small: 9 }
            : { mark: 32, big: 15, small: 10 };
  return (
    <div className="brand" style={{ gap: 12 }}>
      <BrandMark size={cfg.mark} />
      <div className="brand-wordmark" style={{ gap: 1 }}>
        <span style={{ fontSize: cfg.big, fontWeight: 900, letterSpacing: "-0.04em" }}>GET&nbsp;FIT</span>
        <span style={{ fontSize: cfg.small }}>by tito fit</span>
      </div>
    </div>
  );
}

/* ------------------- Ring ------------------- */
function Ring({ value, max, size = 120, stroke = 12, color = "var(--accent)", label, sub, children }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = Math.max(0, Math.min(1, value / max));
  const off = c * (1 - pct);
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={size / 2} cy={size / 2} r={r} stroke="var(--line)" strokeWidth={stroke} fill="none" />
        <circle cx={size / 2} cy={size / 2} r={r} stroke={color} strokeWidth={stroke} fill="none"
                strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
                style={{ transition: "stroke-dashoffset 0.7s cubic-bezier(.2,.8,.2,1)" }} />
      </svg>
      <div style={{
        position: "absolute", inset: 0,
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        textAlign: "center"
      }}>
        {children || (
          <>
            <div className="mono" style={{ fontSize: size * 0.22, fontWeight: 700, letterSpacing: "-0.02em" }}>{label}</div>
            {sub && <div className="eyebrow" style={{ marginTop: 2 }}>{sub}</div>}
          </>
        )}
      </div>
    </div>
  );
}

/* ------------------- Placeholder ------------------- */
function Placeholder({ label, ratio = "4/3", style }) {
  return <div className="ph" data-label={label} style={{ aspectRatio: ratio, ...style }} />;
}

/* ------------------- Avatar ------------------- */
function Avatar({ name = "JS", size = 36 }) {
  return (
    <div className="avatar" style={{ width: size, height: size, fontSize: size * 0.38 }}>
      {name.slice(0, 2).toUpperCase()}
    </div>
  );
}

/* ------------------- Chip / Eyebrow ------------------- */
function Eyebrow({ children, style }) { return <div className="eyebrow" style={style}>{children}</div>; }

/* ------------------- Sparkline / Line chart ------------------- */
function LineChart({ data, height = 180, accessor = d => d.kg, labels = true }) {
  const w = 600;
  const h = height;
  const pad = 36;
  const xs = data.map((_, i) => pad + (i * (w - pad * 2)) / (data.length - 1));
  const vals = data.map(accessor);
  const min = Math.min(...vals) - 0.5;
  const max = Math.max(...vals) + 0.5;
  const ys = vals.map(v => pad + ((max - v) * (h - pad * 2)) / (max - min));
  const path = xs.map((x, i) => (i ? "L" : "M") + x + "," + ys[i]).join(" ");
  const area = path + " L" + xs[xs.length - 1] + "," + (h - pad) + " L" + xs[0] + "," + (h - pad) + " Z";

  return (
    <svg viewBox={"0 0 " + w + " " + h} width="100%" height={h}>
      <defs>
        <linearGradient id="lc-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.35" />
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* baseline grid */}
      {[0, 0.25, 0.5, 0.75, 1].map((t, i) => (
        <line key={i} x1={pad} y1={pad + t * (h - pad * 2)} x2={w - pad} y2={pad + t * (h - pad * 2)}
              stroke="var(--line-soft)" strokeDasharray="2 4" />
      ))}
      <path d={area} fill="url(#lc-grad)" />
      <path d={path} fill="none" stroke="var(--fg)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      {xs.map((x, i) => (
        <g key={i}>
          <circle cx={x} cy={ys[i]} r={i === xs.length - 1 ? 5 : 3}
                  fill={i === xs.length - 1 ? "var(--accent)" : "var(--bg)"}
                  stroke="var(--fg)" strokeWidth="2" />
          {labels && i % Math.ceil(data.length / 6) === 0 && (
            <text x={x} y={h - 10} fontSize="10" textAnchor="middle"
                  fontFamily="var(--f-mono)" fill="var(--fg-muted)">{data[i].date}</text>
          )}
        </g>
      ))}
    </svg>
  );
}

/* ------------------- Macro bar ------------------- */
function MacroBar({ p, c, f, target }) {
  const tp = target?.protein || 1;
  const tc = target?.carbs || 1;
  const tf = target?.fat || 1;
  const cell = (label, val, tgt, color) => (
    <div className="col" style={{ flex: 1, gap: 6 }}>
      <div className="between">
        <div className="eyebrow">{label}</div>
        <div className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{val}/{tgt}g</div>
      </div>
      <div style={{ height: 6, background: "var(--bg-sunken)", borderRadius: 3, overflow: "hidden" }}>
        <div style={{ width: Math.min(100, (val / tgt) * 100) + "%", height: "100%", background: color }} />
      </div>
    </div>
  );
  return (
    <div className="row" style={{ gap: 20, alignItems: "stretch" }}>
      {cell("Protein", p, tp, "var(--m-protein)")}
      {cell("Carbs",   c, tc, "var(--m-carbs)")}
      {cell("Fat",     f, tf, "var(--m-fat)")}
    </div>
  );
}

/* ------------------- Icon (line) ------------------- */
function Icon({ name, size = 18, color = "currentColor" }) {
  const stroke = { width: 1.6, stroke: color, fill: "none", strokeLinecap: "round", strokeLinejoin: "round" };
  const v = (children) => (
    <svg width={size} height={size} viewBox="0 0 24 24">{children}</svg>
  );
  switch (name) {
    case "home":    return v(<><path {...stroke} d="M3 11l9-8 9 8v9a1 1 0 0 1-1 1h-5v-7h-6v7H4a1 1 0 0 1-1-1z"/></>);
    case "meal":    return v(<><path {...stroke} d="M5 3v10a3 3 0 0 0 3 3v5M9 3v6M5 8h4M16 3c-2 1.5-2 5 0 7v11"/></>);
    case "photo":   return v(<><rect {...stroke} x="3" y="5" width="18" height="14" rx="2"/><circle {...stroke} cx="9" cy="11" r="2"/><path {...stroke} d="M3 17l5-4 4 3 4-4 5 5"/></>);
    case "user":    return v(<><circle {...stroke} cx="12" cy="8" r="4"/><path {...stroke} d="M4 20c2-4 6-6 8-6s6 2 8 6"/></>);
    case "card":    return v(<><rect {...stroke} x="3" y="6" width="18" height="13" rx="2"/><path {...stroke} d="M3 11h18"/></>);
    case "logout":  return v(<><path {...stroke} d="M15 4h4a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1h-4M10 8l-4 4 4 4M6 12h11"/></>);
    case "plus":    return v(<><path {...stroke} d="M12 5v14M5 12h14"/></>);
    case "settings":return v(<><circle {...stroke} cx="12" cy="12" r="3"/><path {...stroke} d="M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.4-2.3.9a7 7 0 0 0-2-1.2L14 3h-4l-.6 2.6a7 7 0 0 0-2 1.2l-2.3-.9-2 3.4 2 1.5A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.2l-2 1.5 2 3.4 2.3-.9a7 7 0 0 0 2 1.2L10 21h4l.6-2.6a7 7 0 0 0 2-1.2l2.3.9 2-3.4-2-1.5A7 7 0 0 0 19 12z"/></>);
    case "arrow":   return v(<><path {...stroke} d="M5 12h14M13 6l6 6-6 6"/></>);
    case "check":   return v(<><path {...stroke} d="M5 12l5 5 9-11"/></>);
    case "x":       return v(<><path {...stroke} d="M6 6l12 12M18 6L6 18"/></>);
    case "refresh": return v(<><path {...stroke} d="M4 11a8 8 0 0 1 14-4l3 1M20 13a8 8 0 0 1-14 4l-3-1M17 4v4h-4M7 20v-4h4"/></>);
    case "drag":    return v(<><circle {...stroke} cx="9" cy="6" r="1"/><circle {...stroke} cx="15" cy="6" r="1"/><circle {...stroke} cx="9" cy="12" r="1"/><circle {...stroke} cx="15" cy="12" r="1"/><circle {...stroke} cx="9" cy="18" r="1"/><circle {...stroke} cx="15" cy="18" r="1"/></>);
    case "lock":    return v(<><rect {...stroke} x="5" y="11" width="14" height="9" rx="2"/><path {...stroke} d="M8 11V8a4 4 0 1 1 8 0v3"/></>);
    case "bell":    return v(<><path {...stroke} d="M6 16V11a6 6 0 1 1 12 0v5l2 2H4z"/><path {...stroke} d="M10 20a2 2 0 0 0 4 0"/></>);
    case "upload":  return v(<><path {...stroke} d="M12 16V4M6 10l6-6 6 6M4 20h16"/></>);
    case "clock":   return v(<><circle {...stroke} cx="12" cy="12" r="9"/><path {...stroke} d="M12 7v5l3 2"/></>);
    case "flame":   return v(<><path {...stroke} d="M12 3c1 4-3 5-3 9a5 5 0 0 0 10 0c0-3-2-4-3-6 0 2-2 2-2 0 0-2-1-3-2-3z"/></>);
    default:        return v(<><circle {...stroke} cx="12" cy="12" r="9"/></>);
  }
}

function DataRow({ k, v, muted }) {
  return (
    <div className="between" style={{ fontSize: 14 }}>
      <span className="muted">{k}</span>
      <span className="mono" style={{ fontWeight: 600, color: muted ? "var(--fg-muted)" : "var(--fg)" }}>{v}</span>
    </div>
  );
}

Object.assign(window, {
  Brand, BrandMark, Ring, Placeholder, Avatar, Eyebrow, LineChart, MacroBar, Icon, DataRow,
});
