/* ============================================================
   ADMIN + PORTOFOLIO LIVE (Firebase)
   - usePortfolio(): baca koleksi 'portfolio' dari Firestore (realtime).
   - AdminGate: muncul saat URL diakhiri #admin → login → kelola video.
   Hooks (useState/useEffect/dst) sudah di-destructure global di cv-components.jsx.
   ============================================================ */

/* ---------- Ekstrak ID YouTube dari berbagai bentuk link ---------- */
function ytId(input) {
  if (!input) return "";
  const s = String(input).trim();
  // Sudah berupa ID polos (11 karakter)
  if (/^[a-zA-Z0-9_-]{11}$/.test(s)) return s;
  try {
    const u = new URL(s.startsWith("http") ? s : "https://" + s);
    const host = u.hostname.replace(/^www\./, "").replace(/^m\./, "");
    if (host === "youtu.be") {
      const id = u.pathname.slice(1, 12);
      return /^[a-zA-Z0-9_-]{11}$/.test(id) ? id : "";
    }
    if (host.endsWith("youtube.com")) {
      const v = u.searchParams.get("v");
      if (v && /^[a-zA-Z0-9_-]{11}$/.test(v)) return v;
      const m = u.pathname.match(/\/(?:shorts|embed|v|live)\/([a-zA-Z0-9_-]{11})/);
      if (m) return m[1];
    }
  } catch (e) {}
  // Cadangan: cari pola ID di mana saja
  const m = s.match(/[a-zA-Z0-9_-]{11}/);
  return m ? m[0] : "";
}

/* ---------- Hook: portofolio realtime ---------- */
function usePortfolio() {
  const [items, setItems] = useState([]);
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    if (!window.FB || !window.FB.db) { setLoaded(true); return; }
    const unsub = window.FB.db
      .collection("portfolio")
      .orderBy("order", "asc")
      .onSnapshot(
        (snap) => {
          const arr = [];
          snap.forEach((doc) => {
            const d = doc.data() || {};
            arr.push({
              _docId: doc.id,
              id: d.videoId || "",
              title: d.title || "",
              kind: d.kind === "featured" ? "featured" : "shorts",
              order: typeof d.order === "number" ? d.order : 0,
            });
          });
          setItems(arr);
          setLoaded(true);
        },
        (err) => { console.error("portfolio snapshot:", err); setLoaded(true); }
      );
    return () => unsub();
  }, []);

  const shorts = items.filter((x) => x.kind !== "featured");
  const featured = items.filter((x) => x.kind === "featured");
  return { shorts, featured, all: items, loaded, empty: loaded && items.length === 0 };
}

/* ---------- Deteksi #admin di URL ---------- */
function useHashAdmin() {
  const read = () =>
    typeof location !== "undefined" && location.hash.toLowerCase().replace(/\/$/, "") === "#admin";
  const [on, setOn] = useState(read);
  useEffect(() => {
    const h = () => setOn(read());
    window.addEventListener("hashchange", h);
    return () => window.removeEventListener("hashchange", h);
  }, []);
  const close = () => {
    if (location.hash) history.replaceState(null, "", location.pathname + location.search);
    setOn(false);
  };
  return [on, close];
}

/* ---------- Status login ---------- */
function useAuthUser() {
  const [user, setUser] = useState(null);
  const [ready, setReady] = useState(false);
  useEffect(() => {
    if (!window.FB || !window.FB.auth) { setReady(true); return; }
    const unsub = window.FB.auth.onAuthStateChanged((u) => { setUser(u); setReady(true); });
    return () => unsub();
  }, []);
  return { user, ready };
}

/* ---------- Gerbang admin ---------- */
function AdminGate({ accent }) {
  const [open, close] = useHashAdmin();
  if (!open) return null;
  return <AdminOverlay accent={accent} onClose={close} />;
}

function AdminOverlay({ accent, onClose }) {
  const { user, ready } = useAuthUser();
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const noFB = !window.FB;
  return (
    <div className="adm-root" style={{ "--accent": accent }}>
      <div className="adm-scrim" onClick={onClose} />
      <div className="adm-card" role="dialog" aria-modal="true">
        <button className="adm-x" onClick={onClose} aria-label="Tutup"><span /><span /></button>
        {noFB ? (
          <div className="adm-body"><div className="adm-err">Firebase belum siap. Cek koneksi atau config.</div></div>
        ) : !ready ? (
          <div className="adm-body"><div className="adm-loading">Memuat…</div></div>
        ) : !user ? (
          <AdminLogin />
        ) : (
          <AdminPanel user={user} onClose={onClose} />
        )}
      </div>
    </div>
  );
}

