// Phone preview column — intentional, sticky, never overlapping. (preview.jsx)
// Ported from the coral redesign; brand gradient + handle wired to live data.

function fitAspect(fit) {
  return ({ square: "1 / 1", portrait: "4 / 5", vertical: "9 / 16", original: "1 / 1" }[fit] || "1 / 1");
}
function truncatePreview(text, max = 110) {
  const clean = String(text || "").replace(/\s+/g, " ").trim();
  return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
}

function PhoneFrame({ device, children }) {
  return (
    <div className={`cp-phone ${device === "android" ? "android" : ""}`}>
      <div className="cp-phone-screen">
        <div className="cp-phone-notch" />
        {children}
      </div>
    </div>
  );
}

function StatusBar({ dark }) {
  const color = dark ? "#fff" : "#0a0a0a";
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "11px 18px 4px", fontSize: 11, fontWeight: 600, color, position: "relative", zIndex: 5 }}>
      <span>9:41</span>
      <span style={{ display: "inline-flex", gap: 4, alignItems: "center" }}>
        <svg width="13" height="9" viewBox="0 0 13 9" fill="currentColor"><rect x="0" y="6" width="2" height="3" rx="0.5"/><rect x="3" y="4" width="2" height="5" rx="0.5"/><rect x="6" y="2" width="2" height="7" rx="0.5"/><rect x="9" y="0" width="2" height="9" rx="0.5"/></svg>
        <svg width="16" height="8" viewBox="0 0 16 8" fill="none"><rect x="0.5" y="0.5" width="13" height="7" rx="1.5" stroke="currentColor" opacity="0.5"/><rect x="2" y="2" width="9" height="4" rx="0.5" fill="currentColor"/><rect x="14" y="2.5" width="1.5" height="3" rx="0.5" fill="currentColor" opacity="0.5"/></svg>
      </span>
    </div>
  );
}

