/* Community data + CommunityCard + animated LoveButton.
 * Exported on window.Community = { PIECES, CommunityCard, LoveButton, KIND_META }. */

const { Avatar } = window.ClaudeDesignExtractedStyles_062859;

const KIND_META = {
  Prototype: { tint: "accent", color: "var(--cds-clay)" },
  Slides: { tint: "template", color: "var(--cds-violet-500)" },
  Document: { tint: "designSystem", color: "var(--om-text-design-system-badge)" },
  Wireframe: { tint: "neutral", color: "var(--cds-gray-500)" },
  Animation: { tint: "template", color: "var(--cds-mineral)" },
};

/* avatar tints rotate for variety */
const PIECES = [
  // ── Featured ──────────────────────────────────────────────
  { id: "tidal", title: "Tidal Drift – ambient player", kind: "Prototype", thumb: "player", author: "Marlowe Reyes", initials: "MR", tint: "template", loves: 4820, remixes: 612, featured: true },
  { id: "orders", title: "Orders, reimagined", kind: "Prototype", thumb: "analytics", author: "Priya Nandakumar", initials: "PN", tint: "accent", loves: 3914, remixes: 488, featured: true },
  { id: "logistics", title: "Logistics – Series A deck", kind: "Slides", thumb: "deck", author: "Theo Vance", initials: "TV", tint: "neutral", loves: 3102, remixes: 271, featured: true },
  { id: "flowfield", title: "Flow Field", kind: "Animation", thumb: "shader", author: "Anil Brar", initials: "AB", tint: "template", loves: 5640, remixes: 904, featured: true },
  { id: "sprint", title: "Sprint Board", kind: "Prototype", thumb: "kanban", author: "Jules Okafor", initials: "JO", tint: "designSystem", loves: 2480, remixes: 356, featured: true },
  { id: "tarot", title: "The Star – tarot draw", kind: "Prototype", thumb: "tarot", author: "Wren Halloway", initials: "WH", tint: "template", loves: 3370, remixes: 219, featured: true },
  { id: "lisbon", title: "Lisbon, hourly", kind: "Prototype", thumb: "weather", author: "Sofia Marques", initials: "SM", tint: "accent", loves: 2106, remixes: 187, featured: true },
  { id: "raymarch", title: "Raymarch playground", kind: "Prototype", thumb: "editor", author: "Kenji Watanabe", initials: "KW", tint: "neutral", loves: 1890, remixes: 402, featured: true },
  { id: "streak", title: "Writing Streak", kind: "Prototype", thumb: "habit", author: "Dana Whitfield", initials: "DW", tint: "designSystem", loves: 1654, remixes: 143, featured: true },
  { id: "pocket", title: "Pocket Chat", kind: "Prototype", thumb: "chat", author: "Liang Chen", initials: "LC", tint: "template", loves: 1420, remixes: 98, featured: true },
  { id: "trailhead", title: "Trailhead – route finder", kind: "Prototype", thumb: "map", author: "Esme Holt", initials: "EH", tint: "accent", loves: 1208, remixes: 76, featured: true },
  { id: "moodboard", title: "Moodboard", kind: "Document", thumb: "gallery", author: "Camille Roy", initials: "CR", tint: "neutral", loves: 980, remixes: 64, featured: true },

  // ── Recent (your personalized queue) ──────────────────────
  { id: "r-deploy", title: "One-command deploy demo", kind: "Prototype", thumb: "terminal", author: "Otis Frame", initials: "OF", tint: "neutral", loves: 47, remixes: 5 },
  { id: "r-pitch", title: "Plant-care startup pitch", kind: "Slides", thumb: "deck", author: "Bea Lindqvist", initials: "BL", tint: "template", loves: 128, remixes: 11 },
  { id: "r-habit", title: "Cold-plunge tracker", kind: "Prototype", thumb: "habit", author: "Ravi Desai", initials: "RD", tint: "designSystem", loves: 19, remixes: 1 },
  { id: "r-chat", title: "Support inbox concept", kind: "Prototype", thumb: "chat", author: "Mina Sato", initials: "MS", tint: "accent", loves: 73, remixes: 8 },
  { id: "r-shader", title: "Bioluminescence study", kind: "Animation", thumb: "shader", author: "Nikolai Pope", initials: "NP", tint: "template", loves: 91, remixes: 14 },
  { id: "r-weather", title: "Tide & surf board", kind: "Prototype", thumb: "weather", author: "Coral Adeyemi", initials: "CA", tint: "accent", loves: 6, remixes: 0 },
  { id: "r-orders", title: "Café daily numbers", kind: "Prototype", thumb: "analytics", author: "Hugo Mertens", initials: "HM", tint: "neutral", loves: 34, remixes: 3 },
  { id: "r-gallery", title: "Travel film stills", kind: "Document", thumb: "gallery", author: "Yuki Tanaka", initials: "YT", tint: "designSystem", loves: 152, remixes: 9 },
  { id: "r-kanban", title: "Wedding planner board", kind: "Prototype", thumb: "kanban", author: "Greta Olsson", initials: "GO", tint: "template", loves: 11, remixes: 0 },
];