/* ---------- Form login ---------- */
function AdminLogin() {
  const [email, setEmail] = useState("");
  const [pass, setPass] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    if (!email.trim() || !pass) { setErr("Email & password wajib diisi."); return; }
    setErr(""); setBusy(true);
    try {
      await window.FB.auth.signInWithEmailAndPassword(email.trim(), pass);
    } catch (e) {
      setErr("Gagal masuk. Email atau password salah.");
    }
    setBusy(false);
  };

  return (
    <div className="adm-body">
      <div className="adm-kicker"><span className="adm-line" />Panel Admin</div>
      <h2 className="adm-title">Masuk</h2>
      <label className="adm-field">
        <span>Email</span>
        <input type="email" value={email} autoFocus placeholder="email@kamu.com"
          onChange={(e) => setEmail(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && submit()} />
      </label>
      <label className="adm-field">
        <span>Password</span>
        <input type="password" value={pass} placeholder="••••••••"
          onChange={(e) => setPass(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && submit()} />
      </label>
      {err && <div className="adm-err">{err}</div>}
      <button className="adm-btn adm-btn--go" disabled={busy} onClick={submit}>
        {busy ? "Memproses…" : "Masuk"}
      </button>
    </div>
  );
}

/* ---------- Panel kelola video ---------- */
function AdminPanel({ user, onClose }) {
  const { shorts, featured, all } = usePortfolio();
  const db = window.FB.db;

  const [title, setTitle] = useState("");
  const [link, setLink] = useState("");
  const [kind, setKind] = useState("shorts");
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState(null); // { type:"ok"|"err", text }

  const preview = ytId(link);

  const add = async () => {
    const vid = ytId(link);
    if (!title.trim()) return setMsg({ type: "err", text: "Judul belum diisi." });
    if (!vid) return setMsg({ type: "err", text: "Link YouTube tidak terbaca. Coba salin ulang." });
    setBusy(true); setMsg(null);
    try {
      const maxOrder = all.reduce((m, x) => Math.max(m, x.order || 0), 0);
      await db.collection("portfolio").add({
        title: title.trim(),
        videoId: vid,
        kind,
        order: maxOrder + 1,
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
      setTitle(""); setLink("");
      setMsg({ type: "ok", text: "Ditambahkan ke portofolio ✓" });
    } catch (e) {
      setMsg({ type: "err", text: "Gagal menyimpan: " + (e.message || e) });
    }
    setBusy(false);
  };

  const remove = async (it) => {
    if (!window.confirm('Hapus "' + (it.title || "video") + '"?')) return;
    try { await db.collection("portfolio").doc(it._docId).delete(); }
    catch (e) { window.alert("Gagal hapus: " + (e.message || e)); }
  };

  const rename = async (it) => {
    const t = window.prompt("Judul baru:", it.title);
    if (t == null) return;
    try { await db.collection("portfolio").doc(it._docId).update({ title: t.trim() }); }
    catch (e) { window.alert("Gagal ubah: " + (e.message || e)); }
  };

  const move = async (list, idx, dir) => {
    const a = list[idx], b = list[idx + dir];
    if (!a || !b) return;
    try {
      const batch = db.batch();
      batch.update(db.collection("portfolio").doc(a._docId), { order: b.order });
      batch.update(db.collection("portfolio").doc(b._docId), { order: a.order });
      await batch.commit();
    } catch (e) { window.alert("Gagal mengurutkan: " + (e.message || e)); }
  };

  const logout = async () => { try { await window.FB.auth.signOut(); } catch (e) {} };

  const renderList = (list, label) => (
    <div className="adm-list-block">
      <div className="adm-list-head">{label}<span className="adm-count">{list.length}</span></div>
      {list.length === 0 ? (
        <div className="adm-empty">Belum ada.</div>
      ) : (
        list.map((it, i) => (
          <div className="adm-row" key={it._docId}>
            <img className="adm-thumb" loading="lazy" alt=""
              src={"https://i.ytimg.com/vi/" + it.id + "/default.jpg"} />
            <div className="adm-row-main">
              <div className="adm-row-title">{it.title || "(tanpa judul)"}</div>
              <div className="adm-row-id">{it.id}</div>
            </div>
            <div className="adm-row-acts">
              <button className="adm-mini" title="Naik" disabled={i === 0}
                onClick={() => move(list, i, -1)}>↑</button>
              <button className="adm-mini" title="Turun" disabled={i === list.length - 1}
                onClick={() => move(list, i, 1)}>↓</button>
              <button className="adm-mini" title="Ubah judul" onClick={() => rename(it)}>✎</button>
              <button className="adm-mini adm-mini--del" title="Hapus" onClick={() => remove(it)}>✕</button>
            </div>
          </div>
        ))
      )}
    </div>
  );

  return (
    <div className="adm-body adm-body--panel">
      <div className="adm-top">
        <div>
          <div className="adm-kicker"><span className="adm-line" />Panel Admin</div>
          <h2 className="adm-title">Kelola Portofolio</h2>
          <div className="adm-user">{user.email}</div>
        </div>
      </div>

      {/* ---- Form tambah ---- */}
      <div className="adm-add">
        <label className="adm-field">
          <span>Judul pendek</span>
          <input value={title} placeholder="mis. Showreel Brand X"
            onChange={(e) => setTitle(e.target.value)} />
        </label>
        <label className="adm-field">
          <span>Link YouTube</span>
          <input value={link} placeholder="tempel link youtube / youtu.be / shorts…"
            onChange={(e) => setLink(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && add()} />
        </label>

        <div className="adm-kindrow">
          <button className={"adm-chip" + (kind === "shorts" ? " is-on" : "")}
            onClick={() => setKind("shorts")}>Shorts (potret)</button>
          <button className={"adm-chip" + (kind === "featured" ? " is-on" : "")}
            onClick={() => setKind("featured")}>Landscape</button>
        </div>

        {preview ? (
          <div className="adm-preview">
            <img alt="" src={"https://i.ytimg.com/vi/" + preview + "/default.jpg"} />
            <span>Terbaca: <b>{preview}</b></span>
          </div>
        ) : null}

        {msg && <div className={msg.type === "ok" ? "adm-ok" : "adm-err"}>{msg.text}</div>}

        <button className="adm-btn adm-btn--go" disabled={busy} onClick={add}>
          {busy ? "Menyimpan…" : "Tambah ke Portofolio"}
        </button>
      </div>

      {/* ---- Daftar ---- */}
      {renderList(shorts, "Shorts")}
      {renderList(featured, "Landscape")}

      <div className="adm-foot">
        <button className="adm-btn adm-btn--ghost" onClick={onClose}>Lihat situs</button>
        <button className="adm-btn adm-btn--ghost" onClick={logout}>Keluar</button>
      </div>
    </div>
  );
}