function PreviewMedia({ media, fit, dark }) {
  const objectFit = fit === "original" ? "contain" : "cover";
  if (media && media.src && media.type === "image") {
    return <img src={media.src} alt="" style={{ width: "100%", height: "100%", objectFit, display: "block" }} />;
  }
  if (media && media.src && media.type === "video") {
    // Show the actual video (muted, inline) so the first frame previews like the
    // post will look. metadata preload keeps it light; controls let the user scrub.
    return <video src={media.src} muted playsInline preload="metadata" controls
      style={{ width: "100%", height: "100%", objectFit, display: "block", background: "#000" }} />;
  }
  return (
    <div style={{ width: "100%", height: "100%", background: media?.bg || "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "grid", placeItems: "center" }}>
      <div style={{ textAlign: "center", color: "rgba(255,255,255,0.9)" }}>
        <Icon.Image width="30" height="30" />
        <div style={{ fontSize: 9, marginTop: 4, fontFamily: "'JetBrains Mono', monospace" }}>{media?.name || "media"}</div>
      </div>
    </div>
  );
}

// Feed preview dispatches to a platform-accurate layout for the networks we
// really publish to; everything else falls back to a generic feed card.
function FeedPreview(props) {
  if (props.platform === "mastodon") return <MastodonFeedPreview {...props} />;
  if (props.platform === "x") return <XFeedPreview {...props} />;
  return <GenericFeedPreview {...props} />;
}

// Instagram/Facebook-style card (used for IG, FB, and any platform without a
// dedicated layout). No fabricated like counts — this is a compose preview.
function GenericFeedPreview({ platform, caption, media, fit, handle, avatarLetter }) {
  const platformName = Platforms[platform]?.name || "Instagram";
  return (
    <div style={{ background: "white", color: "#0a0a0a", height: "100%", display: "flex", flexDirection: "column" }}>
      <StatusBar />
      <div style={{ padding: "8px 14px", display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ width: 28, height: 28, borderRadius: 999, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "grid", placeItems: "center", color: "var(--on-accent)", fontSize: 11, fontWeight: 800 }}>{avatarLetter || "C"}</div>
        <div style={{ flex: 1, lineHeight: 1.15 }}>
          <div style={{ fontWeight: 700, fontSize: 12 }}>{handle || "yourbrand"}</div>
          <div style={{ fontSize: 10, color: "#666" }}>{platformName} · preview</div>
        </div>
        <Icon.Dots width="16" height="16" />
      </div>
      <div style={{ position: "relative", width: "100%", aspectRatio: fitAspect(fit), maxHeight: 300, background: "#f0ede8", overflow: "hidden" }}>
        <PreviewMedia media={media} fit={fit} />
      </div>
      <div style={{ padding: "9px 14px", display: "flex", gap: 14 }}>
        <Icon.Heart width="20" height="20" />
        <Icon.Message width="20" height="20" />
        <Icon.Share width="20" height="20" />
        <div style={{ marginLeft: "auto" }}><Icon.Bookmark width="20" height="20" /></div>
      </div>
      <div style={{ padding: "2px 14px 4px", fontSize: 11, lineHeight: 1.45 }}>
        <b>{handle || "yourbrand"}</b> {truncatePreview(caption) || <span style={{ color: "#999" }}>Your caption will appear here…</span>}
      </div>
      <div style={{ padding: "0 14px 12px", fontSize: 9.5, color: "#999", letterSpacing: 0.5 }}>PREVIEW · NOT YET PUBLISHED</div>
    </div>
  );
}

// Mastodon: avatar (rounded square) + display name + @user@instance, text first,
// media below, action row = reply / boost / favourite / bookmark / share.
function MastodonFeedPreview({ caption, media, fit, handle, avatarLetter }) {
  const hasMedia = media && (media.src || media.name);
  const h = handle || "yourbrand";
  return (
    <div style={{ background: "#fff", color: "#191b22", height: "100%", display: "flex", flexDirection: "column" }}>
      <StatusBar />
      <div style={{ padding: "12px 14px 0", display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ width: 40, height: 40, borderRadius: 10, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "grid", placeItems: "center", color: "#fff", fontSize: 15, fontWeight: 800, flexShrink: 0 }}>{avatarLetter || "C"}</div>
        <div style={{ flex: 1, lineHeight: 1.25, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 13 }}>{h}</div>
          <div style={{ fontSize: 11.5, color: "#606984", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>@{h}@mastodon.social</div>
        </div>
        <span style={{ fontSize: 11.5, color: "#606984" }}>now</span>
      </div>
      <div style={{ padding: "8px 14px 10px", fontSize: 13.5, lineHeight: 1.5 }}>
        {truncatePreview(caption, 400) || <span style={{ color: "#9aa0b3" }}>Your post will appear here…</span>}
      </div>
      {hasMedia && (
        <div style={{ margin: "0 14px", borderRadius: 12, overflow: "hidden", border: "1px solid #e1e3ea", aspectRatio: fitAspect(fit), maxHeight: 220 }}>
          <PreviewMedia media={media} fit={fit} />
        </div>
      )}
      <div style={{ marginTop: "auto", padding: "14px 24px", display: "flex", justifyContent: "space-between", color: "#606984" }}>
        <Icon.Reply width="18" height="18" />
        <Icon.Refresh width="18" height="18" />
        <Icon.Star width="18" height="18" />
        <Icon.Bookmark width="18" height="18" />
        <Icon.Share width="18" height="18" />
      </div>
    </div>
  );
}

// X (Twitter): avatar + name · @handle · time, text, media (rounded), action row
// = reply / repost / like / views / bookmark. No fabricated counts.
function XFeedPreview({ caption, media, fit, handle, avatarLetter }) {
  const hasMedia = media && (media.src || media.name);
  const h = handle || "yourbrand";
  // X "Lights out" dark theme.
  return (
    <div style={{ background: "#000", color: "#e7e9ea", height: "100%", display: "flex", flexDirection: "column" }}>
      <StatusBar dark />
      <div style={{ padding: "12px 14px", display: "flex", gap: 10 }}>
        <div style={{ width: 40, height: 40, borderRadius: 999, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "grid", placeItems: "center", color: "#fff", fontSize: 15, fontWeight: 800, flexShrink: 0 }}>{avatarLetter || "C"}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 13 }}>
            <b style={{ color: "#e7e9ea" }}>{h}</b>
            <span style={{ color: "#71767b", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>@{h} · now</span>
            <Icon.Dots width="15" height="15" style={{ marginLeft: "auto", color: "#71767b", flexShrink: 0 }} />
          </div>
          <div style={{ fontSize: 13.5, lineHeight: 1.45, margin: "3px 0 8px", color: "#e7e9ea" }}>
            {truncatePreview(caption, 280) || <span style={{ color: "#71767b" }}>Your post will appear here…</span>}
          </div>
          {hasMedia && (
            <div style={{ borderRadius: 16, overflow: "hidden", border: "1px solid #2f3336", aspectRatio: fitAspect(fit), maxHeight: 200 }}>
              <PreviewMedia media={media} fit={fit} />
            </div>
          )}
          <div style={{ display: "flex", justifyContent: "space-between", color: "#71767b", marginTop: 12, paddingRight: 6 }}>
            <Icon.Message width="17" height="17" />
            <Icon.Refresh width="17" height="17" />
            <Icon.Heart width="17" height="17" />
            <Icon.Bar width="17" height="17" />
            <Icon.Bookmark width="17" height="17" />
          </div>
        </div>
      </div>
    </div>
  );
}

function StoryPreview({ platform, caption, media, fit, handle, avatarLetter }) {
  const platformName = Platforms[platform]?.name || "Instagram";
  return (
    <div style={{ height: "100%", background: media?.bg || "linear-gradient(135deg, var(--accent), var(--accent-2))", color: "white", display: "flex", flexDirection: "column", position: "relative" }}>
      <div style={{ position: "absolute", inset: 0 }}><PreviewMedia media={media} fit="vertical" dark /></div>
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(0,0,0,0.28), rgba(0,0,0,0.06) 40%, rgba(0,0,0,0.55))" }} />
      <StatusBar dark />
      <div style={{ position: "relative", zIndex: 2, padding: "2px 14px 0", display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ width: 26, height: 26, borderRadius: 999, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "grid", placeItems: "center", color: "var(--on-accent)", fontSize: 10, fontWeight: 800 }}>{avatarLetter || "C"}</div>
        <span style={{ fontSize: 12, fontWeight: 600 }}>{handle || "yourbrand"}</span>
        <span style={{ fontSize: 11, opacity: 0.7 }}>{platformName}</span>
        <Icon.X width="18" height="18" style={{ marginLeft: "auto" }} />
      </div>
      <div style={{ position: "relative", zIndex: 2, margin: "auto 0", padding: "0 18px", textAlign: "center" }}>
        <div style={{ fontSize: 12.5, lineHeight: 1.5, opacity: 0.96, textShadow: "0 1px 8px rgba(0,0,0,0.4)" }}>{truncatePreview(caption, 90)}</div>
      </div>
      <div style={{ position: "relative", zIndex: 2, padding: "12px 14px", display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ flex: 1, padding: "8px 14px", border: "1.5px solid rgba(255,255,255,0.55)", borderRadius: 999, fontSize: 11 }}>Send message</div>
        <Icon.Heart width="20" height="20" />
        <Icon.Share width="20" height="20" />
      </div>
    </div>
  );
}

function ReelPreview({ platform, caption, media, handle, avatarLetter }) {
  const platformName = Platforms[platform]?.name || "Instagram";
  return (
    <div style={{ height: "100%", background: media?.bg || "linear-gradient(135deg, var(--accent), var(--accent-2))", color: "white", display: "flex", flexDirection: "column", position: "relative" }}>
      <div style={{ position: "absolute", inset: 0 }}><PreviewMedia media={media} fit="vertical" dark /></div>
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(0,0,0,0.25), transparent 30%, transparent 55%, rgba(0,0,0,0.65))" }} />
      <StatusBar dark />
      <div style={{ position: "relative", zIndex: 2, padding: "2px 14px 0", display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ fontSize: 13, fontWeight: 700 }}>Reels</span>
        <Icon.Dots width="16" height="16" style={{ marginLeft: "auto" }} />
      </div>
      {/* right action rail */}
      <div style={{ position: "absolute", right: 10, bottom: 96, zIndex: 3, display: "flex", flexDirection: "column", alignItems: "center", gap: 16 }}>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2 }}><Icon.Heart width="24" height="24" /><span style={{ fontSize: 10 }}>Like</span></div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2 }}><Icon.Message width="24" height="24" /><span style={{ fontSize: 10 }}>Reply</span></div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2 }}><Icon.Share width="24" height="24" /><span style={{ fontSize: 10 }}>Share</span></div>
        <Icon.Bookmark width="24" height="24" />
        <Icon.Dots width="22" height="22" />
      </div>
      {/* bottom caption */}
      <div style={{ position: "relative", zIndex: 2, marginTop: "auto", padding: "0 56px 16px 14px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
          <div style={{ width: 26, height: 26, borderRadius: 999, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "grid", placeItems: "center", color: "var(--on-accent)", fontSize: 10, fontWeight: 800, border: "1.5px solid #fff" }}>{avatarLetter || "C"}</div>
          <span style={{ fontSize: 12.5, fontWeight: 700 }}>{handle || "yourbrand"}</span>
          <span style={{ fontSize: 11, opacity: 0.8 }}>· {platformName}</span>
        </div>
        <div style={{ fontSize: 12, lineHeight: 1.45, textShadow: "0 1px 6px rgba(0,0,0,0.4)" }}>{truncatePreview(caption, 90) || <span style={{ opacity: 0.7 }}>Your caption will appear here…</span>}</div>
      </div>
    </div>
  );
}

