// Common primitives: Crest, NASEF logo mark, GameTag, ScoreBadge, etc.

const Crest = ({ school, size = "md", className = "" }) => {
  const sizeCls = size === "lg" ? "lg" : size === "xl" ? "xl" : size === "sm" ? "sm" : "";
  if (!school) return <div className={`crest ${sizeCls} ${className}`} style={{ "--c1": "#1F2937", "--c2": "#0B0F18" }}>?</div>;
  if (school.logo) {
    return (
      <div className={`crest ${sizeCls} ${className} crest-logo`}
           style={{ "--c1": "transparent", "--c2": "transparent", background: "transparent", border: "none" }}>
        <img src={school.logo} alt={school.short}
             style={{ width: "100%", height: "100%", objectFit: "contain" }} />
      </div>
    );
  }
  const initials = school.tag?.slice(0, 3) || school.short?.slice(0, 2).toUpperCase() || "?";
  return (
    <div className={`crest ${sizeCls} ${className}`}
         style={{ "--c1": school.c1, "--c2": school.c2 }}>
      {initials}
    </div>
  );
};

// NASEF wordmark using real logo
const NASEFMark = ({ small = false, iconOnly = false }) => {
  const iconSize = small ? 26 : 36;
  if (iconOnly) {
    return <img src="assets/nasef-icon.png" alt="NASEF" style={{ width: iconSize, height: iconSize, objectFit: "contain" }} />;
  }
  return (
    <div className="nasef-mark" style={{ fontSize: small ? 14 : 16 }}>
      <img src="assets/nasef-icon.png" alt="" style={{ width: iconSize, height: iconSize, objectFit: "contain" }} />
      <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.05 }}>
        <span style={{ letterSpacing: "0.04em", color: "var(--nasef-orange)", fontWeight: 700 }}>NASEF</span>
        <span style={{ fontSize: 9, color: "var(--text-muted)", letterSpacing: "0.18em", fontWeight: 500, textTransform: "uppercase" }}>Arena</span>
      </span>
    </div>
  );
};

const GameTag = ({ game, size = "sm" }) => {
  const map = {
    SSBU: { label: "Smash Ultimate", short: "SSBU", color: "#FF4D9F" },
    MK8:  { label: "Mario Kart 8",   short: "MK8",  color: "#F7B928" },
    RL:   { label: "Rocket League",  short: "RL",   color: "#4FE3FF" },
    VAL:  { label: "Valorant",       short: "VAL",  color: "#F2455F" },
    LOL:  { label: "League",         short: "LoL",  color: "#9B6DFF" },
  };
  const g = map[game] || { label: game, short: game, color: "#888" };
  return (
    <span className="badge" style={{
      background: `${g.color}1A`,
      color: g.color,
      borderColor: `${g.color}55`,
      fontFamily: "var(--font-display)",
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 99, background: g.color, boxShadow: `0 0 6px ${g.color}` }} />
      {size === "sm" ? g.short : g.label}
    </span>
  );
};

const ScoreCell = ({ home, away, status, gameLabel }) => {
  if (status === "live") {
    return <span className="badge live"><span className="dot" />LIVE</span>;
  }
  if (status === "upcoming") {
    return <span className="muted mono" style={{ fontSize: 13 }}>—</span>;
  }
  return (
    <span className="mono" style={{ fontWeight: 600, fontSize: 16, letterSpacing: "0.04em" }}>
      {home}<span style={{ color: "var(--text-muted)", margin: "0 6px" }}>–</span>{away}
    </span>
  );
};

