/* ============================================================
   EBTR — Cover art + article cards
   CoverArt generates a distinct, on-brand visual per article from
   CSS gradient fields + SVG motifs (blue=structure, orange=danger,
   purple=connective). No stock photography — the brand is fields,
   bars and blocks. ArticleCard renders the feed cards in 4 sizes.
   ============================================================ */
const { ThreeBar: EBThreeBar, Badge: EBBadge } = window.EBTHubDesignSystem_ccdc9d;

const EBTR_ACCENT = {
  purple: { base: "#5d5dbf", deep: "#3a3a86", ink: "#171633", line: "rgba(255,255,255,0.10)" },
  blue:   { base: "#1d38dc", deep: "#1429a8", ink: "#0b1242", line: "rgba(255,255,255,0.10)" },
  orange: { base: "#ff8c03", deep: "#b35e07", ink: "#2a1705", line: "rgba(255,255,255,0.12)" },
  stone:  { base: "#6f6967", deep: "#403b3a", ink: "#181615", line: "rgba(255,255,255,0.08)" },
};
function ebtrAccentVar(name) {
  return { purple: "var(--ebt-purple)", blue: "var(--ebt-blue)", orange: "var(--ebt-orange)", stone: "var(--neutral-400)" }[name] || "var(--ebt-blue)";
}