function PreviewColumn(props) {
  const { selectedPlatforms, activePreviewPlatform, setActivePreviewPlatform,
          previewFormat, setPreviewFormat, previewDevice, setPreviewDevice,
          caption, media, fit, captionSource, handle, avatarLetter } = props;
  const isStory = previewFormat !== "feed";
  const fitForFormat = isStory ? "vertical" : fit;

  return (
    <div className="cp-preview">
      <div className="cp-preview-head">
        <div className="cp-pv-title"><Icon.Eye width="15" height="15" /> Live preview</div>
        <span className="cp-pv-live"><span className="cp-pv-pulse" /> Updating</span>
      </div>

      <div className="cp-pv-card">
        <div className="cp-pv-pfrow">
          {selectedPlatforms.length === 0 && <span className="faint" style={{ fontSize: 12 }}>Select a channel to preview</span>}
          {selectedPlatforms.map((id) => (
            <button key={id} className={`cp-pv-pf ${activePreviewPlatform === id ? "active" : ""}`} onClick={() => setActivePreviewPlatform(id)} title={Platforms[id]?.name}>
              <PlatformIcon id={id} size={20} />
            </button>
          ))}
        </div>

        <div className="cp-pv-controls">
          <div className="cp-seg">
            <button className={previewFormat === "feed" ? "active" : ""} onClick={() => setPreviewFormat("feed")}>Feed</button>
            <button className={previewFormat === "story" ? "active" : ""} onClick={() => setPreviewFormat("story")}>Story</button>
            <button className={previewFormat === "reel" ? "active" : ""} onClick={() => setPreviewFormat("reel")}>Reel</button>
          </div>
          <div className="cp-seg">
            <button className={previewDevice === "ios" ? "active" : ""} onClick={() => setPreviewDevice("ios")}>iOS</button>
            <button className={previewDevice === "android" ? "active" : ""} onClick={() => setPreviewDevice("android")}>Android</button>
          </div>
        </div>

        <div className="cp-phone-stage">
          <PhoneFrame device={previewDevice}>
            {previewFormat === "feed"
              ? <FeedPreview platform={activePreviewPlatform} caption={caption} media={media} fit={fitForFormat} handle={handle} avatarLetter={avatarLetter} />
              : previewFormat === "reel"
              ? <ReelPreview platform={activePreviewPlatform} caption={caption} media={media} handle={handle} avatarLetter={avatarLetter} />
              : <StoryPreview platform={activePreviewPlatform} caption={caption} media={media} fit={fitForFormat} handle={handle} avatarLetter={avatarLetter} />}
          </PhoneFrame>
        </div>

        <div className="cp-pv-summary">
          <div className="cp-pv-summary-row"><span className="muted">Channel</span><b>{Platforms[activePreviewPlatform]?.name || "—"}</b></div>
          <div className="cp-pv-summary-row"><span className="muted">Caption</span><b>{captionSource}</b></div>
          <div className="cp-pv-summary-row"><span className="muted">Media fit</span><b>{fitForFormat}</b></div>
        </div>
      </div>
    </div>
  );
}

window.PreviewColumn = PreviewColumn;
