/* global React */
const { useState: useStateAdm, useEffect: useEffectAdm, useRef: useRefAdm } = React;

async function authFetch(action, extra = {}) {
  const fd = new FormData();
  fd.append("action", action);
  Object.entries(extra).forEach(([k, v]) => fd.append(k, v));
  const res = await fetch("/admin-auth.php", { method: "POST", body: fd });
  return res.json();
}

function AdminPage({ onNav }) {
  const { isMobile, isTablet, isDesktop } = useBreakpoint();
  const bp = (d, t, m) => isMobile ? m : isTablet ? t : d;

  const [auth, setAuth] = useStateAdm(false);
  const [authChecked, setAuthChecked] = useStateAdm(false);
  const [pw, setPw]   = useStateAdm("");
  const [err, setErr] = useStateAdm("");
  const [loading, setLoading] = useStateAdm(false);
  const [lockSecs, setLockSecs] = useStateAdm(0);
  const [courses, setCourses] = useCourses();
  const [blogs, setBlogs] = useBlogs();
  const [tab, setTab] = useStateAdm("kursevi");
  const [editing, setEditing] = useStateAdm(null);
  const [editingBlog, setEditingBlog] = useStateAdm(null);

  // Proveri PHP session pri učitavanju
  useEffectAdm(() => {
    authFetch("check").then(d => {
      setAuth(!!d.ok);
      setAuthChecked(true);
    }).catch(() => setAuthChecked(true));
  }, []);

  const login = async (e) => {
    e.preventDefault();
    if (loading || lockSecs > 0) return;
    setLoading(true);
    setErr("");
    try {
      const d = await authFetch("login", { password: pw });
      if (d.ok) {
        setAuth(true);
        setErr("");
      } else if (d.locked) {
        setLockSecs(d.remaining || 600);
        const t = setInterval(() => {
          setLockSecs(s => {
            if (s <= 1) { clearInterval(t); return 0; }
            return s - 1;
          });
        }, 1000);
        setErr("Previše pokušaja — pristup privremeno blokiran.");
      } else {
        const left = d.attempts_left ?? "";
        setErr(`Pogrešna lozinka.${left ? ` Još ${left} pokušaj${left === 1 ? "" : "a"}.` : ""}`);
      }
    } catch {
      setErr("Greška veze sa serverom.");
    } finally {
      setLoading(false);
    }
  };

  const logout = async () => {
    await authFetch("logout");
    setAuth(false);
    setPw("");
  };

  const save = (data) => {
    if (editing === "new") {
      setCourses([...courses, { ...data, id: "c-" + Date.now(), active: true }]);
    } else {
      setCourses(courses.map(c => c.id === editing ? { ...c, ...data } : c));
    }
    setEditing(null);
  };
  const remove = (id) => {
    if (confirm("Obrisati kurs? Ova akcija je nepovratna.")) setCourses(courses.filter(c => c.id !== id));
  };
  const toggle = (id) => setCourses(courses.map(c => c.id === id ? { ...c, active: !c.active } : c));
  const resetDefaults = () => {
    if (confirm("Vratiti podrazumevane kurseve? Sve izmene će biti izgubljene.")) setCourses(DEFAULT_COURSES);
  };

  const saveBlog = (data) => {
    if (editingBlog === "new") {
      setBlogs([{ ...data, id: "b-" + Date.now(), active: true }, ...blogs]);
    } else {
      setBlogs(blogs.map(b => b.id === editingBlog ? { ...b, ...data } : b));
    }
    setEditingBlog(null);
  };
  const removeBlog = (id) => {
    if (confirm("Obrisati post? Ova akcija je nepovratna.")) setBlogs(blogs.filter(b => b.id !== id));
  };
  const toggleBlog = (id) => setBlogs(blogs.map(b => b.id === id ? { ...b, active: !b.active } : b));
  const editingBlogData = editingBlog === "new"
    ? { title:"", cat:"Tehnike", read:"5 min", date:"", excerpt:"", imageUrl:"", featured:false, active:true }
    : blogs.find(b => b.id === editingBlog);

  const editingCourse = editing === "new"
    ? { title: "", region: "Vratna kičma", level: "Srednji", duration: "2 dana", hours: "16h", price: "€600", startDate: "", deadline: "", location: "OMT Centar · Beograd, Centar", spots: "1 polaznik", techniques: [], description: "", curriculum: [], badge: "", imageUrl: "" }
    : courses.find(c => c.id === editing);

  const inp = { width: "100%", padding: "11px 14px", fontSize: 14, fontFamily: "inherit", border: "1.5px solid var(--border-default)", borderRadius: 8, outline: 0, background: "#fff", color: "var(--text-primary)" };
  const lbl = { display: "block", fontSize: 11, fontWeight: 700, color: "var(--text-secondary)", marginBottom: 6, letterSpacing: "0.04em", textTransform: "uppercase" };
  const adminBtn = { display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11, fontFamily: "inherit", fontWeight: 600, cursor: "pointer", background: "var(--surface-2)", color: "var(--text-secondary)", border: 0, borderRadius: 6, padding: "5px 10px", letterSpacing: "0.04em", textTransform: "uppercase" };

  if (!authChecked) {
    return <main style={{ minHeight:"80vh", display:"flex", alignItems:"center", justifyContent:"center" }}>
      <div style={{ fontSize:14, color:"var(--text-tertiary)" }}>Učitavanje…</div>
    </main>;
  }

  if (!auth) {
    return (
      <main style={{ minHeight: "80vh", display: "flex", alignItems: "center", justifyContent: "center", padding: bp(32,24,20) }}>
        <div style={{ width: "100%", maxWidth: 400 }}>
          <div style={{ textAlign: "center", marginBottom: 32 }}>
            <img src="assets/logomark.svg" alt="OMT Centar" style={{ width: 56, marginBottom: 16 }} />
            <h1 style={{ margin: "0 0 8px", fontSize: 26, fontWeight: 800, letterSpacing: "-0.02em" }}>Admin panel</h1>
            <p style={{ margin: 0, fontSize: 14, color: "var(--text-tertiary)" }}>OMT Centar — upravljanje kursevima</p>
          </div>
          <div style={{ background: "#fff", borderRadius: 20, boxShadow: "var(--shadow-card)", padding: bp(32,28,24) }}>
            {lockSecs > 0 ? (
              <div style={{ textAlign: "center", padding: "16px 0" }}>
                <Icon name="shield" size={32} color="#C13515"/>
                <div style={{ marginTop: 12, fontSize: 14, fontWeight: 700, color: "#C13515" }}>Pristup privremeno blokiran</div>
                <div style={{ marginTop: 6, fontSize: 13, color: "var(--text-tertiary)" }}>
                  Pokušajte ponovo za <strong>{Math.floor(lockSecs/60)}:{String(lockSecs%60).padStart(2,"0")}</strong>.
                </div>
              </div>
            ) : (
              <form onSubmit={login}>
                <label style={lbl}>Lozinka</label>
                <input type="password" style={{ ...inp, marginBottom: 8 }} value={pw}
                  onChange={(e) => { setPw(e.target.value); setErr(""); }}
                  placeholder="Unesite lozinku" autoFocus autoComplete="current-password"/>
                {err && (
                  <div style={{ fontSize: 13, color: "#C13515", marginBottom: 12, display: "flex", alignItems: "center", gap: 6 }}>
                    <Icon name="close" size={12} color="#C13515"/> {err}
                  </div>
                )}
                <Button variant="primary" size="lg" style={{ width: "100%", justifyContent: "center", marginTop: 8 }} icon="arrowRight">
                  {loading ? "Proveravanje…" : "Prijavite se"}
                </Button>
              </form>
            )}
            <div style={{ marginTop: 16, textAlign: "center" }}>
              <a onClick={() => onNav("home")} style={{ fontSize: 13, color: "var(--text-tertiary)", cursor: "pointer" }}>Nazad na sajt</a>
            </div>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main>
      {/* Header */}
      <div style={{ background: "var(--surface-ink)", color: "#fff", padding: bp("16px 32px","14px 24px","12px 16px") }}>
        <div style={{ maxWidth: 1320, margin: "0 auto", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <img src="assets/logomark.svg" alt="" style={{ width: 28, flexShrink: 0, filter: "brightness(0) invert(1)" }} />
            <div>
              <div style={{ fontSize: bp(15,14,13), fontWeight: 700 }}>Admin Panel · OMT Centar</div>
              {!isMobile && <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", marginTop: 1 }}>Upravljanje kursevima i blogom</div>}
            </div>
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            {!isMobile && (
              <a onClick={() => onNav("home")} style={{ fontSize: 13, color: "rgba(255,255,255,0.65)", cursor: "pointer" }}>
                Pogledaj sajt
              </a>
            )}
            <Button variant="ghost" size="sm" style={{ color: "#fff", borderColor: "rgba(255,255,255,0.2)", background: "rgba(255,255,255,0.08)" }} onClick={logout}>
              Odjavi se
            </Button>
          </div>
        </div>
      </div>

      <section style={{ padding: bp("36px 32px 96px","28px 24px 72px","20px 16px 56px") }}>
        <div style={{ maxWidth: 1320, margin: "0 auto" }}>

          {/* Tab switcher */}
          <div style={{ display:"flex", gap:8, marginBottom:28, background:"var(--surface-1)", borderRadius:12, padding:4, width:"fit-content" }}>
            {[["kursevi","book","Kursevi"],["blog","edit","Blog"]].map(([key,icon,label]) => (
              <button key={key} onClick={() => setTab(key)} style={{ display:"inline-flex", alignItems:"center", gap:7, padding:"9px 18px", borderRadius:9, border:0, cursor:"pointer", fontFamily:"inherit", fontSize:13, fontWeight:700,
                background: tab === key ? "#fff" : "transparent",
                color: tab === key ? "var(--text-primary)" : "var(--text-tertiary)",
                boxShadow: tab === key ? "var(--shadow-card)" : "none",
                transition:"all 150ms" }}>
                <Icon name={icon} size={15}/> {label}
              </button>
            ))}
          </div>

          {/* ── KURSEVI TAB ── */}
          {tab === "kursevi" && (<>
            {/* Stats */}
            <div style={{ display: "grid", gridTemplateColumns: bp("repeat(4,1fr)","repeat(2,1fr)","repeat(2,1fr)"), gap: bp(16,14,10), marginBottom: 28 }}>
              {[
                { label: "Ukupno kurseva", val: courses.length, icon: "book" },
                { label: "Aktivnih", val: courses.filter(c=>c.active).length, icon: "checkCircle" },
                { label: "Neaktivnih", val: courses.filter(c=>!c.active).length, icon: "minus" },
                { label: "Kapacitet", val: courses.filter(c=>c.active).length + " mesta", icon: "users" },
              ].map(({ label, val, icon }) => (
                <div key={label} style={{ background: "#fff", borderRadius: bp(16,14,12), padding: bp("20px 22px","16px 18px","14px 16px"), boxShadow: "var(--shadow-card)", display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 40, height: 40, borderRadius: 12, flexShrink: 0, background: "linear-gradient(135deg,rgba(4,175,143,0.12),rgba(23,164,181,0.1))", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <Icon name={icon} size={20} color="var(--omt-green)" />
                  </div>
                  <div>
                    <div style={{ fontSize: bp(20,18,18), fontWeight: 800, letterSpacing: "-0.02em" }}>{val}</div>
                    <div style={{ fontSize: 11, color: "var(--text-tertiary)", marginTop: 2 }}>{label}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: isMobile ? "flex-start" : "center", marginBottom: 16, flexWrap: "wrap", gap: 12, flexDirection: isMobile ? "column" : "row" }}>
              <h2 style={{ margin: 0, fontSize: bp(20,18,17), fontWeight: 700, letterSpacing: "-0.018em" }}>Kursevi</h2>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                {!isMobile && <Button variant="secondary" size="md" iconLeft="edit" onClick={resetDefaults}>Vrati podrazumevane</Button>}
                <Button variant="primary" size="md" iconLeft="plus" onClick={() => setEditing("new")}>Novi kurs</Button>
              </div>
            </div>
            <div style={{ background: "#fff", borderRadius: bp(20,18,14), boxShadow: "var(--shadow-card)", overflow: "hidden" }}>
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: bp(14,13,13), minWidth: isMobile ? 560 : "auto" }}>
                  <thead>
                    <tr style={{ background: "var(--surface-1)", borderBottom: "1px solid var(--border-subtle)" }}>
                      {(isMobile ? ["Naziv kursa","Cena","Status","Akcije"] : ["Naziv kursa","Region","Nivo","Trajanje","Cena","Datum","Status","Akcije"]).map(h => (
                        <th key={h} style={{ padding: bp("14px 16px","12px 14px","10px 12px"), textAlign: "left", fontSize: 11, fontWeight: 700, color: "var(--text-tertiary)", letterSpacing: "0.06em", textTransform: "uppercase", whiteSpace: "nowrap" }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {courses.map((c, i) => (
                      <tr key={c.id} style={{ borderBottom: "1px solid var(--border-subtle)", opacity: c.active ? 1 : 0.55, background: i % 2 === 0 ? "#fff" : "var(--surface-1)" }}>
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px"), fontWeight: 600, maxWidth: isMobile ? 160 : "auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.title}</td>
                        {!isMobile && <td style={{ padding: "14px 16px", color: "var(--text-secondary)" }}>{c.region}</td>}
                        {!isMobile && <td style={{ padding: "14px 16px", color: "var(--text-secondary)" }}>{c.level}</td>}
                        {!isMobile && <td style={{ padding: "14px 16px", color: "var(--text-secondary)", whiteSpace: "nowrap" }}>{c.duration} · {c.hours}</td>}
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px"), fontWeight: 700, whiteSpace: "nowrap" }}>{c.price}</td>
                        {!isMobile && <td style={{ padding: "14px 16px", color: "var(--text-secondary)", whiteSpace: "nowrap" }}>{c.startDate || "—"}</td>}
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px") }}>
                          <button onClick={() => toggle(c.id)} style={{ fontSize: 11, fontWeight: 700, padding: "3px 10px", borderRadius: 100, border: 0, cursor: "pointer",
                            background: c.active ? "rgba(4,175,143,0.12)" : "var(--surface-3)",
                            color: c.active ? "#02604F" : "var(--text-tertiary)", whiteSpace: "nowrap", fontFamily:"inherit" }}>
                            {c.active ? "Aktivan" : "Neaktivan"}
                          </button>
                        </td>
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px") }}>
                          <div style={{ display: "flex", gap: 6 }}>
                            <button onClick={() => setEditing(c.id)} style={adminBtn}><Icon name="edit" size={12}/> {!isMobile && "Uredi"}</button>
                            <button onClick={() => remove(c.id)} style={{...adminBtn, color: "#C13515"}}><Icon name="trash" size={12}/></button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {courses.length === 0 && (
                <div style={{ padding: 48, textAlign: "center", color: "var(--text-tertiary)" }}>
                  Nema kurseva. <a onClick={() => setEditing("new")} style={{ color: "var(--omt-green-ink)", cursor: "pointer", fontWeight: 600 }}>Dodajte prvi</a>.
                </div>
              )}
            </div>
            {isMobile && <div style={{ marginTop:16, textAlign:"right" }}><Button variant="secondary" size="sm" iconLeft="edit" onClick={resetDefaults}>Vrati podrazumevane</Button></div>}
          </>)}

          {/* ── BLOG TAB ── */}
          {tab === "blog" && (<>
            {/* Blog Stats */}
            <div style={{ display: "grid", gridTemplateColumns: bp("repeat(3,1fr)","repeat(3,1fr)","repeat(2,1fr)"), gap: bp(16,14,10), marginBottom: 28 }}>
              {[
                { label: "Ukupno postova", val: blogs.length, icon: "book" },
                { label: "Objavljenih", val: blogs.filter(b=>b.active).length, icon: "checkCircle" },
                { label: "U nacrtu", val: blogs.filter(b=>!b.active).length, icon: "minus" },
              ].map(({ label, val, icon }) => (
                <div key={label} style={{ background: "#fff", borderRadius: bp(16,14,12), padding: bp("20px 22px","16px 18px","14px 16px"), boxShadow: "var(--shadow-card)", display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ width: 40, height: 40, borderRadius: 12, flexShrink: 0, background: "linear-gradient(135deg,rgba(4,175,143,0.12),rgba(23,164,181,0.1))", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <Icon name={icon} size={20} color="var(--omt-green)" />
                  </div>
                  <div>
                    <div style={{ fontSize: bp(20,18,18), fontWeight: 800, letterSpacing: "-0.02em" }}>{val}</div>
                    <div style={{ fontSize: 11, color: "var(--text-tertiary)", marginTop: 2 }}>{label}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: isMobile ? "flex-start" : "center", marginBottom: 16, flexWrap: "wrap", gap: 12, flexDirection: isMobile ? "column" : "row" }}>
              <h2 style={{ margin: 0, fontSize: bp(20,18,17), fontWeight: 700, letterSpacing: "-0.018em" }}>Blog postovi</h2>
              <Button variant="primary" size="md" iconLeft="plus" onClick={() => setEditingBlog("new")}>Novi post</Button>
            </div>
            <div style={{ background: "#fff", borderRadius: bp(20,18,14), boxShadow: "var(--shadow-card)", overflow: "hidden" }}>
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: bp(14,13,13), minWidth: isMobile ? 500 : "auto" }}>
                  <thead>
                    <tr style={{ background: "var(--surface-1)", borderBottom: "1px solid var(--border-subtle)" }}>
                      {(isMobile ? ["Naslov","Kat.","Status","Akcije"] : ["Naslov","Kategorija","Datum","Trajanje","Istaknuto","Status","Akcije"]).map(h => (
                        <th key={h} style={{ padding: bp("14px 16px","12px 14px","10px 12px"), textAlign: "left", fontSize: 11, fontWeight: 700, color: "var(--text-tertiary)", letterSpacing: "0.06em", textTransform: "uppercase", whiteSpace: "nowrap" }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {blogs.map((b, i) => (
                      <tr key={b.id} style={{ borderBottom: "1px solid var(--border-subtle)", opacity: b.active ? 1 : 0.5, background: i % 2 === 0 ? "#fff" : "var(--surface-1)" }}>
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px"), fontWeight: 600, maxWidth: isMobile ? 140 : 280, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{b.title}</td>
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px"), color: "var(--text-secondary)", whiteSpace: "nowrap" }}>{b.cat}</td>
                        {!isMobile && <td style={{ padding: "14px 16px", color: "var(--text-secondary)", whiteSpace: "nowrap" }}>{b.date || "—"}</td>}
                        {!isMobile && <td style={{ padding: "14px 16px", color: "var(--text-secondary)", whiteSpace: "nowrap" }}>{b.read}</td>}
                        {!isMobile && <td style={{ padding: "14px 16px" }}>
                          {b.featured ? <span style={{ fontSize:11, fontWeight:700, color:"var(--omt-green-ink)", background:"rgba(4,175,143,0.1)", padding:"2px 8px", borderRadius:100 }}>Da</span> : <span style={{ fontSize:11, color:"var(--text-tertiary)" }}>—</span>}
                        </td>}
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px") }}>
                          <button onClick={() => toggleBlog(b.id)} style={{ fontSize: 11, fontWeight: 700, padding: "3px 10px", borderRadius: 100, border: 0, cursor: "pointer",
                            background: b.active ? "rgba(4,175,143,0.12)" : "var(--surface-3)",
                            color: b.active ? "#02604F" : "var(--text-tertiary)", whiteSpace: "nowrap", fontFamily:"inherit" }}>
                            {b.active ? "Objavljeno" : "Nacrt"}
                          </button>
                        </td>
                        <td style={{ padding: bp("14px 16px","12px 14px","10px 12px") }}>
                          <div style={{ display: "flex", gap: 6 }}>
                            <button onClick={() => setEditingBlog(b.id)} style={adminBtn}><Icon name="edit" size={12}/> {!isMobile && "Uredi"}</button>
                            <button onClick={() => removeBlog(b.id)} style={{...adminBtn, color: "#C13515"}}><Icon name="trash" size={12}/></button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {blogs.length === 0 && (
                <div style={{ padding: 48, textAlign: "center", color: "var(--text-tertiary)" }}>
                  Nema postova. <a onClick={() => setEditingBlog("new")} style={{ color: "var(--omt-green-ink)", cursor: "pointer", fontWeight: 600 }}>Dodajte prvi</a>.
                </div>
              )}
            </div>
          </>)}

        </div>
      </section>

      {/* Course Editor Modal */}
      {editing && editingCourse && (
        <AdminCourseEditor course={editingCourse} isNew={editing === "new"} onSave={save} onCancel={() => setEditing(null)} isMobile={isMobile} />
      )}
      {/* Blog Editor Modal */}
      {editingBlog && editingBlogData && (
        <AdminBlogEditor blog={editingBlogData} isNew={editingBlog === "new"} onSave={saveBlog} onCancel={() => setEditingBlog(null)} isMobile={isMobile} />
      )}
    </main>
  );
}

function AdminCourseEditor({ course, isNew, onSave, onCancel, isMobile }) {
  const [f, setF] = useStateAdm({
    ...course,
    imageUrl: course.imageUrl || "",
    active: course.active !== false,
    techniques: (course.techniques || []).join(", "),
    curriculum: (course.curriculum || []).join("\n"),
  });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const handleImage = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setF(prev => ({ ...prev, imageUrl: ev.target.result }));
    reader.readAsDataURL(file);
  };

  const inp = { width: "100%", padding: "11px 14px", fontSize: 14, fontFamily: "inherit", border: "1.5px solid var(--border-default)", borderRadius: 8, outline: 0, background: "#fff", color: "var(--text-primary)" };
  const lbl = { display: "block", fontSize: 11, fontWeight: 700, color: "var(--text-secondary)", marginBottom: 6, letterSpacing: "0.04em", textTransform: "uppercase" };

  const submit = () => {
    const data = {
      ...f,
      active: f.active !== false,
      techniques: f.techniques.split(",").map(t => t.trim()).filter(Boolean),
      curriculum: f.curriculum.split("\n").map(t => t.trim()).filter(Boolean),
    };
    onSave(data);
  };

  const colSpan = isMobile ? "span 1" : "span 2";

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(14,26,23,0.6)", display: "flex", alignItems: "center", justifyContent: "center", padding: isMobile ? 12 : 32, backdropFilter: "blur(6px)" }} onClick={onCancel}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "#fff", borderRadius: isMobile ? 20 : 24, padding: isMobile ? "24px 20px" : 36, maxWidth: 760, width: "100%", maxHeight: "92vh", overflow: "auto", boxShadow: "var(--shadow-hover)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
          <div>
            <Eyebrow>{isNew ? "Novi kurs" : "Uredi kurs"}</Eyebrow>
            <h2 style={{ margin: "8px 0 0", fontSize: isMobile ? 18 : 22, fontWeight: 700, letterSpacing: "-0.018em" }}>{isNew ? "Dodaj novi kurs" : f.title}</h2>
          </div>
          <button onClick={onCancel} style={{ background: "var(--surface-2)", border: 0, borderRadius: "50%", width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 }}>
            <Icon name="close" size={18}/>
          </button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 14 }}>
          <div style={{ gridColumn: colSpan }}>
            <label style={lbl}>Naziv kursa *</label>
            <input style={inp} value={f.title} onChange={set("title")} placeholder="HVLA vratne kičme — kompletan modul"/>
          </div>
          <div><label style={lbl}>Region</label>
            <select style={inp} value={f.region} onChange={set("region")}>
              <option>Vratna kičma</option><option>Torakalna</option><option>LS kičma</option><option>SI zglob</option><option>Visceralno</option><option>Periferne</option><option>Kompletan program</option>
            </select>
          </div>
          <div><label style={lbl}>Nivo</label>
            <select style={inp} value={f.level} onChange={set("level")}>
              <option>Početni</option><option>Početni / Srednji</option><option>Srednji</option><option>Srednji / Napredni</option><option>Napredni</option>
            </select>
          </div>
          <div><label style={lbl}>Trajanje</label><input style={inp} value={f.duration} onChange={set("duration")} placeholder="2 dana"/></div>
          <div><label style={lbl}>Broj sati</label><input style={inp} value={f.hours} onChange={set("hours")} placeholder="16h"/></div>
          <div><label style={lbl}>Cena</label><input style={inp} value={f.price} onChange={set("price")} placeholder="€680"/></div>
          <div><label style={lbl}>Datum početka</label><input style={inp} value={f.startDate} onChange={set("startDate")} placeholder="12.05.2026"/></div>
          <div><label style={lbl}>Prijave do</label><input style={inp} value={f.deadline} onChange={set("deadline")} placeholder="07.05.2026"/></div>
          <div><label style={lbl}>Lokacija</label><input style={inp} value={f.location} onChange={set("location")} placeholder="OMT Centar · Beograd, Centar"/></div>
          <div style={{ gridColumn: colSpan }}>
            <label style={lbl}>Broj polaznika</label>
            <input style={inp} value={f.spots} onChange={set("spots")} placeholder="1 polaznik"/>
          </div>
          <div style={{ gridColumn: colSpan }}>
            <label style={lbl}>Slika kursa</label>
            {f.imageUrl ? (
              <div style={{ marginBottom: 10, position: "relative", borderRadius: 10, overflow: "hidden", maxHeight: 180 }}>
                <img src={f.imageUrl} alt="" style={{ width: "100%", objectFit: "cover", maxHeight: 180, display: "block" }} />
                <button type="button" onClick={() => setF(prev => ({ ...prev, imageUrl: "" }))}
                  style={{ position: "absolute", top: 8, right: 8, background: "rgba(14,26,23,0.75)", color: "#fff", border: 0, borderRadius: "50%", width: 28, height: 28, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="close" size={14}/>
                </button>
              </div>
            ) : (
              <div style={{ border: "1.5px dashed var(--border-default)", borderRadius: 10, padding: "20px 16px", textAlign: "center", marginBottom: 2, background: "var(--surface-1)" }}>
                <Icon name="image" size={24} color="var(--text-tertiary)"/>
                <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 6 }}>Izaberite fotografiju kursa</div>
              </div>
            )}
            <input type="file" accept="image/*" onChange={handleImage}
              style={{ marginTop: 6, fontSize: 13, color: "var(--text-secondary)", width: "100%" }}/>
          </div>
          <div style={{ gridColumn: colSpan }}>
            <label style={lbl}>Badge oznaka (npr. "Popularno", "Novo")</label>
            <input style={inp} value={f.badge} onChange={set("badge")} placeholder="Popularno"/>
          </div>
          <div style={{ gridColumn: colSpan }}>
            <label style={lbl}>Tehnike (odvojene zarezima)</label>
            <input style={inp} value={f.techniques} onChange={set("techniques")} placeholder="O.A.A. C0-C1-C2, Cradle hold, Myofascial"/>
          </div>
          <div style={{ gridColumn: colSpan }}>
            <label style={lbl}>Program kursa — šta se uči (svaka stavka u novom redu)</label>
            <textarea style={{...inp, minHeight: 120, resize: "vertical"}} value={f.curriculum} onChange={set("curriculum")} placeholder={"Anatomija i biomehanika regiona\nPalpatorna dijagnostika\nVođena praksa tehnika"}/>
          </div>
          <div style={{ gridColumn: colSpan }}>
            <label style={lbl}>Opis</label>
            <textarea style={{...inp, minHeight: 90, resize: "vertical"}} value={f.description} onChange={set("description")} placeholder="Kratki opis kursa..."/>
          </div>
        </div>
        {!isNew && (
          <label style={{ display:"flex", gap:10, alignItems:"center", marginTop:20, padding:"12px 14px", background:"var(--surface-1)", borderRadius:10, cursor:"pointer" }}>
            <input type="checkbox" checked={f.active !== false} onChange={e => setF(prev => ({ ...prev, active: e.target.checked }))}
              style={{ accentColor:"var(--omt-green)", width:16, height:16 }}/>
            <div>
              <div style={{ fontSize:13, fontWeight:700, color:"var(--text-primary)" }}>Aktivan kurs</div>
              <div style={{ fontSize:11, color:"var(--text-tertiary)" }}>Neaktivni kursevi se ne prikazuju posetiteljima</div>
            </div>
          </label>
        )}
        <div style={{ marginTop: 24, display: "flex", gap: 12, justifyContent: "flex-end" }}>
          <Button variant="secondary" onClick={onCancel}>Otkaži</Button>
          <Button variant="primary" icon="check" onClick={submit}>{isNew ? "Dodaj kurs" : "Sačuvaj izmene"}</Button>
        </div>
      </div>
    </div>
  );
}

function AdminBlogEditor({ blog, isNew, onSave, onCancel, isMobile }) {
  const [f, setF] = useStateAdm({ ...blog });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const setCheck = (k) => (e) => setF({ ...f, [k]: e.target.checked });

  const handleImage = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setF(prev => ({ ...prev, imageUrl: ev.target.result }));
    reader.readAsDataURL(file);
  };

  const inp = { width: "100%", padding: "11px 14px", fontSize: 14, fontFamily: "inherit", border: "1.5px solid var(--border-default)", borderRadius: 8, outline: 0, background: "#fff", color: "var(--text-primary)" };
  const lbl = { display: "block", fontSize: 11, fontWeight: 700, color: "var(--text-secondary)", marginBottom: 6, letterSpacing: "0.04em", textTransform: "uppercase" };
  const colSpan = isMobile ? "span 1" : "span 2";

  return (
    <div style={{ position:"fixed", inset:0, zIndex:100, background:"rgba(14,26,23,0.6)", display:"flex", alignItems:"center", justifyContent:"center", padding:isMobile?12:32, backdropFilter:"blur(6px)" }} onClick={onCancel}>
      <div onClick={e => e.stopPropagation()} style={{ background:"#fff", borderRadius:isMobile?20:24, padding:isMobile?"24px 20px":36, maxWidth:680, width:"100%", maxHeight:"92vh", overflow:"auto", boxShadow:"var(--shadow-hover)" }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:24 }}>
          <div>
            <Eyebrow>{isNew ? "Novi post" : "Uredi post"}</Eyebrow>
            <h2 style={{ margin:"8px 0 0", fontSize:isMobile?18:22, fontWeight:700, letterSpacing:"-0.018em" }}>{isNew ? "Dodaj blog post" : f.title}</h2>
          </div>
          <button onClick={onCancel} style={{ background:"var(--surface-2)", border:0, borderRadius:"50%", width:36, height:36, display:"flex", alignItems:"center", justifyContent:"center", cursor:"pointer", flexShrink:0 }}>
            <Icon name="close" size={18}/>
          </button>
        </div>
        <div style={{ display:"grid", gridTemplateColumns:isMobile?"1fr":"1fr 1fr", gap:14 }}>
          <div style={{ gridColumn:colSpan }}>
            <label style={lbl}>Naslov *</label>
            <input style={inp} value={f.title} onChange={set("title")} placeholder="HVLA tehnike: kada i kako ih primeniti"/>
          </div>
          <div>
            <label style={lbl}>Kategorija</label>
            <select style={inp} value={f.cat} onChange={set("cat")}>
              {["Tehnike","Klinička praksa","Anatomija","Karijera","Komunikacija","Osteopatija","Kiropraktika"].map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
          <div>
            <label style={lbl}>Trajanje čitanja</label>
            <input style={inp} value={f.read} onChange={set("read")} placeholder="7 min"/>
          </div>
          <div style={{ gridColumn:colSpan }}>
            <label style={lbl}>Datum objave</label>
            <input style={inp} value={f.date} onChange={set("date")} placeholder="15.04.2026"/>
          </div>
          <div style={{ gridColumn:colSpan }}>
            <label style={lbl}>Kratak opis (prikazuje se na kartici)</label>
            <textarea style={{...inp, minHeight:80, resize:"vertical"}} value={f.excerpt} onChange={set("excerpt")} placeholder="Jedna do dve rečenice koje motivišu čitanje..."/>
          </div>
          <div style={{ gridColumn:colSpan }}>
            <label style={lbl}>Naslovna slika</label>
            {f.imageUrl ? (
              <div style={{ marginBottom:10, position:"relative", borderRadius:10, overflow:"hidden", maxHeight:160 }}>
                <img src={f.imageUrl} alt="" style={{ width:"100%", objectFit:"cover", maxHeight:160, display:"block" }}/>
                <button type="button" onClick={() => setF(prev => ({ ...prev, imageUrl:"" }))}
                  style={{ position:"absolute", top:8, right:8, background:"rgba(14,26,23,0.75)", color:"#fff", border:0, borderRadius:"50%", width:28, height:28, cursor:"pointer", display:"flex", alignItems:"center", justifyContent:"center" }}>
                  <Icon name="close" size={14}/>
                </button>
              </div>
            ) : (
              <div style={{ border:"1.5px dashed var(--border-default)", borderRadius:10, padding:"16px", textAlign:"center", marginBottom:2, background:"var(--surface-1)" }}>
                <Icon name="image" size={22} color="var(--text-tertiary)"/>
                <div style={{ fontSize:12, color:"var(--text-tertiary)", marginTop:4 }}>Izaberite fotografiju</div>
              </div>
            )}
            <input type="file" accept="image/*" onChange={handleImage} style={{ marginTop:6, fontSize:13, color:"var(--text-secondary)", width:"100%" }}/>
          </div>
          <div style={{ gridColumn:colSpan, display:"flex", flexDirection:"column", gap:10 }}>
            <label style={{ display:"flex", gap:10, alignItems:"center", padding:"12px 14px", background:"var(--surface-1)", borderRadius:10, cursor:"pointer" }}>
              <input type="checkbox" checked={!!f.featured} onChange={setCheck("featured")} style={{ accentColor:"var(--omt-green)", width:16, height:16 }}/>
              <div>
                <div style={{ fontSize:13, fontWeight:700, color:"var(--text-primary)" }}>Istaknuti post</div>
                <div style={{ fontSize:11, color:"var(--text-tertiary)" }}>Prikazuje se sa oznakom "Izdvojeno" na blogu</div>
              </div>
            </label>
            {!isNew && (
              <label style={{ display:"flex", gap:10, alignItems:"center", padding:"12px 14px", background:"var(--surface-1)", borderRadius:10, cursor:"pointer" }}>
                <input type="checkbox" checked={f.active !== false} onChange={e => setF(prev => ({ ...prev, active: e.target.checked }))} style={{ accentColor:"var(--omt-green)", width:16, height:16 }}/>
                <div>
                  <div style={{ fontSize:13, fontWeight:700, color:"var(--text-primary)" }}>Objavljen</div>
                  <div style={{ fontSize:11, color:"var(--text-tertiary)" }}>Neobjavljeni postovi nisu vidljivi posetiocima</div>
                </div>
              </label>
            )}
          </div>
        </div>
        <div style={{ marginTop:24, display:"flex", gap:12, justifyContent:"flex-end" }}>
          <Button variant="secondary" onClick={onCancel}>Otkaži</Button>
          <Button variant="primary" icon="check" onClick={() => onSave(f)}>{isNew ? "Dodaj post" : "Sačuvaj izmene"}</Button>
        </div>
      </div>
    </div>
  );
}

window.AdminPage = AdminPage;