function fmt(n) {
  if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, "") + "k";
  return String(n);
}

const HeartIcon = ({ filled, size = 15 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: "block" }}
    fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth={filled ? 0 : 1.9} strokeLinejoin="round">
    <path d="M12 20.5C12 20.5 3.5 15 3.5 8.9 3.5 6.2 5.6 4.2 8.2 4.2c1.7 0 3.1.9 3.8 2.2.7-1.3 2.1-2.2 3.8-2.2 2.6 0 4.7 2 4.7 4.7C20.5 15 12 20.5 12 20.5Z" />
  </svg>
);

function LoveButton({ id, base, compact }) {
  const storeKey = "cd-community-loves";
  const read = () => { try { return JSON.parse(localStorage.getItem(storeKey) || "{}"); } catch (e) { return {}; } };
  const [loved, setLoved] = React.useState(() => !!read()[id]);
  const [burst, setBurst] = React.useState(0);

  const toggle = (e) => {
    e.stopPropagation();
    const next = !loved;
    setLoved(next);
    if (next) setBurst((b) => b + 1);
    const map = read();
    if (next) map[id] = true; else delete map[id];
    try { localStorage.setItem(storeKey, JSON.stringify(map)); } catch (err) {}
  };

  const count = base + (loved ? 1 : 0);
  return (
    <button type="button" onClick={toggle}
      style={{
        display: "inline-flex", alignItems: "center", gap: 6, height: 30, padding: compact ? "0 9px" : "0 11px",
        borderRadius: 999, cursor: "pointer", fontFamily: "var(--cds-font-sans)", fontSize: 12.5, fontWeight: 600,
        border: "1px solid " + (loved ? "var(--cds-clay)" : "var(--om-border-card)"),
        background: loved ? "var(--om-accent-primary-bg)" : "var(--om-bg-surface)",
        color: loved ? "var(--cds-clay)" : "var(--om-text-secondary)",
        transition: "background .15s, border-color .15s, color .15s, transform .08s", position: "relative",
      }}
      onMouseDown={(e) => (e.currentTarget.style.transform = "scale(.94)")}
      onMouseUp={(e) => (e.currentTarget.style.transform = "scale(1)")}
      onMouseLeave={(e) => (e.currentTarget.style.transform = "scale(1)")}>
      <span style={{ position: "relative", display: "inline-flex", animation: burst ? "cd-heart-pop .42s var(--cds-ease-overshoot)" : "none" }} key={burst}>
        <HeartIcon filled={loved} />
        {burst > 0 && loved && (
          <span aria-hidden style={{ position: "absolute", inset: 0, display: "block" }}>
            {[0, 1, 2, 3, 4, 5].map((i) => (
              <span key={i} style={{
                position: "absolute", left: "50%", top: "50%", width: 3, height: 3, borderRadius: "50%",
                background: "var(--cds-clay)", "--a": `${i * 60}deg`,
                animation: "cd-spark .5s ease-out forwards",
              }} />
            ))}
          </span>
        )}
      </span>
      <span style={{ minWidth: 14, textAlign: "left", fontVariantNumeric: "tabular-nums" }}>{fmt(count)}</span>
    </button>
  );
}

