// ──────────────────────────────────────────────────────────────────
// Takedown UI primitives — iPhone frame, Button, Card, TextInput,
// Badge, Tag, Avatar, Overline, Hairline, ModuleDot, TabBar, StatusBar.
// All consume CSS custom properties from brand.css so dark/light flips
// at the class boundary.
// ──────────────────────────────────────────────────────────────────

// iPhone 14-style frame. 390×844 design size.
// `dark` prop forces theme class on the inner screen.
const PHONE_W = 390;
const PHONE_H = 844;

const Phone = ({ dark = true, children, label, status = "9:41", subtleChrome = false }) => {
  const themeClass = dark ? "tkdn-dark" : "tkdn-light";
  return (
    <div
      className="tkdn"
      style={{
        position: "relative",
        width: PHONE_W,
        height: PHONE_H,
        borderRadius: 56,
        padding: 10,
        background: subtleChrome ? "transparent" : (dark ? "#000" : "#0D0808"),
        boxSizing: "content-box",
      }}
    >
      <div
        className={themeClass}
        style={{
          position: "relative",
          width: "100%",
          height: "100%",
          background: "var(--bg-primary)",
          color: "var(--text-primary)",
          borderRadius: 46,
          overflow: "hidden",
        }}
      >
        <StatusBar time={status} dark={dark} />
        <HomeIndicator dark={dark} />
        {children}
      </div>
    </div>
  );
};

const StatusBar = ({ time = "9:41", dark = true }) => (
  <div
    style={{
      position: "absolute",
      top: 0,
      left: 0,
      right: 0,
      height: 54,
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      padding: "0 28px",
      zIndex: 50,
      pointerEvents: "none",
      color: "var(--text-primary)",
      fontSize: 15,
      fontWeight: 600,
      letterSpacing: 0.01,
    }}
  >
    <div style={{ paddingTop: 8 }}>{time}</div>
    {/* Dynamic island */}
    <div
      style={{
        position: "absolute",
        top: 11,
        left: "50%",
        transform: "translateX(-50%)",
        width: 122,
        height: 36,
        borderRadius: 999,
        background: "#000",
      }}
    />
    <div style={{ display: "flex", gap: 6, alignItems: "center", paddingTop: 8 }}>
      {/* Signal */}
      <svg width="18" height="11" viewBox="0 0 18 11" fill="currentColor">
        <rect x="0" y="7" width="3" height="4" rx="0.5" />
        <rect x="5" y="5" width="3" height="6" rx="0.5" />
        <rect x="10" y="2.5" width="3" height="8.5" rx="0.5" />
        <rect x="15" y="0" width="3" height="11" rx="0.5" />
      </svg>
      {/* WiFi */}
      <svg width="16" height="11" viewBox="0 0 16 11" fill="currentColor">
        <path d="M8 11a1.4 1.4 0 1 1 0-2.8A1.4 1.4 0 0 1 8 11zm-4-3.2l1.4 1.4a3.7 3.7 0 0 1 5.2 0L12 7.8a5.7 5.7 0 0 0-8 0zM1 5l1.4 1.4a8 8 0 0 1 11.2 0L15 5a10 10 0 0 0-14 0z" />
      </svg>
      {/* Battery */}
      <svg width="25" height="12" viewBox="0 0 25 12" fill="none" stroke="currentColor">
        <rect x="0.5" y="0.5" width="21" height="11" rx="2.5" />
        <rect x="22.5" y="4" width="1.5" height="4" rx="0.5" fill="currentColor" />
        <rect x="2" y="2" width="18" height="8" rx="1.5" fill="currentColor" />
      </svg>
    </div>
  </div>
);

const HomeIndicator = ({ dark = true }) => (
  <div
    style={{
      position: "absolute",
      bottom: 8,
      left: "50%",
      transform: "translateX(-50%)",
      width: 134,
      height: 5,
      borderRadius: 3,
      background: "var(--text-primary)",
      opacity: 0.95,
      zIndex: 50,
      pointerEvents: "none",
    }}
  />
);