// Match row used in dashboard / schedule
const MatchRow = ({ match, schools, perspective = "ham", onClick, compact = false }) => {
  const home = schools[match.home];
  const away = schools[match.away];
  const isHome = match.home === perspective;
  const me = isHome ? home : away;
  const opp = isHome ? away : home;
  const myScore = isHome ? match.homeScore : match.awayScore;
  const oppScore = isHome ? match.awayScore : match.homeScore;
  const won = match.status === "complete" && myScore > oppScore;
  const lost = match.status === "complete" && myScore < oppScore;

  const dt = new Date(match.date + "T" + match.time);
  const dateStr = dt.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" });
  const timeStr = dt.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });

  return (
    <div className="match-row" onClick={onClick}
      style={{
        display: "grid",
        gridTemplateColumns: compact ? "auto 1fr auto" : "92px 1fr auto auto",
        gap: 16, alignItems: "center",
        padding: compact ? "12px 14px" : "14px 18px",
        borderRadius: "var(--r-md)",
        background: match.status === "live" ? "rgba(255,59,92,0.06)" : "transparent",
        border: "1px solid",
        borderColor: match.status === "live" ? "rgba(255,59,92,0.25)" : "transparent",
        cursor: onClick ? "pointer" : "default",
        transition: "all 0.12s",
      }}
      onMouseEnter={e => { if (onClick) e.currentTarget.style.background = "var(--bg-elevated)"; }}
      onMouseLeave={e => { if (onClick) e.currentTarget.style.background = match.status === "live" ? "rgba(255,59,92,0.06)" : "transparent"; }}
    >
      {!compact && (
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          <span className="upper" style={{ color: "var(--text-muted)" }}>Wk {match.week}</span>
          <span style={{ fontSize: 12, color: "var(--text-secondary)" }}>{dateStr}</span>
          <span style={{ fontSize: 11, color: "var(--text-muted)" }} className="mono">{timeStr}</span>
        </div>
      )}

      <div style={{ display: "flex", flexDirection: "column", gap: 6, minWidth: 0 }}>
        <div className="row" style={{ gap: 10 }}>
          <Crest school={home} size="sm" />
          <span style={{ fontWeight: isHome ? 600 : 400, color: lost && isHome ? "var(--text-muted)" : "var(--text)" }}>{home.name}</span>
          {match.status === "complete" && <span className="mono" style={{ marginLeft: "auto", fontWeight: 600, color: won && isHome ? "var(--success)" : lost && isHome ? "var(--text-muted)" : (myScore < oppScore ? "var(--text-muted)" : "var(--success)") }}>{match.homeScore}</span>}
        </div>
        <div className="row" style={{ gap: 10 }}>
          <Crest school={away} size="sm" />
          <span style={{ fontWeight: !isHome ? 600 : 400, color: lost && !isHome ? "var(--text-muted)" : "var(--text)" }}>{away.name}</span>
          {match.status === "complete" && <span className="mono" style={{ marginLeft: "auto", fontWeight: 600, color: won && !isHome ? "var(--success)" : lost && !isHome ? "var(--text-muted)" : (myScore < oppScore && !isHome ? "var(--text-muted)" : "") }}>{match.awayScore}</span>}
        </div>
      </div>

      {!compact && <GameTag game={match.game} />}

      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        {match.status === "live" && <span className="badge live"><span className="dot" />LIVE</span>}
        {match.status === "upcoming" && <span className="badge upcoming">Upcoming</span>}
        {match.status === "complete" && (won ? <span className="badge complete">W</span> : <span className="badge" style={{ color: "var(--text-muted)" }}>L</span>)}
        {onClick && <IconChevRight size={16} style={{ color: "var(--text-muted)" }} />}
      </div>
    </div>
  );
};

const Empty = ({ icon: Ic = IconInfo, title, body, action }) => (
  <div style={{ textAlign: "center", padding: "48px 24px", color: "var(--text-muted)" }}>
    <div style={{ display: "inline-flex", padding: 14, borderRadius: 12, background: "var(--bg-elevated)", marginBottom: 16, color: "var(--text-secondary)" }}>
      <Ic size={22} />
    </div>
    <h3 style={{ color: "var(--text)", marginBottom: 6, fontSize: 16 }}>{title}</h3>
    <p style={{ maxWidth: 380, margin: "0 auto", fontSize: 13 }}>{body}</p>
    {action && <div style={{ marginTop: 16 }}>{action}</div>}
  </div>
);

const PageHeader = ({ eyebrow, title, subtitle, actions }) => (
  <div className="page-header" style={{ marginBottom: 28, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 24 }}>
    <div className="page-header-text">
      {eyebrow && <div className="upper muted" style={{ marginBottom: 6 }}>{eyebrow}</div>}
      <h1 style={{ fontSize: 32, marginBottom: 6, fontWeight: 600, letterSpacing: "-0.02em" }}>{title}</h1>
      {subtitle && <p style={{ color: "var(--text-secondary)", fontSize: 14, margin: 0 }}>{subtitle}</p>}
    </div>
    {actions && <div className="row page-header-actions">{actions}</div>}
  </div>
);