/* ---- The cover field. `cover` chooses the motif; `accent` the palette. ---- */
function EBTRCover({ cover = "grid", accent = "blue", label, big = false, src, style }) {
  const p = EBTR_ACCENT[accent] || EBTR_ACCENT.blue;
  const wrap = {
    position: "relative", width: "100%", height: "100%", overflow: "hidden",
    background: p.ink, ...style,
  };
  const fill = { position: "absolute", inset: 0 };

  // If a real cover image URL is provided, use it (magazine-style) with a
  // subtle scrim + the three-bar tick for brand cohesion.
  if (src) {
    return (
      <div style={wrap} aria-hidden="true">
        <img src={src} alt="" loading="lazy" style={{ ...fill, width: "100%", height: "100%", objectFit: "cover" }} />
        <div style={{ ...fill, background: "linear-gradient(to top, rgba(0,0,0,0.45) 0%, transparent 42%)" }} />
        <div style={{ position: "absolute", left: 0, bottom: 0, display: "flex", width: big ? 96 : 60, height: big ? 6 : 4 }}>
          <span style={{ flex: 1, background: "var(--bar-1)" }} />
          <span style={{ flex: 1, background: "var(--bar-2)" }} />
          <span style={{ flex: 1, background: "var(--bar-3)" }} />
        </div>
      </div>
    );
  }

  let layers = null;
  if (cover === "slope") {
    // Risk Slope: blue (safe) → orange (danger), rising bars
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: "linear-gradient(105deg, #0b1242 0%, #1d38dc 38%, #b35e07 78%, #ff8c03 100%)" }} />
        <svg style={fill} viewBox="0 0 100 60" preserveAspectRatio="none">
          {[10, 24, 38, 52, 66, 80].map((x, i) => (
            <rect key={i} x={x} y={52 - i * 7} width="7" height={6 + i * 7} fill="rgba(0,0,0,0.22)" />
          ))}
          <path d="M2 52 L92 6" stroke="rgba(255,255,255,0.55)" strokeWidth="0.6" fill="none" />
        </svg>
      </React.Fragment>
    );
  } else if (cover === "grid") {
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: `radial-gradient(120% 90% at 75% 10%, ${p.base} 0%, ${p.deep} 45%, ${p.ink} 100%)` }} />
        <div style={{ ...fill, backgroundImage: `linear-gradient(${p.line} 1px, transparent 1px), linear-gradient(90deg, ${p.line} 1px, transparent 1px)`, backgroundSize: big ? "44px 44px" : "26px 26px" }} />
      </React.Fragment>
    );
  } else if (cover === "stack") {
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: `linear-gradient(135deg, ${p.deep} 0%, ${p.base} 60%, ${p.ink} 100%)` }} />
        <div style={{ position: "absolute", right: "8%", top: "50%", transform: "translateY(-50%)", display: "flex", flexDirection: "column", gap: 6 }}>
          {["var(--bar-1)", "var(--bar-2)", "var(--bar-3)"].map((c, i) => (
            <span key={i} style={{ height: big ? 26 : 16, width: big ? 132 : 78, background: c, transform: `translateX(${i * (big ? -18 : -11)}px)` }} />
          ))}
        </div>
      </React.Fragment>
    );
  } else if (cover === "diagnostic") {
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: `linear-gradient(120deg, ${p.ink} 0%, ${p.deep} 70%, ${p.base} 120%)` }} />
        <div style={{ ...fill, display: "flex", alignItems: "flex-end", gap: "6%", padding: "0 12% 16%" }}>
          {[["L1", 0.34, "var(--ebt-blue)"], ["L2", 0.62, "var(--ebt-orange)"], ["L3", 1.0, "var(--ebt-purple)"]].map(([t, h, c], i) => (
            <div key={i} style={{ flex: 1, textAlign: "center" }}>
              <div style={{ height: (big ? 120 : 70) * h, background: c, opacity: 0.92 }} />
              <div style={{ fontFamily: "var(--font-ui)", fontSize: big ? 12 : 9, color: "rgba(255,255,255,0.8)", marginTop: 6, letterSpacing: "0.1em" }}>{t}</div>
            </div>
          ))}
        </div>
      </React.Fragment>
    );
  } else if (cover === "mono") {
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: "radial-gradient(130% 100% at 85% 90%, #2a1705 0%, #161414 55%, #0e0d0d 100%)" }} />
        <div style={{ position: "absolute", left: 0, top: "18%", height: "64%", width: big ? 14 : 9, background: "var(--ebt-orange)" }} />
        <div style={{ ...fill, display: "flex", alignItems: "center", justifyContent: "flex-end", paddingRight: "8%" }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: big ? 150 : 88, color: "rgba(255,140,3,0.16)", lineHeight: 1 }}>F</span>
        </div>
      </React.Fragment>
    );
  } else if (cover === "memory") {
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: `radial-gradient(110% 110% at 30% 20%, ${p.base} 0%, ${p.deep} 50%, ${p.ink} 100%)` }} />
        {[0, 1, 2, 3, 4].map((i) => (
          <div key={i} style={{ position: "absolute", inset: 0, border: "1px solid rgba(255,255,255,0.10)", transform: `scale(${1 - i * 0.16})`, opacity: 1 - i * 0.16 }} />
        ))}
      </React.Fragment>
    );
  } else if (cover === "scatter") {
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: `radial-gradient(120% 100% at 60% 30%, ${p.base} 0%, ${p.deep} 55%, ${p.ink} 100%)` }} />
        <svg style={fill} viewBox="0 0 100 60">
          {Array.from({ length: 26 }).map((_, i) => {
            const x = (i * 37) % 100, y = (i * 53) % 60, r = ((i * 7) % 5) * 0.5 + 1;
            return <circle key={i} cx={x} cy={y} r={r} fill={i % 4 === 0 ? "var(--ebt-orange)" : "rgba(255,255,255,0.35)"} />;
          })}
        </svg>
      </React.Fragment>
    );
  } else if (cover === "brief") {
    layers = (
      <React.Fragment>
        <div style={{ ...fill, background: `linear-gradient(115deg, ${p.ink} 0%, ${p.deep} 65%, ${p.base} 130%)` }} />
        <div style={{ ...fill, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <span style={{ fontFamily: "var(--font-ui)", fontSize: big ? 92 : 52, color: "rgba(255,255,255,0.9)", letterSpacing: "-0.02em" }}>95<span style={{ color: "var(--ebt-orange)" }}>%</span></span>
        </div>
      </React.Fragment>
    );
  }

  return (
    <div style={wrap} aria-hidden="true">
      {layers}
      {/* shared bottom scrim + three-bar tick for cohesion */}
      <div style={{ ...fill, background: "linear-gradient(to top, rgba(0,0,0,0.45) 0%, transparent 42%)" }} />
      <div style={{ position: "absolute", left: 0, bottom: 0, display: "flex", width: big ? 96 : 60, height: big ? 6 : 4 }}>
        <span style={{ flex: 1, background: "var(--bar-1)" }} />
        <span style={{ flex: 1, background: "var(--bar-2)" }} />
        <span style={{ flex: 1, background: "var(--bar-3)" }} />
      </div>
    </div>
  );
}

/* ---- Small reusable bits ---- */
function EBTRCategoryTag({ category, onClick, active }) {
  const cats = window.EBTR_DATA.categories;
  const c = cats[category];
  if (!c) return null;
  return (
    <button
      onClick={onClick}
      style={{
        display: "inline-flex", alignItems: "center", gap: 8, background: "none", border: "none",
        padding: 0, cursor: onClick ? "pointer" : "default", fontFamily: "var(--font-ui)",
        fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase",
        color: active ? "var(--white)" : "var(--text-secondary)",
      }}
    >
      <span style={{ width: 9, height: 9, background: ebtrAccentVar(c.color), flex: "none" }} />
      {c.label}
    </button>
  );
}

function EBTRMeta({ article, light }) {
  const a = window.EBTR_DATA.authors[article.author];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.04em", color: light ? "var(--text-secondary)" : "var(--text-muted)" }}>
      <span style={{ color: "var(--text-primary)" }}>{a.name}</span>
      <span style={{ opacity: 0.5 }}>/</span>
      <span>{article.readingMins} MIN</span>
    </div>
  );
}