// ── Button ────────────────────────────────────────────────────────
// variants: primary (filled accent), secondary (outline + accent text on press inverts),
//           ghost (text only), destructive (error ramp)
// sizes: large (40), medium (36), small (28 — chip)
// CTA-color preference: we expose a `tone` prop:
//   "accent" — orange (brand)
//   "mono"   — black-on-dark inverts to white; white-on-light inverts to black (the modern sleek default)
const Button = ({
  label,
  onClick,
  variant = "primary",
  size = "large",
  tone = "mono",
  disabled = false,
  loading = false,
  fullWidth = false,
  leftIcon,
  rightIcon,
  style,
}) => {
  const sizes = {
    large: { h: 48, px: 20, fs: 15, ic: 18 },
    medium: { h: 40, px: 16, fs: 14, ic: 16 },
    small: { h: 30, px: 12, fs: 12, ic: 14 },
  };
  const s = sizes[size];
  const isAccent = tone === "accent";

  const palettes = {
    primary: isAccent
      ? { bg: "var(--accent)", fg: "var(--text-on-accent)", bd: "var(--accent)" }
      : { bg: "var(--text-primary)", fg: "var(--bg-primary)", bd: "var(--text-primary)" },
    secondary: isAccent
      ? { bg: "transparent", fg: "var(--accent)", bd: "var(--accent)" }
      : { bg: "transparent", fg: "var(--text-primary)", bd: "var(--text-primary)" },
    ghost: { bg: "transparent", fg: isAccent ? "var(--accent)" : "var(--text-primary)", bd: "transparent" },
    destructive: { bg: "transparent", fg: "var(--error)", bd: "var(--error)" },
  };
  const p = palettes[variant];

  return (
    <button
      onClick={onClick}
      disabled={disabled || loading}
      style={{
        appearance: "none",
        border: variant === "ghost" ? "none" : `1px solid ${p.bd}`,
        background: p.bg,
        color: p.fg,
        height: s.h,
        padding: `0 ${s.px}px`,
        borderRadius: size === "small" ? "var(--r-xs)" : "var(--r-sm)",
        fontFamily: "inherit",
        fontWeight: 600,
        fontSize: s.fs,
        lineHeight: 1,
        letterSpacing: 0.02,
        cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.4 : 1,
        width: fullWidth ? "100%" : "auto",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        gap: 8,
        transition: "background var(--t-fast), color var(--t-fast), transform 120ms ease-out",
        WebkitTapHighlightColor: "transparent",
        ...style,
      }}
      onMouseDown={(e) => (e.currentTarget.style.transform = "scale(0.97)")}
      onMouseUp={(e) => (e.currentTarget.style.transform = "scale(1)")}
      onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}
    >
      {leftIcon && React.cloneElement(leftIcon, { size: s.ic })}
      {label}
      {rightIcon && React.cloneElement(rightIcon, { size: s.ic })}
    </button>
  );
};

// ── Card ──────────────────────────────────────────────────────────
// border-encoded elevation: 1 = subtle, 2 = default, 3 = strong (2px).
const Card = ({ elevation = 1, padding = true, onClick, children, style }) => {
  const borders = {
    1: "1px solid var(--border-subtle)",
    2: "1px solid var(--border-default)",
    3: "2px solid var(--border-default)",
  };
  return (
    <div
      onClick={onClick}
      style={{
        border: borders[elevation],
        background: "var(--surface-card)",
        borderRadius: "var(--r-sm)",
        padding: padding ? "var(--s-4)" : 0,
        cursor: onClick ? "pointer" : "default",
        ...style,
      }}
    >
      {children}
    </div>
  );
};

// ── TextInput ─────────────────────────────────────────────────────
const TextInput = ({
  label,
  value,
  onChange,
  type = "text",
  error,
  hint,
  leftIcon,
  rightIcon,
  isPassword = false,
  autoFocus = false,
  style,
}) => {
  const [focused, setFocused] = React.useState(false);
  const [showPw, setShowPw] = React.useState(false);
  const float = focused || (value && value.length > 0);
  const actualType = isPassword ? (showPw ? "text" : "password") : type;
  const ringColor = error ? "var(--error)" : "var(--accent)";

  return (
    <div style={{ width: "100%", ...style }}>
      <div
        style={{
          position: "relative",
          height: 56,
          background: "var(--bg-primary)",
          border: `1px solid ${error ? "var(--error)" : focused ? "var(--text-primary)" : "var(--border-default)"}`,
          borderRadius: "var(--r-sm)",
          padding: "0 14px",
          display: "flex",
          alignItems: "center",
          gap: 10,
          transition: "border-color var(--t-fast), box-shadow var(--t-fast)",
          boxShadow: focused ? `0 0 0 2px ${ringColor}` : "none",
        }}
      >
        {leftIcon && (
          <span style={{ color: "var(--text-secondary)" }}>{React.cloneElement(leftIcon, { size: 18 })}</span>
        )}
        <div style={{ flex: 1, position: "relative", height: "100%" }}>
          <label
            style={{
              position: "absolute",
              left: 0,
              top: float ? 8 : "50%",
              transform: float ? "none" : "translateY(-50%)",
              fontSize: float ? 11 : 14,
              fontWeight: float ? 700 : 400,
              letterSpacing: float ? "0.1em" : 0,
              textTransform: float ? "uppercase" : "none",
              color: float ? "var(--text-secondary)" : "var(--text-tertiary)",
              transition: "top var(--t-fast), font-size var(--t-fast), font-weight var(--t-fast), letter-spacing var(--t-fast), color var(--t-fast)",
              pointerEvents: "none",
            }}
          >
            {label}
          </label>
          <input
            type={actualType}
            value={value || ""}
            onChange={(e) => onChange && onChange(e.target.value)}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            autoFocus={autoFocus}
            style={{
              width: "100%",
              height: "100%",
              paddingTop: float ? 18 : 0,
              border: "none",
              background: "transparent",
              outline: "none",
              fontFamily: "inherit",
              fontSize: 15,
              fontWeight: 500,
              color: "var(--text-primary)",
              caretColor: "var(--accent)",
            }}
          />
        </div>
        {isPassword && (
          <button
            type="button"
            onClick={() => setShowPw(!showPw)}
            style={{
              border: "none",
              background: "transparent",
              color: "var(--text-secondary)",
              cursor: "pointer",
              padding: 4,
            }}
          >
            {showPw ? <I.EyeSlash size={18} /> : <I.Eye size={18} />}
          </button>
        )}
        {rightIcon && !isPassword && (
          <span style={{ color: "var(--text-secondary)" }}>{React.cloneElement(rightIcon, { size: 18 })}</span>
        )}
      </div>
      {(hint || error) && (
        <div
          className={error ? "t-caption-lg" : "t-caption-lg"}
          style={{
            marginTop: 6,
            color: error ? "var(--error)" : "var(--text-secondary)",
            paddingLeft: 4,
          }}
        >
          {error || hint}
        </div>
      )}
    </div>
  );
};

