
// screens-create-post.jsx — BoltKit Create Post Wizard (6 steps)
// Babel standalone, no ES module imports. All deps are globals.

const GOALS = [
  { id: "awareness",  label: "Build Awareness",    icon: "layers",      desc: "Reach new people and introduce your brand" },
  { id: "traffic",    label: "Drive Traffic",       icon: "arrow_right", desc: "Get people to your website or profile" },
  { id: "leads",      label: "Generate Leads",      icon: "plus",        desc: "Capture interest and contact details" },
  { id: "engagement", label: "Boost Engagement",    icon: "copy",        desc: "Drive likes, comments, saves and shares" },
  { id: "offer",      label: "Promote Offer",       icon: "sparkle",     desc: "Sell a product, service or deal" },
  { id: "trust",      label: "Build Trust",         icon: "check",       desc: "Social proof, testimonials and authority" },
];

const POST_TYPES = [
  { id: "coming-soon",    label: "Coming Soon",       prompt: "Mysterious dramatic teaser with strong anticipation" },
  { id: "product-launch", label: "Product Launch",    prompt: "Bold clean product hero reveal" },
  { id: "behind-scenes",  label: "Behind the Scenes", prompt: "Authentic candid moment showing real team or process" },
  { id: "social-proof",   label: "Social Proof",      prompt: "Clean powerful testimonial or results graphic" },
  { id: "how-it-works",   label: "How It Works",      prompt: "Clean minimal explainer showing a process" },
  { id: "event",          label: "Event",             prompt: "High-energy event announcement" },
  { id: "lifestyle",      label: "Lifestyle",         prompt: "Premium aspirational lifestyle moment" },
  { id: "offer",          label: "Offer / Deal",      prompt: "Bold limited-time offer with urgency" },
];

const IG_FORMATS = [
  { id: "story",    label: "Reels",  ratio: "9:16", dalle: "story",    aspect: "9/16" },
  { id: "portrait", label: "Post",   ratio: "4:5",  dalle: "portrait", aspect: "4/5"  },
  { id: "square",   label: "Square", ratio: "1:1",  dalle: "square",   aspect: "1/1"  },
];

const DEFAULT_PILLARS = [
  { id: "education",   name: "Education",         color: "#EFFF00" },
  { id: "inspiration", name: "Inspiration",        color: "#4ADE80" },
  { id: "behind",      name: "Behind the Scenes",  color: "#60A5FA" },
  { id: "promotion",   name: "Promotion",          color: "#F97316" },
  { id: "community",   name: "Community",          color: "#A78BFA" },
  { id: "authority",   name: "Authority",          color: "#F472B6" },
];

const STEP_LABELS = ["Goal", "Pillar", "Type", "Ideas", "Image", "Caption"];

// ─── Design tokens ────────────────────────────────────────────────────────────
const C = {
  bg:      "#1A1813",
  card:    "#201E18",
  card2:   "#26241E",
  border:  "#3A372F",
  accent:  "#EFFF00",
  text:    "#F4F4F0",
  muted:   "#C8C8C5",
  vmuted:  "#5C5C5C",
  error:   "#FF4D5E",
  success: "#4ADE80",
};

const fontHead = { fontFamily: "'Anton', Impact, sans-serif", textTransform: "uppercase" };
const fontMono = { fontFamily: "'JetBrains Mono', monospace" };

// ─── Button style helpers ─────────────────────────────────────────────────────
function backBtnStyle() {
  return {
    background: C.card2, color: C.muted,
    border: `1px solid ${C.border}`, borderRadius: 8,
    padding: "11px 22px",
    ...fontMono, fontSize: 11, fontWeight: 700,
    letterSpacing: "0.1em", cursor: "pointer",
  };
}

function nextBtnStyle(enabled) {
  return {
    background: enabled ? C.accent : C.card2,
    color: enabled ? C.bg : C.vmuted,
    border: "none", borderRadius: 8, padding: "11px 28px",
    ...fontMono, fontSize: 11, fontWeight: 700, letterSpacing: "0.1em",
    cursor: enabled ? "pointer" : "not-allowed",
    display: "flex", alignItems: "center", gap: 8,
    transition: "background 0.15s, color 0.15s",
  };
}

