/* ========================================================================
   screens-library.jsx — Content Library: filterable post management
   ====================================================================== */

const STATUS_CONFIG = {
  draft:     { label: "Draft",     color: "#8A8A8A", bg: "rgba(138,138,138,0.12)", border: "rgba(138,138,138,0.3)"  },
  approved:  { label: "Approved",  color: "#EFFF00", bg: "rgba(239,255,0,0.10)",   border: "rgba(239,255,0,0.3)"    },
  scheduled: { label: "Scheduled", color: "#4DA8FF", bg: "rgba(77,168,255,0.12)",  border: "rgba(77,168,255,0.3)"   },
  posted:    { label: "Posted",    color: "#4ADE80", bg: "rgba(74,222,128,0.12)",  border: "rgba(74,222,128,0.3)"   },
  failed:    { label: "Failed",    color: "#FF4D5E", bg: "rgba(255,77,94,0.12)",   border: "rgba(255,77,94,0.3)"    },
};

const STATUSES = ["draft", "approved", "scheduled", "posted", "failed"];

const FORMAT_RATIO = { story: "9:16", portrait: "4:5", square: "1:1" };
const FORMAT_ASPECT = { story: "9/16", portrait: "4/5", square: "1/1" };

const ContentLibraryScreen = () => {
  const [posts,        setPosts]        = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("boltkit.igPosts.v2") || "[]"); } catch { return []; }
  });
  const [filter,       setFilter]       = React.useState("all");
  const [search,       setSearch]       = React.useState("");
  const [approveId,    setApproveId]    = React.useState(null); // id of post showing date-picker
  const [approveDate,  setApproveDate]  = React.useState("");
  const [approveTime,  setApproveTime]  = React.useState("09:00");
  const [calendarId,   setCalendarId]   = React.useState(null);
  const [calDate,      setCalDate]      = React.useState("");
  const [calTime,      setCalTime]      = React.useState("09:00");

  const savePosts = (list) => {
    setPosts(list);
    try { localStorage.setItem("boltkit.igPosts.v2", JSON.stringify(list.slice(0, 200))); } catch {}
  };

  const updatePost = (id, patch) => savePosts(posts.map(p => p.id === id ? { ...p, ...patch } : p));

  const deletePost = (id) => {
    if (!window.confirm("Delete this post?")) return;
    savePosts(posts.filter(p => p.id !== id));
  };

  const duplicatePost = (post) => {
    const copy = { ...post, id: `igpost-dup-${Date.now()}`, status: "draft", created_at: new Date().toISOString() };
    savePosts([copy, ...posts]);
    window.BoltKitToast?.({ msg: "Post duplicated.", type: "success" });
  };

  /* Approve flow: set status to approved + optionally set scheduled_at */
  const startApprove = (id) => {
    setApproveId(id);
    setApproveDate("");
    setApproveTime("09:00");
  };

  const commitApprove = (id) => {
    updatePost(id, { status: "approved", approved_at: new Date().toISOString() });
    setApproveId(null);
    window.BoltKitToast?.({ msg: "Post approved.", type: "success" });
  };

  /* Calendar flow: set status to scheduled */
  const startCalendar = (id) => {
    setCalendarId(id);
    setCalDate("");
    setCalTime("09:00");
  };

  const commitCalendar = (id) => {
    if (!calDate) { window.BoltKitToast?.({ msg: "Pick a date first.", type: "error" }); return; }
    updatePost(id, { status: "scheduled", scheduled_at: `${calDate}T${calTime}` });
    setCalendarId(null);
    window.BoltKitToast?.({ msg: "Post scheduled.", type: "success" });
  };

  /* Filter + search */
  const visiblePosts = posts.filter(p => {
    const matchStatus = filter === "all" || p.status === filter;
    const matchSearch = !search || (p.caption || "").toLowerCase().includes(search.toLowerCase()) || (p.hook || "").toLowerCase().includes(search.toLowerCase());
    return matchStatus && matchSearch;
  });

  /* Count per status */
  const counts = { all: posts.length };
  STATUSES.forEach(s => { counts[s] = posts.filter(p => p.status === s).length; });

  const getFormatRatio = (post) => {
    if (post.ratio) return post.ratio;
    return FORMAT_RATIO[post.format] || "1:1";
  };

  const getFormatAspect = (post) => {
    if (post.aspect) return post.aspect;
    return FORMAT_ASPECT[post.format] || "1/1";
  };

  const statusCfg = (s) => STATUS_CONFIG[s] || STATUS_CONFIG.draft;

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

          {/* ── Header ── */}
          <div style={{ padding: "28px 32px 0", borderBottom: "1px solid #34312A" }}>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.22em", color: "#EFFF00", fontWeight: 800, marginBottom: 6, textTransform: "uppercase" }}>
              CONTENT LIBRARY
            </div>
            <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
              <h1 style={{ fontFamily: "'Anton', Impact, sans-serif", fontSize: 38, lineHeight: 1, margin: 0, color: "#F4F4F0", textTransform: "uppercase" }}>
                {posts.length} {posts.length === 1 ? "POST" : "POSTS"}
              </h1>
              <div style={{ display: "flex", gap: 8 }}>
                <button className="btn btn-secondary" onClick={() => window.BoltKitGo?.("ig-generate")} style={{ fontSize: 12 }}>
                  <Icon name="plus" size={12} stroke={2} /> Create Post
                </button>
                <button className="btn btn-secondary" onClick={() => window.BoltKitGo?.("ig-calendar")} style={{ fontSize: 12 }}>
                  <Icon name="calendar" size={12} stroke={2} /> Calendar
                </button>
              </div>
            </div>

            {/* Status tabs */}
            <div style={{ display: "flex", gap: 0, overflowX: "auto", marginBottom: -1 }}>
              {[{ key: "all", label: "All" }, ...STATUSES.map(s => ({ key: s, label: STATUS_CONFIG[s].label }))].map(tab => {
                const count = counts[tab.key] || 0;
                const active = filter === tab.key;
                const cfg = tab.key !== "all" ? statusCfg(tab.key) : null;
                return (
                  <button
                    key={tab.key}
                    onClick={() => setFilter(tab.key)}
                    style={{
                      padding: "10px 16px",
                      background: "none",
                      border: "none",
                      borderBottom: active ? "2px solid #EFFF00" : "2px solid transparent",
                      color: active ? "#F4F4F0" : "#5C5C5C",
                      fontFamily: "'JetBrains Mono', monospace",
                      fontSize: 11,
                      fontWeight: 800,
                      letterSpacing: "0.12em",
                      textTransform: "uppercase",
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      gap: 7,
                      whiteSpace: "nowrap",
                      paddingBottom: 11,
                    }}
                  >
                    {cfg && <span style={{ width: 6, height: 6, borderRadius: "50%", background: active ? cfg.color : "#3A372F", flexShrink: 0 }} />}
                    {tab.label}
                    <span style={{ background: active ? "rgba(239,255,0,0.12)" : "#26241E", color: active ? "#EFFF00" : "#5C5C5C", padding: "1px 6px", borderRadius: 10, fontSize: 10 }}>
                      {count}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* ── Search bar ── */}
          <div style={{ padding: "14px 32px", borderBottom: "1px solid #2A2822", background: "#1C1A14" }}>
            <div style={{ position: "relative", maxWidth: 440 }}>
              <span style={{ position: "absolute", top: "50%", left: 11, transform: "translateY(-50%)", color: "#5C5C5C" }}>
                <Icon name="filter" size={13} stroke={2} />
              </span>
              <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search captions…"
                style={{ width: "100%", boxSizing: "border-box", background: "#201E18", border: "1px solid #3A372F", color: "#F4F4F0", padding: "9px 12px 9px 34px", fontSize: 13, borderRadius: 5, outline: "none", fontFamily: "Inter, system-ui, sans-serif" }}
              />
              {search && (
                <button onClick={() => setSearch("")} style={{ position: "absolute", top: "50%", right: 10, transform: "translateY(-50%)", background: "none", border: "none", color: "#5C5C5C", cursor: "pointer", padding: 2 }}>
                  <Icon name="plus" size={12} stroke={2} />
                </button>
              )}
            </div>
          </div>

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

            {/* Empty — no posts at all */}
            {posts.length === 0 && (
              <div style={{ textAlign: "center", padding: "72px 0" }}>
                <BoltMini size={40} color="#3A372F" />
                <div style={{ marginTop: 14, fontFamily: "'Anton', Impact, sans-serif", fontSize: 20, color: "#3A372F", textTransform: "uppercase", letterSpacing: "0.04em" }}>NO POSTS YET</div>
                <div style={{ marginTop: 8, fontSize: 13, color: "#5C5C5C", marginBottom: 20 }}>Generate your first post to start building your content library.</div>
                <button className="btn btn-primary" onClick={() => window.BoltKitGo?.("ig-generate")} style={{ fontSize: 13, padding: "11px 22px" }}>
                  <BoltMini size={13} color="#1A1813" /> Create First Post
                </button>
              </div>
            )}

            {/* Empty — filter has no results */}
            {posts.length > 0 && visiblePosts.length === 0 && (
              <div style={{ textAlign: "center", padding: "60px 0", color: "#5C5C5C" }}>
                <Icon name="filter" size={28} stroke={1.5} />
                <div style={{ marginTop: 10, fontSize: 13 }}>No posts match this filter.</div>
                <button onClick={() => { setFilter("all"); setSearch(""); }} style={{ marginTop: 12, background: "none", border: "none", color: "#EFFF00", fontSize: 12, fontWeight: 700, cursor: "pointer", fontFamily: "'JetBrains Mono', monospace" }}>
                  CLEAR FILTERS
                </button>
              </div>
            )}

            {/* Posts grid */}
            {visiblePosts.length > 0 && (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
                {visiblePosts.map(post => {
                  const cfg = statusCfg(post.status);
                  const ratio = getFormatRatio(post);
                  const aspect = getFormatAspect(post);
                  const isApprovingThis = approveId === post.id;
                  const isCalendarThis  = calendarId === post.id;
                  const hashCount = (post.hashtags || []).length;
                  const date = post.created_at ? new Date(post.created_at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "2-digit" }) : null;

                  return (
                    <div
                      key={post.id}
                      style={{ background: "#201E18", border: "1px solid #3A372F", borderRadius: 8, overflow: "hidden", display: "flex", flexDirection: "column" }}
                    >
                      {/* Thumbnail */}
                      <div style={{ aspectRatio: aspect, background: "#26241E", position: "relative", overflow: "hidden", flexShrink: 0 }}>
                        {post.imageUrl ? (
                          <img src={post.imageUrl} alt={post.alt_text || "Post"} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
                        ) : (
                          <div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8, color: "#3A372F" }}>
                            <Icon name="insta" size={24} stroke={1} />
                            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 800, letterSpacing: "0.14em", color: "#3A372F" }}>{ratio}</span>
                          </div>
                        )}

                        {/* Format badge — top-left */}
                        <div style={{ position: "absolute", top: 8, left: 8, background: "rgba(0,0,0,0.75)", color: "#EFFF00", fontFamily: "'JetBrains Mono', monospace", fontSize: 9, fontWeight: 800, padding: "3px 7px", borderRadius: 3, backdropFilter: "blur(4px)" }}>
                          {ratio}
                        </div>

                        {/* Status badge — top-right */}
                        <div style={{ position: "absolute", top: 8, right: 8, background: cfg.bg, border: `1px solid ${cfg.border}`, color: cfg.color, fontFamily: "'JetBrains Mono', monospace", fontSize: 9, fontWeight: 800, padding: "3px 8px", borderRadius: 3, backdropFilter: "blur(4px)", textTransform: "uppercase", letterSpacing: "0.1em" }}>
                          {cfg.label}
                        </div>

                        {/* Status dropdown overlay */}
                        <div style={{ position: "absolute", bottom: 8, right: 8 }}>
                          <select
                            value={post.status}
                            onChange={e => updatePost(post.id, { status: e.target.value })}
                            style={{ background: "rgba(26,24,19,0.88)", border: "1px solid #3A372F", color: "#C8C8C5", borderRadius: 4, padding: "3px 6px", fontSize: 10, fontFamily: "'JetBrains Mono', monospace", outline: "none", cursor: "pointer", backdropFilter: "blur(4px)" }}
                          >
                            {STATUSES.map(s => (
                              <option key={s} value={s}>{STATUS_CONFIG[s].label}</option>
                            ))}
                          </select>
                        </div>
                      </div>

                      {/* Card body */}
                      <div style={{ padding: "12px 14px 14px", flex: 1, display: "flex", flexDirection: "column" }}>

                        {/* Hook */}
                        {post.hook && (
                          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, fontWeight: 800, color: "#EFFF00", marginBottom: 5, lineHeight: 1.4, letterSpacing: "0.02em" }}>
                            {post.hook}
                          </div>
                        )}

                        {/* Caption preview */}
                        <div style={{ fontSize: 12, color: "#C8C8C5", lineHeight: 1.55, flex: 1, marginBottom: 10, display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden" }}>
                          {post.caption || <span style={{ color: "#5C5C5C", fontStyle: "italic" }}>No caption yet</span>}
                        </div>

                        {/* Meta chips */}
                        <div style={{ display: "flex", gap: 5, flexWrap: "wrap", marginBottom: 10 }}>
                          {hashCount > 0 && (
                            <span style={{ background: "rgba(77,168,255,0.10)", border: "1px solid rgba(77,168,255,0.2)", color: "#4DA8FF", padding: "2px 8px", borderRadius: 4, fontSize: 10, fontFamily: "'JetBrains Mono', monospace", fontWeight: 800 }}>
                              #{hashCount} tags
                            </span>
                          )}
                          {post.goal && (
                            <span style={{ background: "#26241E", border: "1px solid #3A372F", color: "#8A8A8A", padding: "2px 8px", borderRadius: 4, fontSize: 10, fontFamily: "'JetBrains Mono', monospace" }}>
                              {post.goal}
                            </span>
                          )}
                          {post.viral_score && (
                            <span style={{ background: "rgba(239,255,0,0.08)", border: "1px solid rgba(239,255,0,0.2)", color: "#EFFF00", padding: "2px 8px", borderRadius: 4, fontSize: 10, fontFamily: "'JetBrains Mono', monospace", fontWeight: 800 }}>
                              V{post.viral_score}
                            </span>
                          )}
                          {date && (
                            <span style={{ color: "#5C5C5C", fontSize: 10, fontFamily: "'JetBrains Mono', monospace", marginLeft: "auto", paddingTop: 2 }}>
                              {date}
                            </span>
                          )}
                        </div>

                        {/* Approve date picker */}
                        {isApprovingThis && (
                          <div style={{ marginBottom: 10, padding: "10px 12px", background: "rgba(239,255,0,0.06)", border: "1px solid rgba(239,255,0,0.2)", borderRadius: 6 }}>
                            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, fontWeight: 800, color: "#EFFF00", letterSpacing: "0.14em", marginBottom: 8 }}>APPROVE + SCHEDULE</div>
                            <div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
                              <input type="date" value={approveDate} onChange={e => setApproveDate(e.target.value)} style={{ flex: 1, background: "#1A1813", border: "1px solid #3A372F", color: "#F4F4F0", padding: "6px 8px", fontSize: 11, borderRadius: 4, outline: "none" }} />
                              <input type="time" value={approveTime} onChange={e => setApproveTime(e.target.value)} style={{ width: 82, background: "#1A1813", border: "1px solid #3A372F", color: "#F4F4F0", padding: "6px 8px", fontSize: 11, borderRadius: 4, outline: "none" }} />
                            </div>
                            <div style={{ display: "flex", gap: 6 }}>
                              <button className="btn btn-primary btn-sm" onClick={() => commitApprove(post.id)} style={{ flex: 1 }}>
                                <Icon name="check" size={11} stroke={2} /> Approve
                              </button>
                              <button className="btn btn-secondary btn-sm" onClick={() => setApproveId(null)}>Cancel</button>
                            </div>
                          </div>
                        )}

                        {/* Calendar date picker */}
                        {isCalendarThis && (
                          <div style={{ marginBottom: 10, padding: "10px 12px", background: "rgba(77,168,255,0.07)", border: "1px solid rgba(77,168,255,0.2)", borderRadius: 6 }}>
                            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, fontWeight: 800, color: "#4DA8FF", letterSpacing: "0.14em", marginBottom: 8 }}>SCHEDULE DATE</div>
                            <div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
                              <input type="date" value={calDate} onChange={e => setCalDate(e.target.value)} style={{ flex: 1, background: "#1A1813", border: "1px solid #3A372F", color: "#F4F4F0", padding: "6px 8px", fontSize: 11, borderRadius: 4, outline: "none" }} />
                              <input type="time" value={calTime} onChange={e => setCalTime(e.target.value)} style={{ width: 82, background: "#1A1813", border: "1px solid #3A372F", color: "#F4F4F0", padding: "6px 8px", fontSize: 11, borderRadius: 4, outline: "none" }} />
                            </div>
                            <div style={{ display: "flex", gap: 6 }}>
                              <button className="btn btn-secondary btn-sm" onClick={() => commitCalendar(post.id)} style={{ flex: 1, color: "#4DA8FF", borderColor: "rgba(77,168,255,0.3)" }}>
                                <Icon name="calendar" size={11} stroke={2} /> Schedule
                              </button>
                              <button className="btn btn-secondary btn-sm" onClick={() => setCalendarId(null)}>Cancel</button>
                            </div>
                          </div>
                        )}

                        {/* Quick actions */}
                        <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
                          {/* Edit */}
                          <button
                            className="btn btn-secondary btn-sm"
                            onClick={() => window.BoltKitGo?.("ig-generate")}
                            title="Edit caption"
                            style={{ flex: "0 0 auto" }}
                          >
                            <Icon name="edit" size={11} stroke={2} />
                          </button>

                          {/* Move to calendar */}
                          <button
                            className="btn btn-secondary btn-sm"
                            onClick={() => isCalendarThis ? setCalendarId(null) : startCalendar(post.id)}
                            title="Move to calendar"
                            style={{ flex: "0 0 auto", color: isCalendarThis ? "#4DA8FF" : undefined, borderColor: isCalendarThis ? "rgba(77,168,255,0.4)" : undefined }}
                          >
                            <Icon name="calendar" size={11} stroke={2} />
                          </button>

                          {/* Duplicate */}
                          <button
                            className="btn btn-secondary btn-sm"
                            onClick={() => duplicatePost(post)}
                            title="Duplicate"
                            style={{ flex: "0 0 auto" }}
                          >
                            <Icon name="copy" size={11} stroke={2} />
                          </button>

                          {/* Approve (draft only) */}
                          {post.status === "draft" && (
                            <button
                              className="btn btn-secondary btn-sm"
                              onClick={() => isApprovingThis ? setApproveId(null) : startApprove(post.id)}
                              title="Approve"
                              style={{ flex: 1, color: isApprovingThis ? "#EFFF00" : "#4ADE80", borderColor: isApprovingThis ? "rgba(239,255,0,0.3)" : "rgba(74,222,128,0.3)", minWidth: 72 }}
                            >
                              <Icon name="check" size={11} stroke={2} />
                              {isApprovingThis ? "Cancel" : "Approve"}
                            </button>
                          )}

                          {/* Delete */}
                          <button
                            className="btn btn-secondary btn-sm"
                            onClick={() => deletePost(post.id)}
                            title="Delete"
                            style={{ flex: "0 0 auto", color: "#FF4D5E", borderColor: "rgba(255,77,94,0.2)", marginLeft: "auto" }}
                          >
                            <Icon name="trash" size={11} stroke={2} />
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ContentLibraryScreen });