// ── Overline / eyebrow ───────────────────────────────────────────
const Overline = ({ children, color, style }) => (
  <div
    className="t-overline"
    style={{
      color: color || "var(--text-secondary)",
      ...style,
    }}
  >
    {children}
  </div>
);

// ── Hairline ─────────────────────────────────────────────────────
const Hairline = ({ vertical, style, color }) => (
  <div
    style={{
      background: color || "var(--border-subtle)",
      ...(vertical ? { width: 1, height: "100%" } : { height: 1, width: "100%" }),
      ...style,
    }}
  />
);

// ── Tag (chip) ───────────────────────────────────────────────────
const Tag = ({ children, active = false, accent = false, onClick, style }) => (
  <span
    onClick={onClick}
    style={{
      display: "inline-flex",
      alignItems: "center",
      gap: 4,
      padding: "5px 10px",
      borderRadius: "var(--r-xs)",
      border: `1px solid ${
        active
          ? "var(--text-primary)"
          : accent
          ? "var(--accent)"
          : "var(--border-subtle)"
      }`,
      background: active ? "var(--text-primary)" : "transparent",
      color: active ? "var(--bg-primary)" : accent ? "var(--accent)" : "var(--text-primary)",
      fontSize: 11,
      fontWeight: 700,
      letterSpacing: "0.1em",
      textTransform: "uppercase",
      cursor: onClick ? "pointer" : "default",
      ...style,
    }}
  >
    {children}
  </span>
);

// ── Badge ─────────────────────────────────────────────────────────
const Badge = ({ count, dot = false, color = "var(--accent)", style }) => {
  if (dot) {
    return (
      <span
        style={{
          width: 8,
          height: 8,
          borderRadius: "var(--r-full)",
          background: color,
          display: "inline-block",
          ...style,
        }}
      />
    );
  }
  return (
    <span
      style={{
        minWidth: 18,
        height: 18,
        padding: "0 5px",
        borderRadius: "var(--r-full)",
        background: color,
        color: "#fff",
        fontSize: 10,
        fontWeight: 700,
        lineHeight: "18px",
        textAlign: "center",
        display: "inline-block",
        ...style,
      }}
    >
      {count}
    </span>
  );
};

// ── Avatar ────────────────────────────────────────────────────────
const Avatar = ({ size = 40, src, initials, ring, style }) => (
  <div
    style={{
      width: size,
      height: size,
      borderRadius: "var(--r-full)",
      background: src ? `linear-gradient(135deg, #2a1a1a, #4a3030)` : "var(--bg-tertiary)",
      backgroundImage: src ? `url(${src})` : undefined,
      backgroundSize: "cover",
      backgroundPosition: "center",
      color: "var(--text-primary)",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      fontWeight: 700,
      fontSize: size * 0.36,
      letterSpacing: 0.02,
      border: ring ? `2px solid ${ring}` : "none",
      flexShrink: 0,
      ...style,
    }}
  >
    {!src && initials}
  </div>
);

// ── Module dot (5 module tints) ──────────────────────────────────
const MODULE_TINTS = {
  dojo: "var(--module-dojo)",
  builder: "var(--module-builder)",
  store: "var(--module-store)",
  scout: "var(--module-scout)",
  athlete: "var(--module-athlete)",
};