// ─── StepIndicator ────────────────────────────────────────────────────────────
function StepIndicator({ step, onBack }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 0 }}>
      {STEP_LABELS.map((label, i) => {
        const done   = i < step;
        const active = i === step;
        const locked = i > step;
        return (
          <React.Fragment key={i}>
            <div
              onClick={() => done && onBack(i)}
              style={{
                display: "flex", alignItems: "center", gap: 8,
                cursor: done ? "pointer" : "default",
                opacity: locked ? 0.35 : 1,
                transition: "opacity 0.2s",
              }}
            >
              <div style={{
                width: 28, height: 28, borderRadius: "50%",
                display: "flex", alignItems: "center", justifyContent: "center",
                background: done ? C.accent : active ? C.accent : C.card2,
                border: `2px solid ${active ? C.accent : done ? C.accent : C.border}`,
                flexShrink: 0,
              }}>
                {done
                  ? <Icon name="check" size={12} stroke={2.5} color={C.bg} />
                  : <span style={{ ...fontMono, fontSize: 11, color: active ? C.bg : C.vmuted, fontWeight: 700 }}>{i + 1}</span>
                }
              </div>
              <span style={{
                ...fontMono, fontSize: 10, letterSpacing: "0.08em",
                color: active ? C.accent : done ? C.muted : C.vmuted,
                fontWeight: active ? 700 : 400,
                whiteSpace: "nowrap",
              }}>{label.toUpperCase()}</span>
            </div>
            {i < STEP_LABELS.length - 1 && (
              <div style={{
                flex: 1, height: 1,
                background: i < step ? C.accent : C.border,
                margin: "0 10px", minWidth: 16,
                transition: "background 0.3s",
              }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ─── PostPreviewCard ──────────────────────────────────────────────────────────
function PostPreviewCard({ format, imageUrl, idea, caption }) {
  const aspect = format ? format.aspect : "4/5";
  const previewText = caption ? caption.caption : (idea ? idea.hook : null);
  const tags = caption ? (caption.hashtags || []) : (idea ? (idea.suggestedHashtags || []) : []);

  return (
    <div style={{
      background: C.card,
      border: `1px solid ${C.border}`,
      borderRadius: 12,
      overflow: "hidden",
      width: "100%",
    }}>
      <div style={{
        padding: "10px 14px",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        borderBottom: `1px solid ${C.border}`,
      }}>
        <span style={{ ...fontMono, fontSize: 10, color: C.vmuted, letterSpacing: "0.1em" }}>INSTAGRAM PREVIEW</span>
        {format && (
          <span style={{
            ...fontMono, fontSize: 9, color: C.accent,
            background: "rgba(239,255,0,0.08)",
            border: "1px solid rgba(239,255,0,0.2)",
            borderRadius: 4, padding: "2px 8px", letterSpacing: "0.1em",
          }}>{format.label.toUpperCase()} {format.ratio}</span>
        )}
      </div>

      <div style={{ padding: "12px 12px 0" }}>
        <div style={{
          aspectRatio: aspect,
          background: C.card2, borderRadius: 8,
          overflow: "hidden",
          display: "flex", alignItems: "center", justifyContent: "center",
          border: `1px solid ${C.border}`,
        }}>
          {imageUrl
            ? <img src={imageUrl} alt="Generated post" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            : (
              <div style={{ textAlign: "center", padding: 20 }}>
                <Icon name="image" size={28} stroke={1.5} color={C.vmuted} />
                <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, marginTop: 8, letterSpacing: "0.08em" }}>IMAGE PREVIEW</div>
              </div>
            )
          }
        </div>
      </div>

      <div style={{ padding: "10px 14px 14px" }}>
        {idea && idea.hook && (
          <p style={{
            fontSize: 12, fontWeight: 700, color: C.text,
            margin: "0 0 6px", lineHeight: 1.4,
            display: "-webkit-box", WebkitLineClamp: 2,
            WebkitBoxOrient: "vertical", overflow: "hidden",
          }}>{idea.hook}</p>
        )}
        {previewText && idea && previewText !== idea.hook && (
          <p style={{
            fontSize: 11, color: C.muted, margin: "0 0 8px", lineHeight: 1.5,
            display: "-webkit-box", WebkitLineClamp: 3,
            WebkitBoxOrient: "vertical", overflow: "hidden",
          }}>{previewText}</p>
        )}
        {tags.length > 0 && (
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 6 }}>
            {tags.slice(0, 5).map((t, i) => (
              <span key={i} style={{
                ...fontMono, fontSize: 9,
                color: C.accent, background: "rgba(239,255,0,0.06)",
                border: "1px solid rgba(239,255,0,0.15)",
                borderRadius: 3, padding: "2px 6px",
              }}>#{String(t).replace(/^#/, "")}</span>
            ))}
            {tags.length > 5 && (
              <span style={{ ...fontMono, fontSize: 9, color: C.vmuted }}>+{tags.length - 5}</span>
            )}
          </div>
        )}
        {!idea && !previewText && (
          <p style={{ ...fontMono, fontSize: 9, color: C.vmuted, margin: 0, letterSpacing: "0.06em" }}>
            SELECT AN IDEA TO PREVIEW
          </p>
        )}
      </div>
    </div>
  );
}

// ─── Step 1: Goal ─────────────────────────────────────────────────────────────
function StepGoal({ goal, setGoal, onNext }) {
  return (
    <div>
      <div style={{ marginBottom: 28 }}>
        <h2 style={{ ...fontHead, fontSize: 22, color: C.text, margin: "0 0 8px" }}>
          What's your goal for this post?
        </h2>
        <p style={{ fontSize: 14, color: C.muted, margin: 0 }}>
          Choose the primary business objective this post should achieve.
        </p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
        {GOALS.map(g => {
          const selected = goal && goal.id === g.id;
          return (
            <div
              key={g.id}
              onClick={() => setGoal(g)}
              style={{
                background: selected ? "rgba(239,255,0,0.06)" : C.card2,
                border: `1.5px solid ${selected ? C.accent : C.border}`,
                borderRadius: 10, padding: "16px 14px",
                cursor: "pointer",
                transition: "border-color 0.15s, background 0.15s",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <Icon name={g.icon} size={14} stroke={2} color={selected ? C.accent : C.muted} />
                <span style={{ ...fontMono, fontSize: 10, letterSpacing: "0.08em", color: selected ? C.accent : C.text, fontWeight: 700 }}>
                  {g.label.toUpperCase()}
                </span>
              </div>
              <p style={{ fontSize: 12, color: C.muted, margin: 0, lineHeight: 1.5 }}>{g.desc}</p>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 28, display: "flex", justifyContent: "flex-end" }}>
        <button
          data-bk-bound="true"
          onClick={onNext}
          disabled={!goal}
          style={nextBtnStyle(!!goal)}
        >
          NEXT <Icon name="arrow_right" size={12} stroke={2.5} color={goal ? C.bg : C.vmuted} />
        </button>
      </div>
    </div>
  );
}

// ─── Step 2: Pillar ───────────────────────────────────────────────────────────
function StepPillar({ pillar, setPillar, onNext, onBack }) {
  const stored = (() => { try { return JSON.parse(localStorage.getItem("boltkit.pillars.v1") || "[]"); } catch { return []; } })();
  const displayPillars = stored.length > 0 ? stored : DEFAULT_PILLARS;

  return (
    <div>
      <div style={{ marginBottom: 28 }}>
        <h2 style={{ ...fontHead, fontSize: 22, color: C.text, margin: "0 0 8px" }}>
          Which content pillar?
        </h2>
        <p style={{ fontSize: 14, color: C.muted, margin: 0 }}>
          Align this post to a content pillar from your strategy.
        </p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
        {displayPillars.map((p, i) => {
          const selected = pillar && (pillar.id === p.id || pillar.name === p.name);
          const color = p.color || ["#EFFF00","#4ADE80","#60A5FA","#F97316","#A78BFA","#F472B6"][i % 6];
          return (
            <div
              key={p.id || i}
              onClick={() => setPillar(p)}
              style={{
                background: selected ? `${color}10` : C.card2,
                border: `1.5px solid ${selected ? color : C.border}`,
                borderRadius: 10, padding: "16px 14px",
                cursor: "pointer",
                transition: "border-color 0.15s, background 0.15s",
              }}
            >
              <div style={{
                width: 6, height: 6, borderRadius: "50%",
                background: color, marginBottom: 10,
              }} />
              <div style={{
                ...fontMono, fontSize: 11, fontWeight: 700,
                color: selected ? color : C.text,
                letterSpacing: "0.06em",
              }}>{(p.name || p.label || "").toUpperCase()}</div>
              {p.description && (
                <p style={{ fontSize: 11, color: C.muted, margin: "6px 0 0", lineHeight: 1.4 }}>{p.description}</p>
              )}
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 28, display: "flex", justifyContent: "space-between" }}>
        <button data-bk-bound="true" onClick={onBack} style={backBtnStyle()}>BACK</button>
        <button data-bk-bound="true" onClick={onNext} disabled={!pillar} style={nextBtnStyle(!!pillar)}>
          NEXT <Icon name="arrow_right" size={12} stroke={2.5} color={pillar ? C.bg : C.vmuted} />
        </button>
      </div>
    </div>
  );
}

// ─── Step 3: Post Type ────────────────────────────────────────────────────────
function StepType({ postType, setPostType, onNext, onBack }) {
  return (
    <div>
      <div style={{ marginBottom: 28 }}>
        <h2 style={{ ...fontHead, fontSize: 22, color: C.text, margin: "0 0 8px" }}>
          What kind of post?
        </h2>
        <p style={{ fontSize: 14, color: C.muted, margin: 0 }}>
          Pick a post format — this shapes the visuals and messaging angle.
        </p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
        {POST_TYPES.map(pt => {
          const selected = postType && postType.id === pt.id;
          return (
            <div
              key={pt.id}
              onClick={() => setPostType(pt)}
              style={{
                background: selected ? "rgba(239,255,0,0.06)" : C.card2,
                border: `1.5px solid ${selected ? C.accent : C.border}`,
                borderRadius: 10, padding: "14px 12px",
                cursor: "pointer",
                transition: "border-color 0.15s, background 0.15s",
              }}
            >
              <div style={{
                ...fontMono, fontSize: 10, fontWeight: 700,
                color: selected ? C.accent : C.text,
                letterSpacing: "0.06em", marginBottom: 6,
              }}>{pt.label.toUpperCase()}</div>
              <p style={{ fontSize: 11, color: C.vmuted, margin: 0, lineHeight: 1.4 }}>{pt.prompt}</p>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 28, display: "flex", justifyContent: "space-between" }}>
        <button data-bk-bound="true" onClick={onBack} style={backBtnStyle()}>BACK</button>
        <button data-bk-bound="true" onClick={onNext} disabled={!postType} style={nextBtnStyle(!!postType)}>
          NEXT <Icon name="arrow_right" size={12} stroke={2.5} color={postType ? C.bg : C.vmuted} />
        </button>
      </div>
    </div>
  );
}

// ─── Step 4: Ideas ────────────────────────────────────────────────────────────
function StepIdeas({ ideas, setIdeas, selectedIdea, setSelectedIdea, loadingIdeas, setLoadingIdeas, goal, pillar, postType, onNext, onBack, project, brandBrain }) {
  const generateIdeas = async () => {
    setLoadingIdeas(true);
    try {
      const res = await fetch("/api/generate-post-ideas", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ project, brandBrain, goal: goal.id, pillar, postType: postType.id }),
      });
      const data = await res.json();
      setIdeas(data.ideas || []);
    } catch (e) {
      window.BoltKitToast && window.BoltKitToast({ msg: "Failed to generate ideas. Try again.", type: "error" });
    } finally {
      setLoadingIdeas(false);
    }
  };

  React.useEffect(() => {
    if (ideas.length === 0 && !loadingIdeas) generateIdeas();
  }, []);

  const scoreColor = (score) => {
    if (score >= 8) return C.success;
    if (score >= 5) return C.accent;
    return C.muted;
  };

  return (
    <div>
      <div style={{ marginBottom: 20, display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <div>
          <h2 style={{ ...fontHead, fontSize: 22, color: C.text, margin: "0 0 8px" }}>Choose a post idea</h2>
          <p style={{ fontSize: 14, color: C.muted, margin: 0 }}>
            AI-generated ideas based on your goal, pillar and post type.
          </p>
        </div>
        <button
          data-bk-bound="true"
          onClick={generateIdeas}
          disabled={loadingIdeas}
          style={{
            ...fontMono, fontSize: 10, fontWeight: 700,
            letterSpacing: "0.08em", color: C.accent,
            background: "rgba(239,255,0,0.08)",
            border: "1px solid rgba(239,255,0,0.2)",
            borderRadius: 7, padding: "8px 16px",
            cursor: loadingIdeas ? "not-allowed" : "pointer",
            display: "flex", alignItems: "center", gap: 6,
            opacity: loadingIdeas ? 0.6 : 1,
            whiteSpace: "nowrap", flexShrink: 0,
          }}
        >
          <Icon name="refresh" size={11} stroke={2} color={C.accent} />
          {loadingIdeas ? "GENERATING..." : "REGENERATE"}
        </button>
      </div>

      {loadingIdeas ? (
        <div style={{
          display: "flex", flexDirection: "column",
          alignItems: "center", justifyContent: "center",
          padding: "60px 20px", gap: 16,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: "50%",
            border: `3px solid ${C.border}`, borderTopColor: C.accent,
            animation: "spin 0.8s linear infinite",
          }} />
          <p style={{ ...fontMono, fontSize: 11, color: C.muted, letterSpacing: "0.08em" }}>
            GENERATING IDEAS...
          </p>
        </div>
      ) : ideas.length === 0 ? (
        <div style={{
          border: `1px dashed ${C.border}`, borderRadius: 12,
          padding: "60px 20px", textAlign: "center",
        }}>
          <Icon name="brain" size={28} stroke={1.5} color={C.vmuted} />
          <p style={{ ...fontMono, fontSize: 11, color: C.vmuted, marginTop: 12, letterSpacing: "0.08em" }}>
            NO IDEAS YET
          </p>
          <button
            data-bk-bound="true"
            onClick={generateIdeas}
            style={{
              marginTop: 16, background: C.accent, color: C.bg,
              border: "none", borderRadius: 8, padding: "10px 24px",
              ...fontMono, fontSize: 11, fontWeight: 700,
              letterSpacing: "0.1em", cursor: "pointer",
              display: "inline-flex", alignItems: "center", gap: 8,
            }}
          >
            <Icon name="sparkle" size={12} stroke={2} color={C.bg} />
            GENERATE IDEAS
          </button>
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {ideas.map((idea, i) => {
            const sel = selectedIdea === idea;
            return (
              <div
                key={i}
                onClick={() => setSelectedIdea(idea)}
                style={{
                  background: sel ? "rgba(239,255,0,0.05)" : C.card2,
                  border: `1.5px solid ${sel ? C.accent : C.border}`,
                  borderRadius: 10, padding: "16px",
                  cursor: "pointer",
                  transition: "border-color 0.15s, background 0.15s",
                }}
              >
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 8 }}>
                  <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em" }}>IDEA {i + 1}</div>
                  {idea.salesIntentScore != null && (
                    <div style={{
                      ...fontMono, fontSize: 9, fontWeight: 700,
                      color: scoreColor(idea.salesIntentScore),
                      background: `${scoreColor(idea.salesIntentScore)}15`,
                      border: `1px solid ${scoreColor(idea.salesIntentScore)}30`,
                      borderRadius: 4, padding: "2px 7px", letterSpacing: "0.08em",
                    }}>INTENT {idea.salesIntentScore}/10</div>
                  )}
                </div>
                <p style={{
                  fontSize: 13, fontWeight: 700, color: C.text,
                  margin: "0 0 8px", lineHeight: 1.4,
                }}>{idea.hook}</p>
                {idea.visualConcept && (
                  <p style={{
                    fontSize: 11, color: C.muted, margin: "0 0 8px", lineHeight: 1.5,
                    display: "-webkit-box", WebkitLineClamp: 2,
                    WebkitBoxOrient: "vertical", overflow: "hidden",
                  }}>{idea.visualConcept}</p>
                )}
                {idea.audienceReason && (
                  <p style={{
                    fontSize: 10, color: C.vmuted, margin: "0 0 8px", lineHeight: 1.4,
                    fontStyle: "italic",
                  }}>{idea.audienceReason}</p>
                )}
                {idea.captionAngle && (
                  <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.06em" }}>
                    ANGLE: {idea.captionAngle}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      <div style={{ marginTop: 28, display: "flex", justifyContent: "space-between" }}>
        <button data-bk-bound="true" onClick={onBack} style={backBtnStyle()}>BACK</button>
        <button data-bk-bound="true" onClick={onNext} disabled={!selectedIdea} style={nextBtnStyle(!!selectedIdea)}>
          NEXT <Icon name="arrow_right" size={12} stroke={2.5} color={selectedIdea ? C.bg : C.vmuted} />
        </button>
      </div>
    </div>
  );
}

// ─── Step 5: Image ────────────────────────────────────────────────────────────
function StepImage({ format, setFormat, customPrompt, setCustomPrompt, imageUrl, setImageUrl, generatingImage, setGeneratingImage, selectedIdea, postType, project, onNext, onBack }) {
  const buildImagePrompt = () => {
    let bb = null;
    try { bb = JSON.parse(localStorage.getItem("boltkit.brandBrain.v1") || "null"); } catch {}

    const parts = [];
    // Image brief is the master brand control — goes first
    if (bb?.imageBrief) parts.push("BRAND IDENTITY: " + bb.imageBrief);
    if (postType && postType.prompt) parts.push(postType.prompt);
    if (selectedIdea && selectedIdea.visualConcept) parts.push(selectedIdea.visualConcept);
    if (project && project.name) parts.push("Brand: " + project.name);
    if (project && project.description) parts.push(String(project.description).slice(0, 120));
    // Colours + typography — only if no imageBrief (which already contains this)
    if (!bb?.imageBrief) {
      if (bb?.primary)   parts.push("Primary brand colour: " + bb.primary);
      if (bb?.secondary) parts.push("Secondary colour: " + bb.secondary);
      if (bb?.accent)    parts.push("Accent colour: " + bb.accent);
      if (bb?.typography) parts.push("Typography: " + bb.typography);
      if (bb?.brand_voice || bb?.brandVoice) parts.push("Brand voice: " + String(bb.brand_voice || bb.brandVoice).slice(0, 80));
    }
    parts.push("Format: " + format.ratio + " Instagram " + format.label);
    parts.push("High quality, photorealistic. Strictly maintain brand identity throughout.");
    return parts.join(". ");
  };

  const generateImage = async () => {
    setGeneratingImage(true);
    const imagePrompt = customPrompt || buildImagePrompt();
    try {
      const res = await fetch("/api/generate-image", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ prompt: imagePrompt, size: format.dalle, styleHint: postType ? postType.id : null }),
      });
      const data = await res.json();
      if (data.ok && data.imageUrl) setImageUrl(data.imageUrl);
      else throw new Error(data.error || "No image returned");
    } catch (e) {
      window.BoltKitToast && window.BoltKitToast({ msg: "Image generation failed: " + (e.message || "Try again."), type: "error" });
    } finally {
      setGeneratingImage(false);
    }
  };

  const spinnerStyle = {
    width: 14, height: 14, borderRadius: "50%",
    border: `2px solid ${C.vmuted}`, borderTopColor: C.muted,
    animation: "spin 0.8s linear infinite",
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ ...fontHead, fontSize: 22, color: C.text, margin: "0 0 8px" }}>
          Generate your image
        </h2>
        <p style={{ fontSize: 14, color: C.muted, margin: 0 }}>
          AI-generated visuals based on your idea. Customize the prompt if needed.
        </p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28, alignItems: "start" }}>
        {/* Left: controls */}
        <div>
          {selectedIdea && selectedIdea.visualConcept && (
            <div style={{
              background: C.card2, border: `1px solid ${C.border}`,
              borderRadius: 8, padding: "12px 14px", marginBottom: 16,
            }}>
              <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 6 }}>VISUAL CONCEPT</div>
              <p style={{ fontSize: 12, color: C.muted, margin: 0, lineHeight: 1.5 }}>{selectedIdea.visualConcept}</p>
            </div>
          )}

          {/* Format selector */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 8 }}>FORMAT</div>
            <div style={{ display: "flex", gap: 8 }}>
              {IG_FORMATS.map(f => {
                const sel = format && format.id === f.id;
                return (
                  <button
                    key={f.id}
                    data-bk-bound="true"
                    onClick={() => setFormat(f)}
                    style={{
                      ...fontMono, fontSize: 10, fontWeight: 700,
                      letterSpacing: "0.08em",
                      background: sel ? C.accent : C.card2,
                      color: sel ? C.bg : C.muted,
                      border: `1.5px solid ${sel ? C.accent : C.border}`,
                      borderRadius: 6, padding: "7px 14px",
                      cursor: "pointer",
                      transition: "all 0.15s",
                    }}
                  >{f.label.toUpperCase()} {f.ratio}</button>
                );
              })}
            </div>
          </div>

          {/* Custom prompt */}
          <div style={{ marginBottom: 20 }}>
            <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 8 }}>
              CUSTOM PROMPT (OPTIONAL)
            </div>
            <textarea
              value={customPrompt}
              onChange={e => setCustomPrompt(e.target.value)}
              placeholder={buildImagePrompt()}
              rows={4}
              style={{
                width: "100%", background: C.card2,
                border: `1px solid ${C.border}`,
                borderRadius: 8, padding: "10px 12px",
                color: C.text, fontSize: 12, lineHeight: 1.5,
                resize: "vertical", outline: "none",
                boxSizing: "border-box",
                fontFamily: "Inter, system-ui, sans-serif",
              }}
            />
            {customPrompt && (
              <button
                data-bk-bound="true"
                onClick={() => setCustomPrompt("")}
                style={{
                  ...fontMono, fontSize: 9, color: C.vmuted, background: "none",
                  border: "none", cursor: "pointer", marginTop: 4, padding: 0,
                  letterSpacing: "0.06em",
                }}
              >CLEAR OVERRIDE</button>
            )}
          </div>

          <button
            data-bk-bound="true"
            onClick={generateImage}
            disabled={generatingImage}
            style={{
              width: "100%",
              background: generatingImage ? C.card2 : C.accent,
              color: generatingImage ? C.vmuted : C.bg,
              border: "none", borderRadius: 8, padding: "12px",
              ...fontMono, fontSize: 11, fontWeight: 700,
              letterSpacing: "0.1em", cursor: generatingImage ? "not-allowed" : "pointer",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
              transition: "all 0.15s",
            }}
          >
            {generatingImage
              ? <><div style={spinnerStyle} />GENERATING IMAGE...</>
              : <><Icon name="image" size={13} stroke={2} color={C.bg} />{imageUrl ? "REGENERATE IMAGE" : "GENERATE IMAGE"}</>
            }
          </button>
        </div>

        {/* Right: image preview */}
        <div>
          <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 10 }}>PREVIEW</div>
          <div style={{
            aspectRatio: format ? format.aspect : "4/5",
            background: C.card2, borderRadius: 10,
            overflow: "hidden",
            display: "flex", alignItems: "center", justifyContent: "center",
            border: `1px solid ${C.border}`,
            maxHeight: 420,
            margin: "0 auto",
          }}>
            {imageUrl
              ? <img src={imageUrl} alt="Generated" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              : generatingImage
                ? (
                  <div style={{ textAlign: "center" }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: "50%",
                      border: `3px solid ${C.border}`, borderTopColor: C.accent,
                      animation: "spin 0.8s linear infinite",
                      margin: "0 auto 12px",
                    }} />
                    <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.08em" }}>GENERATING...</div>
                  </div>
                )
                : (
                  <div style={{ textAlign: "center", padding: 24 }}>
                    <Icon name="image" size={32} stroke={1.5} color={C.vmuted} />
                    <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, marginTop: 10, letterSpacing: "0.08em" }}>
                      IMAGE WILL APPEAR HERE
                    </div>
                  </div>
                )
            }
          </div>
        </div>
      </div>

      <div style={{ marginTop: 28, display: "flex", justifyContent: "space-between" }}>
        <button data-bk-bound="true" onClick={onBack} style={backBtnStyle()}>BACK</button>
        <button data-bk-bound="true" onClick={onNext} disabled={!imageUrl} style={nextBtnStyle(!!imageUrl)}>
          NEXT <Icon name="arrow_right" size={12} stroke={2.5} color={imageUrl ? C.bg : C.vmuted} />
        </button>
      </div>
    </div>
  );
}

