/* ========================================================================
   screens-strategy.jsx — Content Strategy: editable content pillars
   ====================================================================== */

const DEFAULT_PILLARS = [
  { id: "pillar-default-1",  name: "Product Education",    description: "Posts that educate the audience about the product and how it works.", exampleTopics: ["How it works", "Key features", "Tutorial tips"],          priority: 1,  active: true  },
  { id: "pillar-default-2",  name: "Problem / Solution",   description: "Content that names the pain point and positions the product as the answer.", exampleTopics: ["Common frustrations", "Before vs after", "Root cause"],  priority: 2,  active: true  },
  { id: "pillar-default-3",  name: "Behind the Scenes",    description: "Authentic, real moments showing the team, process, and creation story.", exampleTopics: ["Team day", "Work in progress", "Studio setup"],            priority: 3,  active: true  },
  { id: "pillar-default-4",  name: "Social Proof",         description: "Customer wins, testimonials, reviews, and real-world results.",           exampleTopics: ["Customer review", "Case study", "Before/after results"],   priority: 4,  active: true  },
  { id: "pillar-default-5",  name: "Founder Story",        description: "Personal moments and the 'why' behind the brand that build deep trust.",   exampleTopics: ["Why I started this", "Lessons learned", "Personal wins"], priority: 5,  active: true  },
  { id: "pillar-default-6",  name: "Offers & Promotions",  description: "Limited-time deals, bundles, and urgency-driven sales posts.",            exampleTopics: ["Flash sale", "Bundle deal", "Last chance offer"],          priority: 6,  active: false },
  { id: "pillar-default-7",  name: "Tips & Advice",        description: "Valuable actionable advice that builds authority and gets saved.",          exampleTopics: ["Quick tip", "How to", "3 things to avoid"],                priority: 7,  active: true  },
  { id: "pillar-default-8",  name: "Lifestyle",            description: "Aspirational content showing the world and values behind the brand.",      exampleTopics: ["Morning routine", "Brand aesthetic", "Mood board"],        priority: 8,  active: true  },
  { id: "pillar-default-9",  name: "FAQs",                 description: "Address the most common questions and objections head-on.",                exampleTopics: ["Top questions", "Myth busting", "Is it right for me?"],    priority: 9,  active: false },
  { id: "pillar-default-10", name: "Before & After",       description: "Transformation stories showing visible, compelling results.",              exampleTopics: ["Client transformation", "Product glow-up", "Then vs now"], priority: 10, active: true  },
];

const PRIORITY_COLORS = ["#EFFF00","#4ADE80","#4DA8FF","#FF9F43","#C8C8C5","#8A8A8A","#5C5C5C","#5C5C5C","#5C5C5C","#5C5C5C"];