// ── Tab bar (bottom nav) ─────────────────────────────────────────
const TabBar = ({ active = "home", onChange, badges = {} }) => {
  const tabs = [
    { key: "home", icon: I.Home, label: "Feed", module: "athlete" },
    { key: "store", icon: I.Store, label: "Gear", module: "store" },
    { key: "team", icon: I.Users, label: "Team HQ", module: "builder" },
    { key: "events", icon: I.Calendar, label: "Events", module: "dojo" },
    { key: "profile", icon: I.Profile, label: "You", module: "athlete" },
  ];
  return (
    <div
      style={{
        position: "absolute",
        bottom: 0,
        left: 0,
        right: 0,
        height: 83,
        background: "var(--bg-primary)",
        borderTop: "1px solid var(--border-subtle)",
        display: "flex",
        paddingBottom: 22,
        zIndex: 40,
      }}
    >
      {tabs.map((t) => {
        const isActive = active === t.key;
        const Ico = t.icon;
        return (
          <button
            key={t.key}
            onClick={() => onChange && onChange(t.key)}
            style={{
              flex: 1,
              border: "none",
              background: "transparent",
              cursor: "pointer",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              gap: 4,
              padding: 8,
              position: "relative",
              color: isActive ? "var(--text-primary)" : "var(--text-tertiary)",
              WebkitTapHighlightColor: "transparent",
            }}
          >
            {/* top rule indicator */}
            <div
              style={{
                position: "absolute",
                top: 0,
                left: "50%",
                transform: "translateX(-50%)",
                width: isActive ? 28 : 0,
                height: 2,
                background: MODULE_TINTS[t.module],
                transition: "width var(--t-base)",
              }}
            />
            <div style={{ position: "relative" }}>
              <Ico size={22} stroke={isActive ? 2 : 1.5} />
              {badges[t.key] && (
                <Badge
                  count={badges[t.key]}
                  style={{
                    position: "absolute",
                    top: -4,
                    right: -8,
                  }}
                />
              )}
            </div>
            <span
              style={{
                fontSize: 10,
                fontWeight: 700,
                letterSpacing: "0.12em",
                textTransform: "uppercase",
              }}
            >
              {t.label}
            </span>
          </button>
        );
      })}
    </div>
  );
};

// ── TopBar (screen header) ────────────────────────────────────────
const TopBar = ({ title, left, right, large, sticky = false, modulekey, overline }) => (
  <div
    style={{
      position: sticky ? "sticky" : "relative",
      top: 0,
      background: "var(--bg-primary)",
      paddingTop: 54,
      paddingBottom: large ? 20 : 12,
      paddingLeft: 20,
      paddingRight: 20,
      zIndex: 30,
      borderBottom: large ? "none" : "1px solid var(--border-subtle)",
    }}
  >
    {!large && (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 32 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {left}
          <div className="t-sub-lg" style={{ fontWeight: 600 }}>
            {title}
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>{right}</div>
      </div>
    )}
    {large && (
      <div>
        {overline && (
          <Overline style={{ marginBottom: 8, color: modulekey ? MODULE_TINTS[modulekey] : "var(--accent)" }}>
            {overline}
          </Overline>
        )}
        <div className="t-h3" style={{ marginTop: 4 }}>{title}</div>
      </div>
    )}
  </div>
);

// ── Photo placeholder (abstract athletic) ────────────────────────
// We can't ship real photography — render placeholder fields that
// read as athletic photography stand-ins. Use as backgrounds.
const PhotoPlaceholder = ({ kind = "athlete", style }) => {
  const palettes = {
    athlete: ["#1a0e0e", "#3a1f1a", "#0d0808"],
    canvas: ["#1a1414", "#2a1f1f", "#0d0808"],
    arena: ["#0d0808", "#1f1414", "#3a1a1a"],
    mat: ["#0a0808", "#1a1010", "#2a1818"],
    gym: ["#0d0808", "#1a1410", "#241a14"],
  };
  const p = palettes[kind] || palettes.athlete;
  // Layered radial gradients to suggest a dramatic figure-on-dark photo
  return (
    <div
      style={{
        background: `
          radial-gradient(60% 80% at 50% 35%, ${p[1]} 0%, ${p[0]} 45%, ${p[2]} 100%),
          linear-gradient(180deg, ${p[2]} 0%, ${p[0]} 100%)
        `,
        ...style,
      }}
    />
  );
};

// Expose all to global scope so other Babel scripts can use them.
Object.assign(window, {
  Phone,
  StatusBar,
  HomeIndicator,
  Button,
  Card,
  TextInput,
  Overline,
  Hairline,
  Tag,
  Badge,
  Avatar,
  TabBar,
  TopBar,
  PhotoPlaceholder,
  MODULE_TINTS,
  PHONE_W,
  PHONE_H,
});