const Tabs = ({ items, value, onChange }) => (
  <div style={{ display: "flex", gap: 4, padding: 4, background: "var(--bg-base)", borderRadius: "var(--r-md)", border: "1px solid var(--border-soft)", width: "fit-content" }}>
    {items.map(it => (
      <button key={it.value} onClick={() => onChange(it.value)}
        className="h-display"
        style={{
          padding: "7px 14px",
          fontSize: 12,
          fontWeight: 600,
          letterSpacing: "0.02em",
          background: value === it.value ? "var(--bg-elevated)" : "transparent",
          color: value === it.value ? "var(--text)" : "var(--text-muted)",
          border: "none",
          borderRadius: "var(--r-sm)",
          cursor: "pointer",
          transition: "all 0.12s",
        }}>
        {it.label}
      </button>
    ))}
  </div>
);

// Toast / inline notification
const Toast = ({ kind = "info", title, body, onClose }) => {
  const colors = {
    info: { bg: "var(--neon-cyan-soft)", border: "rgba(79,227,255,0.3)", text: "var(--neon-cyan)" },
    success: { bg: "rgba(45,212,120,0.1)", border: "rgba(45,212,120,0.3)", text: "var(--success)" },
    warning: { bg: "rgba(247,185,40,0.1)", border: "rgba(247,185,40,0.3)", text: "var(--warning)" },
  };
  const c = colors[kind] || colors.info;
  return (
    <div style={{
      padding: "12px 14px", borderRadius: "var(--r-md)",
      background: c.bg, border: `1px solid ${c.border}`,
      display: "flex", gap: 12, alignItems: "flex-start",
    }}>
      <IconInfo size={16} style={{ color: c.text, marginTop: 2, flexShrink: 0 }} />
      <div style={{ flex: 1, fontSize: 13 }}>
        {title && <div style={{ fontWeight: 600, color: "var(--text)", marginBottom: 2 }}>{title}</div>}
        <div style={{ color: "var(--text-secondary)" }}>{body}</div>
      </div>
      {onClose && <button className="btn ghost icon sm" onClick={onClose}><IconX size={12} /></button>}
    </div>
  );
};

// Player avatar — circular bitmap from assets/avatars
const Avatar = ({ src, name = "?", size = 32, ring = null, style = {} }) => {
  const initial = (name || "?").trim()[0]?.toUpperCase() || "?";
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      overflow: "hidden",
      background: "linear-gradient(135deg, #2A1810 0%, #14060A 100%)",
      border: ring ? `2px solid ${ring}` : "1px solid var(--border)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontWeight: 700, fontSize: Math.max(10, Math.round(size * 0.42)),
      color: "var(--text-secondary)",
      flexShrink: 0,
      boxShadow: ring ? `0 0 0 1px rgba(0,0,0,0.4), 0 2px 6px rgba(0,0,0,0.3)` : "none",
      ...style,
    }}>
      {src ? (
        <img src={src} alt={name}
          onError={(e) => { e.currentTarget.style.display = "none"; }}
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
      ) : initial}
    </div>
  );
};

// SSBU marquee banner — wallpaper backdrop with overlay content
const SSBUBanner = ({ height = 180, children, overlay = "match", subtle = false }) => {
  // overlay tints the wallpaper for legibility
  const overlayBg = subtle
    ? "linear-gradient(180deg, rgba(7,9,15,0.55) 0%, rgba(7,9,15,0.75) 100%)"
    : overlay === "match"
    ? "linear-gradient(180deg, rgba(7,9,15,0.35) 0%, rgba(7,9,15,0.65) 55%, rgba(7,9,15,0.92) 100%)"
    : "linear-gradient(180deg, rgba(7,9,15,0.45) 0%, rgba(7,9,15,0.85) 100%)";
  return (
    <div style={{
      position: "relative", height,
      overflow: "hidden",
      backgroundImage: "url(assets/ssbu-banner.png)",
      backgroundSize: "cover",
      backgroundPosition: "center 35%",
      boxShadow: "0 8px 28px -12px rgba(0,0,0,0.6)",
    }}>
      <div style={{ position: "absolute", inset: 0, background: overlayBg }} />
      {/* subtle orange scan */}
      <div style={{
        position: "absolute", inset: 0,
        background: "radial-gradient(ellipse 80% 60% at 50% 100%, rgba(242,104,34,0.18) 0%, transparent 70%)",
        mixBlendMode: "screen",
      }} />
      <div style={{ position: "relative", height: "100%", zIndex: 1 }}>
        {children}
      </div>
    </div>
  );
};

Object.assign(window, { Crest, NASEFMark, GameTag, ScoreCell, MatchRow, Empty, PageHeader, Tabs, Toast, Avatar, SSBUBanner });