const ContentStrategyScreen = () => {
  const project     = typeof currentProject === "function" ? currentProject() : {};
  const brandBrain  = (() => { try { return JSON.parse(localStorage.getItem("boltkit.brandBrain.v1") || "null"); } catch { return null; } })();
  const hasBrain    = Boolean(brandBrain && (brandBrain.tone || brandBrain.audience || brandBrain.positioning));

  const [pillars,    setPillars]    = React.useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("boltkit.pillars.v1") || "null");
      return Array.isArray(saved) && saved.length ? saved : DEFAULT_PILLARS;
    } catch { return DEFAULT_PILLARS; }
  });
  const [generating, setGenerating] = React.useState(false);
  const [editTopics, setEditTopics] = React.useState({}); // pillar id → comma string being edited

  const savePillars = (list) => {
    setPillars(list);
    try { localStorage.setItem("boltkit.pillars.v1", JSON.stringify(list)); } catch {}
  };

  const updatePillar = (id, patch) => savePillars(pillars.map(p => p.id === id ? { ...p, ...patch } : p));

  const deletePillar = (id) => {
    if (!window.confirm("Delete this pillar?")) return;
    savePillars(pillars.filter(p => p.id !== id));
  };

  const addPillar = () => {
    const newPillar = {
      id:            `pillar-${Date.now()}`,
      name:          "New Pillar",
      description:   "Describe what this content pillar is about.",
      exampleTopics: ["Topic idea"],
      priority:      pillars.length + 1,
      active:        true,
    };
    savePillars([...pillars, newPillar]);
  };

  const generateStrategy = async () => {
    if (!hasBrain) {
      window.BoltKitToast?.({ msg: "Build your Brand Brain first.", type: "error" });
      return;
    }
    setGenerating(true);
    window.BoltKitToast?.({ msg: "Generating strategy…", type: "loading" });
    try {
      const resp = await fetch("/api/generate-strategy", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ project, brandBrain }),
      });
      const data = await resp.json();
      if (data.ok && Array.isArray(data.pillars) && data.pillars.length) {
        const merged = data.pillars.map((p, i) => ({
          id:            `pillar-${Date.now()}-${i}`,
          name:          p.name          || "Pillar",
          description:   p.description   || "",
          exampleTopics: Array.isArray(p.exampleTopics) ? p.exampleTopics : [],
          priority:      i + 1,
          active:        true,
          ...p,
        }));
        savePillars(merged);
        window.BoltKitToast?.({ msg: `${merged.length} pillars generated.`, type: "success" });
      } else {
        window.BoltKitToast?.({ msg: data.error || "Generation failed.", type: "error" });
      }
    } catch (e) {
      window.BoltKitToast?.({ msg: e.message || "Generation failed.", type: "error" });
    }
    setGenerating(false);
  };

  const saveStrategy = () => {
    try { localStorage.setItem("boltkit.pillars.v1", JSON.stringify(pillars)); } catch {}
    window.BoltKitToast?.({ msg: "Strategy saved.", type: "success" });
  };

  const activePillars = pillars.filter(p => p.active).length;

  /* ── Inline topic editor helpers ── */
  const startTopicEdit = (pillar) => setEditTopics(prev => ({ ...prev, [pillar.id]: pillar.exampleTopics.join(", ") }));
  const commitTopicEdit = (id) => {
    const raw = editTopics[id] || "";
    const topics = raw.split(",").map(t => t.trim()).filter(Boolean);
    updatePillar(id, { exampleTopics: topics });
    setEditTopics(prev => { const n = { ...prev }; delete n[id]; return n; });
  };

  return (
    <div style={{ height: "100%", display: "flex", background: "#1A1813" }}>
      <SidebarNav active="content-strategy" />
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <TopBar />
        <div style={{ flex: 1, overflowY: "auto" }}>

          {/* ── Header ── */}
          <div style={{ padding: "28px 32px 22px", borderBottom: "1px solid #34312A" }}>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.22em", color: "#EFFF00", fontWeight: 800, marginBottom: 6, textTransform: "uppercase" }}>
              CONTENT STRATEGY
            </div>
            <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
              <div>
                <h1 style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 38, lineHeight: 1, margin: "0 0 8px", color: "#F4F4F0", textTransform: "uppercase" }}>
                  YOUR CONTENT PILLARS
                </h1>
                <div style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 12, color: "#5C5C5C", fontFamily: "'JetBrains Mono', monospace" }}>
                  <span style={{ color: "#C8C8C5" }}>{pillars.length} PILLARS</span>
                  <span>·</span>
                  <span style={{ color: "#4ADE80" }}>{activePillars} ACTIVE</span>
                  {!hasBrain && (
                    <>
                      <span>·</span>
                      <span style={{ color: "#FF4D5E" }}>NO BRAND BRAIN</span>
                    </>
                  )}
                </div>
              </div>

              {/* Action bar */}
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
                <button
                  className={"btn btn-primary" + (generating ? " btn-analysing" : "")}
                  onClick={generateStrategy}
                  disabled={generating || !hasBrain}
                  style={{ fontSize: 13, padding: "10px 20px" }}
                >
                  <span className={generating ? "bolt-thinking" : ""}><BoltMini size={13} color={generating ? "#EFFF00" : "#1A1813"} /></span>
                  {generating ? "Generating…" : "Generate Strategy"}
                </button>
                <button className="btn btn-secondary" onClick={addPillar} style={{ fontSize: 13 }}>
                  <Icon name="plus" size={13} stroke={2} /> Add Pillar
                </button>
                <button className="btn btn-secondary" onClick={saveStrategy} style={{ fontSize: 13 }}>
                  <Icon name="save" size={13} stroke={2} /> Save Strategy
                </button>
                <button className="btn btn-secondary" onClick={() => window.BoltKitGo?.("ig-generate")} style={{ fontSize: 13 }}>
                  Create Post <Icon name="arrow_right" size={13} stroke={2} />
                </button>
              </div>
            </div>
          </div>

          {/* ── Body ── */}
          <div style={{ padding: "24px 32px 60px" }}>

            {/* No Brand Brain warning */}
            {!hasBrain && (
              <div style={{ marginBottom: 24, padding: "20px 24px", background: "rgba(255,77,94,0.08)", border: "1px solid rgba(255,77,94,0.3)", borderRadius: 8, display: "flex", alignItems: "center", gap: 16 }}>
                <Icon name="alert" size={20} stroke={2} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, fontWeight: 800, color: "#FF4D5E", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 4 }}>BRAND BRAIN REQUIRED</div>
                  <div style={{ fontSize: 13, color: "#C8C8C5", lineHeight: 1.5 }}>Build your Brand Brain first to generate a personalised content strategy. Until then, you can use the default pillars below.</div>
                </div>
                <button className="btn btn-secondary" onClick={() => window.BoltKitGo?.("brand-brain")} style={{ whiteSpace: "nowrap", fontSize: 12 }}>
                  Build Brand Brain <Icon name="arrow_right" size={12} stroke={2} />
                </button>
              </div>
            )}

            {/* Generating splash */}
            {generating && (
              <div style={{ textAlign: "center", padding: "48px 0", marginBottom: 24 }}>
                <span className="bolt-thinking" style={{ display: "inline-block" }}><BoltMini size={36} color="#EFFF00" /></span>
                <div style={{ marginTop: 14, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, fontWeight: 800, letterSpacing: "0.18em", color: "#EFFF00", textTransform: "uppercase" }}>AI IS BUILDING YOUR STRATEGY…</div>
                <div style={{ marginTop: 6, fontSize: 12, color: "#5C5C5C" }}>Analysing your brand and audience to create the perfect content mix.</div>
              </div>
            )}

            {/* Pillars grid */}
            {!generating && pillars.length === 0 && (
              <div style={{ textAlign: "center", padding: "60px 0", color: "#5C5C5C" }}>
                <BoltMini size={36} color="#3A372F" />
                <div style={{ marginTop: 12, fontSize: 13 }}>No pillars yet — generate a strategy or add one manually.</div>
              </div>
            )}

            {!generating && pillars.length > 0 && (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 14 }}>
                {pillars.map((pillar, idx) => {
                  const priorityColor = PRIORITY_COLORS[pillar.priority - 1] || "#5C5C5C";
                  const isEditingTopics = editTopics[pillar.id] !== undefined;

                  return (
                    <div
                      key={pillar.id}
                      style={{
                        background: "#201E18",
                        border: `1px solid ${pillar.active ? "#3A372F" : "#2A2822"}`,
                        borderRadius: 8,
                        padding: "18px 18px 16px",
                        opacity: pillar.active ? 1 : 0.55,
                        position: "relative",
                        transition: "opacity 0.2s",
                      }}
                    >
                      {/* Priority badge */}
                      <div style={{ position: "absolute", top: 14, right: 14, display: "flex", alignItems: "center", gap: 8 }}>
                        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, fontWeight: 800, color: priorityColor, letterSpacing: "0.14em", background: `${priorityColor}18`, padding: "3px 7px", borderRadius: 3 }}>
                          #{pillar.priority}
                        </span>
                      </div>

                      {/* Pillar name */}
                      <input
                        value={pillar.name}
                        onChange={e => updatePillar(pillar.id, { name: e.target.value })}
                        style={{
                          fontFamily: "'Anton', Impact, sans-serif",
                          fontSize: 18,
                          fontWeight: 400,
                          textTransform: "uppercase",
                          color: "#F4F4F0",
                          background: "transparent",
                          border: "none",
                          outline: "none",
                          width: "calc(100% - 60px)",
                          padding: 0,
                          marginBottom: 8,
                          letterSpacing: "0.02em",
                        }}
                      />

                      {/* Description */}
                      <textarea
                        value={pillar.description}
                        onChange={e => updatePillar(pillar.id, { description: e.target.value })}
                        rows={2}
                        style={{
                          width: "100%",
                          boxSizing: "border-box",
                          background: "#26241E",
                          border: "1px solid #34312A",
                          borderRadius: 5,
                          color: "#C8C8C5",
                          fontSize: 12,
                          lineHeight: 1.55,
                          padding: "8px 10px",
                          resize: "vertical",
                          outline: "none",
                          fontFamily: "Inter, system-ui, sans-serif",
                          marginBottom: 12,
                        }}
                      />

                      {/* Example topics */}
                      <div style={{ marginBottom: 12 }}>
                        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, fontWeight: 800, color: "#5C5C5C", letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 7 }}>
                          EXAMPLE TOPICS
                        </div>

                        {!isEditingTopics ? (
                          <div style={{ display: "flex", flexWrap: "wrap", gap: 5, cursor: "pointer" }} onClick={() => startTopicEdit(pillar)}>
                            {pillar.exampleTopics.length ? pillar.exampleTopics.map((topic, ti) => (
                              <span
                                key={ti}
                                style={{ background: "#26241E", border: "1px solid #3A372F", color: "#C8C8C5", padding: "4px 9px", borderRadius: 4, fontSize: 11, fontFamily: "Inter, system-ui, sans-serif" }}
                              >
                                {topic}
                              </span>
                            )) : (
                              <span style={{ fontSize: 11, color: "#5C5C5C", fontStyle: "italic" }}>Click to add topics…</span>
                            )}
                            <span style={{ background: "#26241E", border: "1px dashed #3A372F", color: "#5C5C5C", padding: "4px 8px", borderRadius: 4, fontSize: 10, display: "flex", alignItems: "center" }}>
                              <Icon name="edit" size={10} stroke={2} />
                            </span>
                          </div>
                        ) : (
                          <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                            <input
                              autoFocus
                              value={editTopics[pillar.id]}
                              onChange={e => setEditTopics(prev => ({ ...prev, [pillar.id]: e.target.value }))}
                              onBlur={() => commitTopicEdit(pillar.id)}
                              onKeyDown={e => e.key === "Enter" && commitTopicEdit(pillar.id)}
                              placeholder="e.g. How it works, Key features, Tutorial tips"
                              style={{ background: "#1A1813", border: "1px solid #EFFF00", color: "#F4F4F0", padding: "7px 10px", fontSize: 11.5, borderRadius: 4, outline: "none", fontFamily: "Inter, system-ui, sans-serif" }}
                            />
                            <div style={{ fontSize: 10, color: "#5C5C5C", fontFamily: "'JetBrains Mono', monospace" }}>Comma-separated · Enter or click away to save</div>
                          </div>
                        )}
                      </div>

                      {/* Footer: toggle + delete */}
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 10, borderTop: "1px solid #2A2822" }}>
                        {/* Active toggle */}
                        <button
                          onClick={() => updatePillar(pillar.id, { active: !pillar.active })}
                          style={{ display: "flex", alignItems: "center", gap: 7, background: "none", border: "none", cursor: "pointer", padding: 0 }}
                        >
                          <span style={{
                            width: 32, height: 18, borderRadius: 9,
                            background: pillar.active ? "#EFFF00" : "#2A2822",
                            border: `1px solid ${pillar.active ? "#EFFF00" : "#3A372F"}`,
                            position: "relative", display: "inline-block", transition: "background 0.2s",
                          }}>
                            <span style={{
                              position: "absolute", top: 2, left: pillar.active ? 14 : 2,
                              width: 12, height: 12, borderRadius: "50%",
                              background: pillar.active ? "#1A1813" : "#5C5C5C",
                              transition: "left 0.2s",
                            }} />
                          </span>
                          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 800, color: pillar.active ? "#EFFF00" : "#5C5C5C", letterSpacing: "0.12em" }}>
                            {pillar.active ? "ACTIVE" : "INACTIVE"}
                          </span>
                        </button>

                        {/* Priority + delete */}
                        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                          <select
                            value={pillar.priority}
                            onChange={e => updatePillar(pillar.id, { priority: Number(e.target.value) })}
                            style={{ background: "#26241E", border: "1px solid #3A372F", color: "#8A8A8A", borderRadius: 4, padding: "3px 6px", fontSize: 11, fontFamily: "'JetBrains Mono', monospace", outline: "none", cursor: "pointer" }}
                          >
                            {Array.from({ length: 10 }, (_, i) => i + 1).map(n => (
                              <option key={n} value={n}>P{n}</option>
                            ))}
                          </select>
                          <button
                            onClick={() => deletePillar(pillar.id)}
                            style={{ width: 28, height: 28, borderRadius: 5, background: "rgba(255,77,94,0.08)", border: "1px solid rgba(255,77,94,0.2)", color: "#FF4D5E", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}
                          >
                            <Icon name="trash" size={11} stroke={2} />
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}

                {/* Add pillar card */}
                <button
                  onClick={addPillar}
                  style={{
                    background: "transparent",
                    border: "1px dashed #3A372F",
                    borderRadius: 8,
                    padding: "32px 18px",
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: 10,
                    cursor: "pointer",
                    color: "#5C5C5C",
                    minHeight: 180,
                    transition: "border-color 0.2s",
                  }}
                  onMouseEnter={e => e.currentTarget.style.borderColor = "#EFFF00"}
                  onMouseLeave={e => e.currentTarget.style.borderColor = "#3A372F"}
                >
                  <Icon name="plus" size={20} stroke={1.5} />
                  <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 800, letterSpacing: "0.16em", textTransform: "uppercase" }}>ADD PILLAR</span>
                </button>
              </div>
            )}

            {/* Footer actions */}
            {pillars.length > 0 && !generating && (
              <div style={{ marginTop: 28, display: "flex", alignItems: "center", gap: 10, paddingTop: 20, borderTop: "1px solid #34312A" }}>
                <button className="btn btn-primary" onClick={saveStrategy} style={{ fontSize: 13, padding: "10px 22px" }}>
                  <Icon name="save" size={13} stroke={2} /> Save Strategy
                </button>
                <button className="btn btn-secondary" onClick={() => window.BoltKitGo?.("ig-generate")} style={{ fontSize: 13 }}>
                  Create Post <Icon name="arrow_right" size={13} stroke={2} />
                </button>
                <div style={{ flex: 1 }} />
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: "#5C5C5C", letterSpacing: "0.12em" }}>
                  {activePillars}/{pillars.length} pillars active
                </span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ContentStrategyScreen });
