<!doctype html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Panel</title>

<style>
*{box-sizing:border-box}
body{
  margin:0;
  font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Inter,Arial;
  background:
    radial-gradient(900px 500px at 10% 10%, #bae6fd, transparent),
    radial-gradient(800px 500px at 90% 20%, #fbcfe8, transparent),
    linear-gradient(135deg,#fbcfe8,#bae6fd,#fef3c7);
  min-height:100vh;
  color:#0f172a;
}
.container{max-width:720px;margin:auto;padding:20px 16px 32px}
.glass{
  background:linear-gradient(180deg,rgba(255,255,255,.9),rgba(255,255,255,.65));
  backdrop-filter:blur(22px);
  border-radius:22px;
  padding:16px;
  margin-bottom:14px;
  box-shadow:0 18px 40px rgba(0,0,0,.14);
}
.title{font-size:28px;font-weight:900}
.subtitle{font-size:13px;color:#475569}

.segment{display:flex;background:rgba(255,255,255,.6);border-radius:16px;padding:4px;margin-top:12px}
.segment button{
  flex:1;border:none;background:transparent;padding:10px;
  font-weight:800;border-radius:12px;cursor:pointer;color:#475569
}
.segment button.active{
  background:white;color:#0f172a;
  box-shadow:0 6px 16px rgba(0,0,0,.18)
}

label{font-size:13px;font-weight:800;margin-bottom:6px;display:block}
input,textarea{
  width:100%;padding:12px 14px;border-radius:16px;
  border:1px solid rgba(148,163,184,.35);
}
textarea{white-space:pre-wrap;resize:none;line-height:1.5}
.hidden{display:none}

.btn{
  width:100%;padding:14px;border:none;border-radius:18px;
  font-weight:900;color:white;
  background:linear-gradient(180deg,#fb7185,#ec4899);
}
.btn-sm{padding:10px;font-size:14px;border-radius:14px}

.preview img{width:100%;border-radius:16px;margin-top:10px}

.note-actions{display:flex;gap:8px;margin-top:8px}
.btn-clear{background:#e5e7eb}
.btn-preview{background:#60a5fa;color:#fff}

.name-item{
  display:flex;justify-content:space-between;align-items:center;
  background:rgba(255,255,255,.7);
  padding:10px 12px;border-radius:14px;margin-bottom:6px
}
.name-item span{font-weight:700}
.name-item button{border:none;background:none;font-size:16px;cursor:pointer}
.search{margin-bottom:8px}
</style>
</head>

<body>
<div class="container">

<!-- HEADER -->
<div class="glass">
  <div class="title">Admin Panel</div>
  <div class="subtitle">Konten & Nama (Auto Save • Anti Duplikat • Search)</div>

  <div class="segment">
    <button id="btnImage" class="active">🖼️ Gambar</button>
    <button id="btnYoutube">🎬 YouTube</button>
  </div>
</div>

<!-- IMAGE -->
<div id="imageForm" class="glass">
  <label>Upload Gambar</label>
  <input type="file" id="imgFile" accept="image/*">
  <button id="uploadBtn" class="btn btn-sm" style="margin-top:8px">⬆️ Upload</button>

  <label style="margin-top:12px">Atau Link Gambar</label>
  <input id="imgLink" placeholder="https://gambar.jpg">
  <button id="useLink" class="btn btn-sm" style="margin-top:8px">Preview Link</button>

  <div id="imgPreview" class="preview"></div>
</div>

<!-- YOUTUBE -->
<div id="youtubeForm" class="glass hidden">
  <label>Link YouTube</label>
  <input id="ytLink" placeholder="https://youtube.com/watch?v=...">
</div>

<!-- NOTE -->
<div class="glass">
  <label>Catatan</label>
  <textarea id="note" rows="5"></textarea>
  <div class="note-actions">
    <button id="btnClear" class="btn-clear btn-sm">🧹 Clear Konten</button>
    <button id="btnPreview" class="btn-preview btn-sm">👁️ Preview</button>
  </div>
</div>

<!-- SAVE -->
<div class="glass">
  <button id="save" class="btn">💾 Simpan Konten</button>
</div>

<!-- NAMES -->
<div class="glass">
  <label>Daftar Nama</label>

  <input id="searchName" class="search" placeholder="🔍 Cari nama...">

  <input id="newName" placeholder="Tambah nama baru">
  <button id="addName" class="btn btn-sm" style="margin-top:8px">➕ Tambah Nama</button>

  <div id="nameList" style="margin-top:12px"></div>
</div>

</div>

<script>
let finalImageURL="";
let names=[];
let filteredNames=[];

/* ===== SEGMENT ===== */
btnImage.onclick=()=>{
  btnImage.classList.add("active");
  btnYoutube.classList.remove("active");
  imageForm.classList.remove("hidden");
  youtubeForm.classList.add("hidden");
};
btnYoutube.onclick=()=>{
  btnYoutube.classList.add("active");
  btnImage.classList.remove("active");
  youtubeForm.classList.remove("hidden");
  imageForm.classList.add("hidden");
};

/* ===== LOAD DATA ===== */
async function loadData(){
  const res=await fetch("get_json.php",{cache:"no-store"});
  const d=await res.json();

  note.value=d.note||"";

  if(d.mode==="youtube"){
    btnYoutube.click();
    ytLink.value=d.youtube||"";
  }else{
    btnImage.click();
    finalImageURL=d.image||"";
    if(d.image) imgPreview.innerHTML=`<img src="${d.image}">`;
  }

  names=Array.isArray(d.names)?d.names:[];
  sortNames();
  filteredNames=[...names];
  renderNames();
}
loadData();

/* ===== SORT ===== */
function sortNames(){
  names.sort((a,b)=>a.localeCompare(b,"id",{sensitivity:"base"}));
}

/* ===== RENDER ===== */
function renderNames(){
  nameList.innerHTML="";
  filteredNames.forEach((n)=>{
    const i=names.indexOf(n);
    const d=document.createElement("div");
    d.className="name-item";
    d.innerHTML=`
      <span>${n}</span>
      <div>
        <button onclick="editName(${i})">✏️</button>
        <button onclick="deleteName(${i})">🗑️</button>
      </div>`;
    nameList.appendChild(d);
  });
}

/* ===== SEARCH ===== */
searchName.oninput=()=>{
  const q=searchName.value.toLowerCase();
  filteredNames=names.filter(n=>n.toLowerCase().includes(q));
  renderNames();
};

/* ===== SAVE NAMES ONLY ===== */
async function saveNamesOnly(){
  const res=await fetch("get_json.php",{cache:"no-store"});
  const d=await res.json();

  const payload={
    mode:d.mode||"image",
    image:d.image||"",
    youtube:d.youtube||"",
    note:d.note||"",
    names:names
  };

  await fetch("save_json.php",{
    method:"POST",
    headers:{"Content-Type":"application/json"},
    body:JSON.stringify(payload)
  });
}

/* ===== ADD NAME ===== */
addName.onclick=async()=>{
  const v=newName.value.trim();
  if(!v) return;
  if(names.some(n=>n.toLowerCase()===v.toLowerCase())){
    alert("⚠️ Nama sudah ada");
    return;
  }
  names.push(v);
  sortNames();
  filteredNames=[...names];
  newName.value="";
  renderNames();
  await saveNamesOnly();
};

/* ===== EDIT NAME ===== */
window.editName=async(i)=>{
  const v=prompt("Edit nama:",names[i]);
  if(v===null) return;
  const nv=v.trim();
  if(!nv) return;

  if(names.some((n,idx)=>idx!==i && n.toLowerCase()===nv.toLowerCase())){
    alert("⚠️ Nama sudah ada");
    return;
  }
  names[i]=nv;
  sortNames();
  filteredNames=[...names];
  renderNames();
  await saveNamesOnly();
};

/* ===== DELETE NAME ===== */
window.deleteName=async(i)=>{
  if(confirm("Hapus nama ini?")){
    names.splice(i,1);
    filteredNames=[...names];
    renderNames();
    await saveNamesOnly();
  }
};

/* ===== CLEAR CONTENT ===== */
btnClear.onclick=()=>{
  note.value="";
  ytLink.value="";
  imgLink.value="";
  finalImageURL="";
  imgPreview.innerHTML="";
  btnImage.click();
};

/* ===== UPLOAD IMAGE ===== */
uploadBtn.onclick=async()=>{
  if(!imgFile.files[0]) return alert("Pilih gambar dulu");
  const fd=new FormData();
  fd.append("image",imgFile.files[0]);

  uploadBtn.disabled=true;
  uploadBtn.textContent="⏳ Uploading...";
  const res=await fetch("upload_image.php",{method:"POST",body:fd});
  const j=await res.json();
  uploadBtn.disabled=false;
  uploadBtn.textContent="⬆️ Upload";

  if(j.ok){
    finalImageURL=j.url;
    imgPreview.innerHTML=`<img src="${j.url}">`;
  }else alert(j.error||"Upload gagal");
};

/* ===== LINK IMAGE ===== */
useLink.onclick=()=>{
  if(!imgLink.value) return alert("Isi link gambar");
  finalImageURL=imgLink.value;
  imgPreview.innerHTML=`<img src="${finalImageURL}">`;
};

/* ===== SAVE CONTENT ===== */
save.onclick=async()=>{
  const isYT=btnYoutube.classList.contains("active");
  const payload={
    mode:isYT?"youtube":"image",
    image:isYT?"":finalImageURL,
    youtube:isYT?ytLink.value:"",
    note:note.value,
    names:names
  };
  await fetch("save_json.php",{
    method:"POST",
    headers:{"Content-Type":"application/json"},
    body:JSON.stringify(payload)
  });
  alert("✅ Konten tersimpan");
};
</script>
</body>
</html>