// ─── Step 6: Caption + Review ─────────────────────────────────────────────────
function StepCaption({ caption, setCaption, generatingCaption, setGeneratingCaption, goal, pillar, postType, selectedIdea, imageUrl, format, project, saving, onSave, onBack }) {
  const [editCaption,  setEditCaption]  = React.useState(caption ? (caption.caption || "") : "");
  const [editHashtags, setEditHashtags] = React.useState(
    caption
      ? (caption.hashtags || []).map(h => "#" + String(h).replace(/^#/, "")).join(" ")
      : (selectedIdea && selectedIdea.suggestedHashtags ? selectedIdea.suggestedHashtags.map(h => "#" + String(h).replace(/^#/, "")).join(" ") : "")
  );
  const [editCta, setEditCta] = React.useState(
    caption ? (caption.cta || "") : (selectedIdea ? (selectedIdea.cta || "") : "")
  );

  React.useEffect(() => {
    if (caption) {
      setEditCaption(caption.caption || "");
      setEditHashtags((caption.hashtags || []).map(h => "#" + String(h).replace(/^#/, "")).join(" "));
      setEditCta(caption.cta || "");
    }
  }, [caption]);

  const generateCaption = async () => {
    setGeneratingCaption(true);
    const draftPost = {
      theme:         postType  ? postType.id  : null,
      hook:          selectedIdea ? selectedIdea.hook          : null,
      visualConcept: selectedIdea ? selectedIdea.visualConcept : null,
      cta:           selectedIdea ? selectedIdea.cta           : null,
      imageUrl,
      format: format ? format.id : null,
      goal:   goal   ? goal.id   : null,
      pillar: pillar ? pillar.name : null,
    };
    try {
      const res = await fetch("/api/generate-instagram-post", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ project, post: draftPost }),
      });
      const data = await res.json();
      setCaption(data);
    } catch (e) {
      window.BoltKitToast && window.BoltKitToast({ msg: "Caption generation failed.", type: "error" });
    } finally {
      setGeneratingCaption(false);
    }
  };

  const handleSave = () => {
    const tags = editHashtags.split(/\s+/).map(t => t.replace(/^#/, "")).filter(Boolean);
    const merged = Object.assign({}, caption, { caption: editCaption, hashtags: tags, cta: editCta });
    setCaption(merged);
    onSave(merged);
  };

  const tagCount = editHashtags.split(/\s+/).filter(Boolean).length;
  const previewCaption = caption
    ? Object.assign({}, caption, {
        caption: editCaption,
        hashtags: editHashtags.split(/\s+/).map(t => t.replace(/^#/, "")).filter(Boolean),
      })
    : null;

  const spinnerStyle = {
    width: 12, height: 12, borderRadius: "50%",
    border: `2px solid ${C.vmuted}`, borderTopColor: C.muted,
    animation: "spin 0.8s linear infinite",
  };

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <h2 style={{ ...fontHead, fontSize: 22, color: C.text, margin: "0 0 8px" }}>Caption + Review</h2>
        <p style={{ fontSize: 14, color: C.muted, margin: 0 }}>
          Generate and refine your caption before saving to the library.
        </p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, alignItems: "start" }}>
        {/* Left: editor */}
        <div>
          <button
            data-bk-bound="true"
            onClick={generateCaption}
            disabled={generatingCaption}
            style={{
              width: "100%", marginBottom: 20,
              background: generatingCaption ? C.card2 : "rgba(239,255,0,0.08)",
              color: generatingCaption ? C.vmuted : C.accent,
              border: `1px solid ${generatingCaption ? C.border : "rgba(239,255,0,0.2)"}`,
              borderRadius: 8, padding: "11px",
              ...fontMono, fontSize: 11, fontWeight: 700,
              letterSpacing: "0.1em", cursor: generatingCaption ? "not-allowed" : "pointer",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
              transition: "all 0.15s",
            }}
          >
            {generatingCaption
              ? <><div style={spinnerStyle} />GENERATING CAPTION...</>
              : <><Icon name="sparkle" size={12} stroke={2} color={C.accent} />{caption ? "REGENERATE CAPTION" : "GENERATE CAPTION"}</>
            }
          </button>

          {/* Caption */}
          <div style={{ marginBottom: 16 }}>
            <div style={{
              display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8,
            }}>
              <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em" }}>CAPTION</div>
              <div style={{ ...fontMono, fontSize: 9, color: C.vmuted }}>{editCaption.length} CHARS</div>
            </div>
            <textarea
              value={editCaption}
              onChange={e => setEditCaption(e.target.value)}
              placeholder={caption ? "" : "Generate a caption above, or type your own..."}
              rows={8}
              style={{
                width: "100%", background: C.card2,
                border: `1px solid ${C.border}`,
                borderRadius: 8, padding: "12px",
                color: C.text, fontSize: 13, lineHeight: 1.6,
                resize: "vertical", outline: "none",
                boxSizing: "border-box",
                fontFamily: "Inter, system-ui, sans-serif",
              }}
            />
          </div>

          {/* Hashtags */}
          <div style={{ marginBottom: 16 }}>
            <div style={{
              display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8,
            }}>
              <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em" }}>HASHTAGS</div>
              <div style={{
                ...fontMono, fontSize: 9,
                color: tagCount > 30 ? C.error : tagCount > 25 ? "#F97316" : C.vmuted,
              }}>{tagCount}/30</div>
            </div>
            <textarea
              value={editHashtags}
              onChange={e => setEditHashtags(e.target.value)}
              placeholder="#yourbrand #hashtag"
              rows={3}
              style={{
                width: "100%", background: C.card2,
                border: `1px solid ${tagCount > 30 ? C.error : C.border}`,
                borderRadius: 8, padding: "10px 12px",
                color: C.accent, fontSize: 12, lineHeight: 1.6,
                resize: "vertical", outline: "none",
                boxSizing: "border-box",
                fontFamily: "'JetBrains Mono', monospace",
              }}
            />
          </div>

          {/* CTA */}
          <div style={{ marginBottom: 20 }}>
            <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 8 }}>CALL TO ACTION</div>
            <input
              type="text"
              value={editCta}
              onChange={e => setEditCta(e.target.value)}
              placeholder="e.g. Link in bio to shop now"
              style={{
                width: "100%", background: C.card2,
                border: `1px solid ${C.border}`,
                borderRadius: 8, padding: "10px 12px",
                color: C.text, fontSize: 12,
                outline: "none", boxSizing: "border-box",
                fontFamily: "Inter, system-ui, sans-serif",
              }}
            />
          </div>

          {/* Viral score + alt text */}
          {caption && caption.viral_score != null && (
            <div style={{
              background: C.card2, border: `1px solid ${C.border}`,
              borderRadius: 8, padding: "12px 14px", marginBottom: 16,
              display: "flex", alignItems: "flex-start", gap: 16,
            }}>
              <div style={{ flexShrink: 0 }}>
                <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 4 }}>VIRAL SCORE</div>
                <div style={{ ...fontHead, fontSize: 22, color: C.accent }}>
                  {caption.viral_score}<span style={{ fontSize: 12, color: C.vmuted, fontFamily: "Inter, system-ui" }}>/10</span>
                </div>
              </div>
              {caption.alt_text && (
                <div style={{ flex: 1 }}>
                  <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 4 }}>ALT TEXT</div>
                  <p style={{ fontSize: 11, color: C.muted, margin: 0, lineHeight: 1.4 }}>{caption.alt_text}</p>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Right: preview */}
        <div style={{ position: "sticky", top: 24 }}>
          <PostPreviewCard
            format={format}
            imageUrl={imageUrl}
            idea={selectedIdea}
            caption={previewCaption}
          />
        </div>
      </div>

      <div style={{ marginTop: 28, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <button data-bk-bound="true" onClick={onBack} style={backBtnStyle()}>BACK</button>
        <button
          data-bk-bound="true"
          onClick={handleSave}
          disabled={saving || !editCaption}
          style={{
            background: !editCaption || saving ? C.card2 : C.success,
            color: !editCaption || saving ? C.vmuted : C.bg,
            border: "none", borderRadius: 8, padding: "12px 32px",
            ...fontMono, fontSize: 11, fontWeight: 700,
            letterSpacing: "0.1em",
            cursor: !editCaption || saving ? "not-allowed" : "pointer",
            display: "flex", alignItems: "center", gap: 8,
            transition: "all 0.15s",
          }}
        >
          {saving
            ? <><div style={{...spinnerStyle, border: `2px solid ${C.vmuted}`, borderTopColor: C.muted}} />SAVING...</>
            : <><Icon name="check" size={13} stroke={2.5} color={!editCaption ? C.vmuted : C.bg} />SAVE TO LIBRARY</>
          }
        </button>
      </div>
    </div>
  );
}

// ─── Main Screen ──────────────────────────────────────────────────────────────
function CreatePostScreen() {
  const project    = (typeof currentProject === "function" ? currentProject() : null) || {};
  const brandBrain = (typeof readStore === "function" ? readStore("boltkit.brandBrain.v1", null) : null);

  const [step,              setStep]              = React.useState(0);
  const [goal,              setGoal]              = React.useState(null);
  const [pillar,            setPillar]            = React.useState(null);
  const [postType,          setPostType]          = React.useState(null);
  const [ideas,             setIdeas]             = React.useState([]);
  const [selectedIdea,      setSelectedIdea]      = React.useState(null);
  const [loadingIdeas,      setLoadingIdeas]      = React.useState(false);
  const [format,            setFormat]            = React.useState(IG_FORMATS[1]);
  const [customPrompt,      setCustomPrompt]      = React.useState("");
  const [imageUrl,          setImageUrl]          = React.useState(null);
  const [generatingImage,   setGeneratingImage]   = React.useState(false);
  const [caption,           setCaption]           = React.useState(null);
  const [generatingCaption, setGeneratingCaption] = React.useState(false);
  const [saving,            setSaving]            = React.useState(false);

  // Persist draft
  React.useEffect(() => {
    if (typeof writeStore === "function") {
      writeStore("boltkit.postDraft.v1", { step, goal, pillar, postType, selectedIdea, format, customPrompt, imageUrl });
    }
  }, [step, goal, pillar, postType, selectedIdea, format, customPrompt, imageUrl]);

  const goBack    = () => setStep(s => Math.max(0, s - 1));
  const goForward = () => setStep(s => Math.min(5, s + 1));

  const savePost = (captionData) => {
    setSaving(true);
    try {
      const tags = (captionData && captionData.hashtags) ? captionData.hashtags : (selectedIdea && selectedIdea.suggestedHashtags ? selectedIdea.suggestedHashtags : []);
      const post = {
        id:           "post-" + Date.now(),
        createdAt:    new Date().toISOString(),
        status:       "draft",
        goal:         goal    ? goal.id    : null,
        pillar:       pillar  ? pillar.name : null,
        postType:     postType ? postType.id : null,
        hook:         selectedIdea ? selectedIdea.hook          : null,
        visualConcept:selectedIdea ? selectedIdea.visualConcept : null,
        format:       format  ? format.id  : null,
        imageUrl,
        caption:      captionData ? (captionData.caption || "") : "",
        hashtags:     tags,
        cta:          captionData ? (captionData.cta || (selectedIdea ? (selectedIdea.cta || "") : "")) : "",
        alt_text:     captionData ? (captionData.alt_text || "") : "",
        viral_score:  captionData ? (captionData.viral_score || null) : null,
      };
      const existing = (() => { try { return JSON.parse(localStorage.getItem("boltkit.igPosts.v2") || "[]"); } catch { return []; } })();
      const updated  = [post, ...existing].slice(0, 200);
      localStorage.setItem("boltkit.igPosts.v2", JSON.stringify(updated));
      window.BoltKitToast && window.BoltKitToast({ msg: "Post saved to library!", type: "success" });
      window.BoltKitGo    && window.BoltKitGo("library");
    } catch (e) {
      window.BoltKitToast && window.BoltKitToast({ msg: "Save failed.", type: "error" });
      setSaving(false);
    }
  };

  const showTwoCol = step >= 3 && step < 5;

  return (
    <div style={{
      display: "flex", height: "100vh", overflow: "hidden",
      background: C.bg, color: C.text,
      fontFamily: "Inter, system-ui, sans-serif",
    }}>
      <SidebarNav active="create-post" />

      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <TopBar />

        <div style={{ flex: 1, overflowY: "auto" }}>
          <div style={{ maxWidth: 1080, margin: "0 auto", padding: "0 32px 48px" }}>

            {/* Header */}
            <div style={{ paddingTop: 28, paddingBottom: 24 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
                <BoltMini size={14} color={C.accent} />
                <span style={{ ...fontMono, fontSize: 10, color: C.vmuted, letterSpacing: "0.12em" }}>
                  CREATE POST — STEP {step + 1} OF 6
                </span>
              </div>
              <StepIndicator step={step} onBack={(i) => setStep(i)} />
            </div>

            {/* Content */}
            <div style={showTwoCol ? {
              display: "grid",
              gridTemplateColumns: "1fr 300px",
              gap: 28,
              alignItems: "start",
            } : {}}>

              {/* Step card */}
              <div style={{
                background: C.card,
                border: `1px solid ${C.border}`,
                borderRadius: 14,
                padding: "28px",
              }}>
                {step === 0 && <StepGoal goal={goal} setGoal={setGoal} onNext={goForward} />}
                {step === 1 && <StepPillar pillar={pillar} setPillar={setPillar} onNext={goForward} onBack={goBack} />}
                {step === 2 && <StepType postType={postType} setPostType={setPostType} onNext={goForward} onBack={goBack} />}
                {step === 3 && (
                  <StepIdeas
                    ideas={ideas} setIdeas={setIdeas}
                    selectedIdea={selectedIdea} setSelectedIdea={setSelectedIdea}
                    loadingIdeas={loadingIdeas} setLoadingIdeas={setLoadingIdeas}
                    goal={goal} pillar={pillar} postType={postType}
                    onNext={goForward} onBack={goBack}
                    project={project} brandBrain={brandBrain}
                  />
                )}
                {step === 4 && (
                  <StepImage
                    format={format} setFormat={setFormat}
                    customPrompt={customPrompt} setCustomPrompt={setCustomPrompt}
                    imageUrl={imageUrl} setImageUrl={setImageUrl}
                    generatingImage={generatingImage} setGeneratingImage={setGeneratingImage}
                    selectedIdea={selectedIdea} postType={postType} project={project}
                    onNext={goForward} onBack={goBack}
                  />
                )}
                {step === 5 && (
                  <StepCaption
                    caption={caption} setCaption={setCaption}
                    generatingCaption={generatingCaption} setGeneratingCaption={setGeneratingCaption}
                    goal={goal} pillar={pillar} postType={postType}
                    selectedIdea={selectedIdea} imageUrl={imageUrl} format={format}
                    project={project} saving={saving}
                    onSave={savePost} onBack={goBack}
                  />
                )}
              </div>

              {/* Right column: post preview + summary (steps 3-4) */}
              {showTwoCol && (
                <div style={{ position: "sticky", top: 24 }}>
                  <div style={{ ...fontMono, fontSize: 9, color: C.vmuted, letterSpacing: "0.1em", marginBottom: 10 }}>
                    POST PREVIEW
                  </div>
                  <PostPreviewCard
                    format={format}
                    imageUrl={imageUrl}
                    idea={selectedIdea}
                    caption={caption}
                  />

                  {/* Summary pills */}
                  <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
                    {goal && (
                      <div style={{
                        background: C.card2, border: `1px solid ${C.border}`,
                        borderRadius: 6, padding: "8px 12px",
                        display: "flex", alignItems: "center", gap: 8,
                      }}>
                        <Icon name={goal.icon} size={11} stroke={2} color={C.vmuted} />
                        <span style={{ ...fontMono, fontSize: 9, color: C.muted, letterSpacing: "0.06em" }}>
                          {goal.label.toUpperCase()}
                        </span>
                      </div>
                    )}
                    {pillar && (
                      <div style={{
                        background: C.card2, border: `1px solid ${C.border}`,
                        borderRadius: 6, padding: "8px 12px",
                        display: "flex", alignItems: "center", gap: 8,
                      }}>
                        <div style={{
                          width: 6, height: 6, borderRadius: "50%",
                          background: pillar.color || C.accent, flexShrink: 0,
                        }} />
                        <span style={{ ...fontMono, fontSize: 9, color: C.muted, letterSpacing: "0.06em" }}>
                          {(pillar.name || pillar.label || "").toUpperCase()}
                        </span>
                      </div>
                    )}
                    {postType && (
                      <div style={{
                        background: C.card2, border: `1px solid ${C.border}`,
                        borderRadius: 6, padding: "8px 12px",
                      }}>
                        <span style={{ ...fontMono, fontSize: 9, color: C.muted, letterSpacing: "0.06em" }}>
                          {postType.label.toUpperCase()}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
        textarea:focus, input:focus { border-color: #EFFF00 !important; }
        ::-webkit-scrollbar { width: 5px; height: 5px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #3A372F; border-radius: 4px; }
      `}</style>
    </div>
  );
}

Object.assign(window, { CreatePostScreen });
