/* PreviewX — pixel-faithful X (Twitter) card. This is deliberately NOT
   CROPR-branded: it mimics the platform so the team sees exactly what
   followers will see. Handles the X sub-targets (CROPR / Jo / Nitin),
   thread rendering (numbered + connector), media crop, and the 280 limit. */
(function () {
  const SYS = '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif';
  const D = window.CROPR_DATA;

  function XMedia({ media }) {
    if (!media || (!media.url && media.status !== "ready") || !media.kind) return null;
    return (
      <div style={{ marginTop: 12, borderRadius: 16, overflow: "hidden", border: "1px solid #EFF3F4",
        aspectRatio: "16 / 9", background: "linear-gradient(135deg,#38BDF822,#FCA5A533)", position: "relative", display: "grid", placeItems: "center" }}>
        {media.url
          ? (media.kind === "video" ? <video src={media.url} muted playsInline loop style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <img src={media.url} alt={media.altText || ""} style={{ width: "100%", height: "100%", objectFit: "cover" }} />)
          : <div style={{ color: "#536471", fontSize: 12.5, fontWeight: 600, display: "flex", alignItems: "center", gap: 8 }}>
              <Icon name={media.kind === "video" ? "play" : "image"} size={20} color="#536471" />
              {media.kind === "video" ? "Video" : "Image"} · {media.altText || "no alt text"}
            </div>}
        <span style={{ position: "absolute", left: 10, bottom: 10, background: "rgba(0,0,0,.6)", color: "#fff",
          fontSize: 10.5, fontWeight: 700, padding: "2px 7px", borderRadius: 6, textTransform: "uppercase" }}>{media.kind}</span>
      </div>
    );
  }

  function Actions({ n }) {
    const item = (icon, val) => (
      <span style={{ display: "flex", alignItems: "center", gap: 6, color: "#536471", fontSize: 13 }}>
        <Icon name={icon} size={17} color="#536471" />{val}
      </span>
    );
    return (
      <div style={{ display: "flex", justifyContent: "space-between", maxWidth: 340, marginTop: 12 }}>
        {item("message-circle", 12)}{item("repeat-2", 8)}{item("heart", 47)}{item("bar-chart-2", "2.1K")}{item("bookmark", "")}
      </div>
    );
  }

  function Head({ meta, time }) {
    return (
      <div style={{ display: "flex", gap: 4, alignItems: "center", minWidth: 0 }}>
        <span style={{ fontWeight: 700, color: "#0F1419", fontSize: 15, whiteSpace: "nowrap" }}>{meta.name}</span>
        <Icon name="badge-check" size={16} color="#1D9BF0" />
        <span style={{ color: "#536471", fontSize: 15, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{meta.handle} · {time}</span>
      </div>
    );
  }

  function Body({ text }) {
    return <div style={{ color: "#0F1419", fontSize: 15, lineHeight: 1.4, whiteSpace: "pre-wrap", wordBreak: "break-word", marginTop: 2 }}>{text || <span style={{ color: "#AAB8C2" }}>Your post text will appear here…</span>}</div>;
  }

  function PreviewX({ post, channel }) {
    const meta = D.CHANNELS[channel] || D.CHANNELS.x_cropr;
    const variant = (post.content || []).find((v) => v.channel === channel) || { body: "", threadParts: null };
    const media = window.firstVariantMedia ? window.firstVariantMedia(post, variant) : post.media;
    const parts = Array.isArray(variant.threadParts) ? variant.threadParts.filter((p) => (p || "").trim().length) : [];
    const isThread = (variant.format === "series") && parts.length > 0;
    const over = window.CroprRules.countChars(variant.body) > 280;

    const shell = { fontFamily: SYS, background: "#fff", border: "1px solid #EFF3F4", borderRadius: 16, padding: 16, maxWidth: 512, boxShadow: "var(--shadow-sm)" };
    const AvatarX = () => <Avatar color={meta.avatar} initials={meta.initials} src={meta.icon} size={44} />;

    if (variant.format === "article") {
      const a = variant.article || { title: "", body: "" };
      return (
        <div style={shell}>
          <div style={{ display: "flex", gap: 12, marginBottom: 10 }}>
            <AvatarX />
            <div><Head meta={meta} time="2h" /><span style={{ fontSize: 12.5, color: "#536471" }}>published an Article</span></div>
          </div>
          <div style={{ border: "1px solid #EFF3F4", borderRadius: 14, overflow: "hidden" }}>
            <div style={{ aspectRatio: "2 / 1", background: "linear-gradient(135deg,#38BDF8,#FCA5A5)", display: "grid", placeItems: "end start", padding: 16 }}>
              <span style={{ color: "#fff", fontSize: 18, fontWeight: 800, lineHeight: 1.2, textShadow: "0 1px 8px rgba(0,0,0,.25)" }}>{a.title || "Untitled article"}</span>
            </div>
            <div style={{ padding: 14, fontSize: 14, lineHeight: 1.5, color: "#0F1419", whiteSpace: "pre-wrap", maxHeight: 220, overflow: "hidden", position: "relative" }}>
              {a.body || <span style={{ color: "#AAB8C2" }}>Article body…</span>}
            </div>
          </div>
        </div>
      );
    }

    if (isThread) {
      return (
        <div style={shell}>
          {parts.map((p, i) => (
            <div key={i} style={{ display: "flex", gap: 12 }}>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                <AvatarX />
                {i < parts.length - 1 && <div style={{ flex: 1, width: 2, background: "#CFD9DE", marginTop: 4 }} />}
              </div>
              <div style={{ minWidth: 0, flex: 1, paddingBottom: i < parts.length - 1 ? 14 : 0 }}>
                <Head meta={meta} time={i === 0 ? "2h" : ""} />
                <Body text={p} />
                {i === 0 && <XMedia media={media} />}
                <div style={{ display: "flex", justifyContent: "space-between", maxWidth: 200, marginTop: 8 }}>
                  <span style={{ color: "#536471", fontSize: 12.5 }}>{i + 1}/{parts.length}</span>
                  <span style={{ color: window.CroprRules.countChars(p) > 280 ? "#F4212E" : "#8899A6", fontSize: 12.5 }}>{window.CroprRules.countChars(p)}/280</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      );
    }

    return (
      <div style={shell}>
        <div style={{ display: "flex", gap: 12 }}>
          <AvatarX />
          <div style={{ minWidth: 0, flex: 1 }}>
            <Head meta={meta} time="2h" />
            <Body text={variant.body} />
            <XMedia media={media} />
            <Actions />
            <div style={{ marginTop: 10, paddingTop: 8, borderTop: "1px solid #F0F3F4", display: "flex", justifyContent: "flex-end" }}>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: over ? "#F4212E" : "#536471" }}>{window.CroprRules.countChars(variant.body)} / 280</span>
            </div>
          </div>
        </div>
      </div>
    );
  }
  window.PreviewX = PreviewX;
})();