function RemixStat({ n }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: "var(--om-text-tertiary)", fontFamily: "var(--cds-font-sans)", fontWeight: 500 }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 5h7l3 3M4 5v6M4 5l5 5M20 19h-7l-3-3M20 19v-6M20 19l-5-5" />
      </svg>
      {fmt(n)}
    </span>
  );
}

function CommunityCard({ piece, cardStyle = "soft", onOpen }) {
  const [hover, setHover] = React.useState(false);
  const Thumb = window.CommunityThumbs[piece.thumb];
  const km = KIND_META[piece.kind] || KIND_META.Prototype;

  const styles = {
    soft: { border: "1px solid var(--om-border-card)", shadow: "var(--om-shadow-sm)", hoverShadow: "var(--om-shadow-card)", radius: 16 },
    bordered: { border: "1.5px solid var(--om-border-strong)", shadow: "none", hoverShadow: "none", radius: 14 },
    elevated: { border: "1px solid var(--om-border-subtle)", shadow: "var(--om-shadow-md)", hoverShadow: "var(--om-shadow-card)", radius: 18 },
    minimal: { border: "none", shadow: "none", hoverShadow: "none", radius: 14 },
  }[cardStyle] || {};

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => onOpen && onOpen(piece)}
      style={{
        background: cardStyle === "minimal" ? "transparent" : "var(--om-bg-surface)",
        border: styles.border, borderRadius: styles.radius,
        boxShadow: hover ? styles.hoverShadow : styles.shadow,
        overflow: "hidden", cursor: "pointer", fontFamily: "var(--cds-font-sans)",
        transition: "box-shadow .2s var(--cds-ease-out), transform .2s var(--cds-ease-out), border-color .2s",
        transform: hover ? "translateY(-3px)" : "none",
        display: "flex", flexDirection: "column",
      }}>
      {/* thumbnail */}
      <div style={{
        position: "relative", aspectRatio: "16 / 10", borderRadius: cardStyle === "minimal" ? 12 : 0,
        overflow: "hidden", background: "var(--cds-gray-80)",
        border: cardStyle === "minimal" ? "1px solid var(--om-border-card)" : "none",
        borderBottom: cardStyle === "minimal" ? "1px solid var(--om-border-card)" : "1px solid var(--om-border-subtle)",
      }}>
        <div style={{ position: "absolute", inset: 0, transition: "transform .35s var(--cds-ease-out)", transform: hover ? "scale(1.045)" : "scale(1)" }}>
          <Thumb />
        </div>
        {/* kind badge over thumb */}
        <span style={{
          position: "absolute", top: 10, left: 10, display: "inline-flex", alignItems: "center", gap: 5,
          height: 21, padding: "0 9px", borderRadius: 999, background: "#ffffffe6", backdropFilter: "blur(6px)",
          fontSize: 10.5, fontWeight: 700, letterSpacing: "0.02em", color: km.color, boxShadow: "var(--om-shadow-xs)",
        }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: km.color }} />
          {piece.kind}
        </span>
        {/* open affordance */}
        <span style={{
          position: "absolute", right: 10, bottom: 10, height: 28, padding: "0 12px", borderRadius: 999,
          background: "var(--om-accent-black)", color: "var(--om-text-inverse)", fontSize: 11.5, fontWeight: 600,
          display: "inline-flex", alignItems: "center", gap: 5,
          opacity: hover ? 1 : 0, transform: hover ? "translateY(0)" : "translateY(6px)",
          transition: "opacity .2s, transform .2s",
        }}>Open ↗</span>
      </div>
      {/* meta */}
      <div style={{ padding: cardStyle === "minimal" ? "12px 2px 4px" : "14px 16px 15px", display: "flex", flexDirection: "column", gap: 11, flex: 1 }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: "var(--om-text-primary)", letterSpacing: "-0.01em", lineHeight: 1.25 }}>{piece.title}</div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "auto" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
            <Avatar initials={piece.initials} size="sm" tint={piece.tint} />
            <span style={{ fontSize: 12.5, color: "var(--om-text-secondary)", fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{piece.author}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, flexShrink: 0 }}>
            <RemixStat n={piece.remixes} />
            <LoveButton id={piece.id} base={piece.loves} />
          </div>
        </div>
      </div>
    </div>
  );
}

window.Community = { PIECES, CommunityCard, LoveButton, RemixStat, KIND_META, fmt };