function EBTRPremiumTag() {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-ui)", fontSize: 9.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--neutral-1000)", background: "var(--ebt-orange)", padding: "4px 9px", lineHeight: 1 }}>
      <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><rect x="5" y="11" width="14" height="10" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></svg>
      Premium
    </span>
  );
}

/* ---- The article card. size: lead | lg | md | row ---- */
function EBTRArticleCard({ article, size = "md", onOpen, onCategory }) {
  const [hover, setHover] = React.useState(false);
  const cat = window.EBTR_DATA.categories[article.category];
  const accent = ebtrAccentVar(cat.color);
  const titleFont = { fontFamily: "var(--font-body)", fontWeight: 700, color: "var(--text-primary)", letterSpacing: "-0.01em", textWrap: "balance" };

  const open = () => onOpen && onOpen(article.id);

  if (size === "row") {
    return (
      <div onClick={open} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ display: "grid", gridTemplateColumns: "58px 1fr", gap: 16, alignItems: "center", padding: "18px 0", borderBottom: "1px solid var(--border-hairline)", cursor: "pointer", transition: "background var(--dur-base) var(--ease-out)", background: hover ? "rgba(255,255,255,0.02)" : "transparent" }}>
        <div style={{ width: 58, height: 58, flex: "none", outline: hover ? `1px solid ${accent}` : "1px solid var(--border-hairline)", transition: "outline-color var(--dur-base)" }}>
          <EBTRCover cover={article.cover} accent={cat.color} src={article.coverUrl} />
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6, flexWrap: "wrap" }}>
            <EBTRCategoryTag category={article.category} />
            {article.premium && <EBTRPremiumTag />}
          </div>
          <div style={{ ...titleFont, fontSize: 17, lineHeight: 1.22, color: hover ? "var(--blue-400)" : "var(--text-primary)", transition: "color var(--dur-base)" }}>{article.title}</div>
          <div style={{ marginTop: 7 }}><EBTRMeta article={article} /></div>
        </div>
      </div>
    );
  }

  const coverH = size === "lead" ? 360 : size === "lg" ? 240 : 188;
  return (
    <article onClick={open} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: "flex", flexDirection: "column", cursor: "pointer", background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderTop: `3px solid ${hover ? accent : "var(--border-hairline)"}`, transition: "border-color var(--dur-base) var(--ease-out), box-shadow var(--dur-base) var(--ease-out), transform var(--dur-base) var(--ease-out)", boxShadow: hover ? "var(--shadow-md)" : "none", transform: hover ? "translateY(-3px)" : "none", height: "100%" }}>
      <div style={{ height: coverH, position: "relative", flex: "none" }}>
        <EBTRCover cover={article.cover} accent={cat.color} big={size === "lead"} src={article.coverUrl} />
        {article.premium && <div style={{ position: "absolute", top: 12, right: 12 }}><EBTRPremiumTag /></div>}
      </div>
      <div style={{ padding: size === "lead" ? "26px 28px 28px" : "20px 20px 22px", display: "flex", flexDirection: "column", gap: 12, flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <EBTRCategoryTag category={article.category} onClick={onCategory ? (e) => { e.stopPropagation(); onCategory(article.category); } : null} />
        </div>
        <h3 style={{ ...titleFont, margin: 0, fontSize: size === "lead" ? 34 : size === "lg" ? 24 : 19, lineHeight: 1.15, color: hover ? "var(--blue-400)" : "var(--text-primary)", transition: "color var(--dur-base)" }}>{article.title}</h3>
        {size !== "md" && <p style={{ margin: 0, fontFamily: "var(--font-body)", fontSize: size === "lead" ? 17 : 15, lineHeight: 1.5, color: "var(--text-secondary)" }}>{article.dek}</p>}
        <div style={{ marginTop: "auto", paddingTop: 6 }}><EBTRMeta article={article} /></div>
      </div>
    </article>
  );
}

Object.assign(window, { EBTRCover, EBTRCategoryTag, EBTRMeta, EBTRPremiumTag, EBTRArticleCard, ebtrAccentVar });
