<?php
declare(strict_types=1);
require __DIR__ . '/lib.php';
$logged = is_logged_in();
?>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Drop · kazamata</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%236366f1'/%3E%3Cstop offset='1' stop-color='%2322d3ee'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='64' height='64' rx='16' fill='url(%23g)'/%3E%3Cpath d='M32 14c6 8 12 13 12 21a12 12 0 1 1-24 0c0-8 6-13 12-21z' fill='%23fff' opacity='.95'/%3E%3C/svg%3E">
<style>
:root{
  --bg:#070a12;
  --panel:rgba(255,255,255,.045);
  --panel-2:rgba(255,255,255,.07);
  --line:rgba(255,255,255,.09);
  --line-strong:rgba(255,255,255,.16);
  --txt:#eef2f9;
  --muted:#8f9bb3;
  --accent:#6366f1;
  --accent-2:#22d3ee;
  --danger:#f87171;
  --radius:16px;
}
*{box-sizing:border-box}
[hidden]{display:none !important}
html,body{height:100%}
body{
  margin:0;
  font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",system-ui,sans-serif;
  color:var(--txt);
  background:
    radial-gradient(900px 600px at 12% -10%,rgba(99,102,241,.22),transparent 60%),
    radial-gradient(800px 500px at 105% 8%,rgba(34,211,238,.14),transparent 62%),
    var(--bg);
  background-attachment:fixed;
  -webkit-font-smoothing:antialiased;
  font-size:14px;
}
a{color:inherit;text-decoration:none}
button{font:inherit;color:inherit;cursor:pointer}
::selection{background:rgba(99,102,241,.45)}
::-webkit-scrollbar{width:8px;height:8px}
::-webkit-scrollbar-thumb{background:rgba(255,255,255,.13);border-radius:8px}
::-webkit-scrollbar-track{background:transparent}

.app{max-width:1080px;margin:0 auto;padding:18px 20px 60px}
header.top{display:flex;align-items:center;gap:14px;padding:6px 0 18px}
.brand{display:flex;align-items:center;gap:9px;font-weight:650;font-size:17px;letter-spacing:.3px}
.brand svg{width:26px;height:26px;flex:none}
.brand small{font-weight:400;font-size:11px;color:var(--muted);letter-spacing:1px}
.spacer{flex:1}
.storage{display:flex;align-items:center;gap:9px;font-size:12px;color:var(--muted)}
.storage .bar{width:96px;height:5px;border-radius:99px;background:rgba(255,255,255,.1);overflow:hidden}
.storage .bar i{display:block;height:100%;width:0;border-radius:99px;background:linear-gradient(90deg,var(--accent),var(--accent-2));transition:width .35s}
.iconbtn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:1px solid var(--line);background:var(--panel);transition:.18s}
.iconbtn:hover{background:var(--panel-2);border-color:var(--line-strong)}
.iconbtn svg{width:17px;height:17px}

/* 登录 */
.login-wrap{min-height:64vh;display:grid;place-items:center}
.login{width:100%;max-width:360px;padding:28px 24px;border-radius:20px;background:var(--panel);border:1px solid var(--line);text-align:center}
.login h1{font-size:16px;margin:14px 0 6px;font-weight:600}
.login p{color:var(--muted);font-size:12.5px;margin:0 0 20px;line-height:1.7}
.login .drop-logo{width:52px;height:52px;margin:0 auto}
input[type=password],input[type=text]{
  width:100%;height:42px;padding:0 14px;border-radius:11px;border:1px solid var(--line);
  background:rgba(255,255,255,.05);color:var(--txt);outline:none;font-size:14px;transition:.18s
}
input[type=password]:focus,input[type=text]:focus{border-color:rgba(99,102,241,.7);background:rgba(99,102,241,.08)}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:7px;height:40px;padding:0 18px;border-radius:11px;border:1px solid var(--line);background:var(--panel-2);transition:.18s;font-size:13.5px;font-weight:500;white-space:nowrap}
.btn:hover{border-color:var(--line-strong);background:rgba(255,255,255,.1)}
.btn.primary{background:linear-gradient(135deg,#6366f1,#4f46e5);border-color:transparent;color:#fff;font-weight:600;box-shadow:0 6px 20px -8px rgba(99,102,241,.9)}
.btn.primary:hover{filter:brightness(1.1)}
.btn.ghost{background:transparent}
.btn.danger{color:var(--danger);border-color:rgba(248,113,113,.28)}
.btn.danger:hover{background:rgba(248,113,113,.12)}
.btn.block{width:100%}
.btn:disabled{opacity:.45;cursor:not-allowed}

/* 拖拽区 */
.dropzone{
  position:relative;border:1.5px dashed var(--line-strong);border-radius:calc(var(--radius) + 4px);
  padding:38px 20px;text-align:center;transition:border-color .18s,background .18s;
  background:linear-gradient(180deg,rgba(255,255,255,.035),rgba(255,255,255,.012));
  cursor:pointer;overflow:hidden
}
.dropzone:hover,.dropzone.over{border-color:rgba(99,102,241,.85);background:rgba(99,102,241,.09)}
.dropzone .cloud{width:46px;height:46px;margin:0 auto 12px;color:#a5b4fc}
.dropzone h2{margin:0 0 6px;font-size:15.5px;font-weight:600}
.dropzone p{margin:0;font-size:12.5px;color:var(--muted);line-height:1.7}
.dropzone .pill{display:inline-block;margin-top:12px;font-size:11.5px;color:var(--muted);border:1px solid var(--line);border-radius:99px;padding:4px 11px}

.toolrow{display:flex;align-items:center;gap:10px;margin:14px 0 4px;flex-wrap:wrap}
select{height:36px;padding:0 30px 0 12px;border-radius:10px;border:1px solid var(--line);background:rgba(255,255,255,.05);color:var(--txt);outline:none;font-size:13px;appearance:none;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'%3E%3Cpath d='M1 3l4 4 4-4' stroke='%238f9bb3' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");
  background-repeat:no-repeat;background-position:right 11px center}
.toolrow .hint{font-size:12px;color:var(--muted)}

/* 队列 */
.queue{margin-top:12px;display:flex;flex-direction:column;gap:8px}
.qitem{display:flex;align-items:center;gap:11px;padding:11px 13px;border-radius:12px;background:var(--panel);border:1px solid var(--line)}
.qitem .qname{flex:1;min-width:0}
.qitem .qname b{display:block;font-weight:500;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.qitem .qname span{font-size:11.5px;color:var(--muted)}
.qbar{height:4px;border-radius:99px;background:rgba(255,255,255,.1);overflow:hidden;margin-top:6px}
.qbar i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--accent),var(--accent-2));transition:width .2s}
.qpct{font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums;min-width:44px;text-align:right}

/* 文本发送 */
.textbox{margin-top:14px;display:flex;gap:10px;align-items:flex-end}
.textbox textarea{flex:1;min-height:42px;max-height:180px;resize:vertical;padding:11px 13px;border-radius:11px;border:1px solid var(--line);background:rgba(255,255,255,.05);color:var(--txt);outline:none;font:inherit;line-height:1.55;transition:.18s}
.textbox textarea:focus{border-color:rgba(99,102,241,.7)}

/* 列表 */
.listhead{display:flex;align-items:center;gap:10px;margin:30px 0 12px}
.listhead h3{margin:0;font-size:14px;font-weight:600;letter-spacing:.3px}
.listhead .count{font-size:12px;color:var(--muted)}
.list{display:grid;grid-template-columns:repeat(auto-fill,minmax(268px,1fr));gap:12px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:12px;display:flex;flex-direction:column;gap:10px;transition:border-color .18s,background .18s}
.card:hover{border-color:var(--line-strong);background:rgba(255,255,255,.062)}
.card .thumb{width:100%;height:124px;border-radius:10px;background:rgba(0,0,0,.3);display:grid;place-items:center;overflow:hidden;position:relative}
.card .thumb img{width:100%;height:100%;object-fit:cover;display:block}
.card .ext{font-size:13px;font-weight:700;letter-spacing:1px;color:#c7d2fe;padding:9px 14px;border-radius:9px;border:1px solid rgba(99,102,241,.35);background:rgba(99,102,241,.16)}
.card .meta b{display:block;font-size:13px;font-weight:500;line-height:1.45;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.card .meta span{font-size:11.5px;color:var(--muted)}
.card .note{font-size:12.5px;line-height:1.6;color:#cbd5e1;max-height:76px;overflow:hidden;word-break:break-word;white-space:pre-wrap}
.card .acts{display:flex;gap:7px;flex-wrap:wrap;margin-top:auto}
.card .acts .btn{height:31px;padding:0 11px;font-size:12px;border-radius:9px}
.card .files{display:flex;flex-direction:column;gap:4px}
.card .files a{font-size:12px;color:#a5b4fc;display:flex;gap:6px;align-items:center;overflow:hidden}
.card .files a span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.card .files a em{font-style:normal;color:var(--muted);font-size:11px;flex:none}
.badge{font-size:10.5px;padding:3px 8px;border-radius:99px;border:1px solid var(--line);color:var(--muted);flex:none}
.badge.warn{color:#fbbf24;border-color:rgba(251,191,36,.3);background:rgba(251,191,36,.08)}

.empty{padding:36px 10px;text-align:center;color:var(--muted);font-size:13px;border:1px dashed var(--line);border-radius:14px}

/* toast */
#toast{position:fixed;left:50%;bottom:26px;transform:translate(-50%,14px);background:rgba(20,25,38,.96);border:1px solid var(--line-strong);
  padding:10px 16px;border-radius:11px;font-size:13px;opacity:0;pointer-events:none;transition:.22s;z-index:50;max-width:82vw;text-align:center}
#toast.show{opacity:1;transform:translate(-50%,0)}

/* 设置弹层 */
.sheet{position:fixed;inset:0;background:rgba(4,6,12,.62);display:none;place-items:center;padding:20px;z-index:40}
.sheet.open{display:grid}
.sheet .inner{width:100%;max-width:420px;background:#0e1320;border:1px solid var(--line-strong);border-radius:18px;padding:22px;display:flex;flex-direction:column;gap:14px}
.sheet h3{margin:0;font-size:15px}
.sheet .field{display:flex;flex-direction:column;gap:6px}
.sheet .field label{font-size:12px;color:var(--muted)}
.sheet .kv{display:flex;justify-content:space-between;font-size:12.5px;color:var(--muted);padding:7px 0;border-bottom:1px solid var(--line)}
.sheet .kv b{color:var(--txt);font-weight:500}
.sheet .rowbtns{display:flex;gap:9px}
.sheet .rowbtns .btn{flex:1}
.sheet .tip{font-size:11.5px;color:var(--muted);line-height:1.7}

body.embed .app{max-width:none;padding:14px 14px 30px}
body.embed header.top{padding-bottom:12px}
body.embed .brand small{display:none}
body.embed .storage .bar{width:64px}
body.embed .dropzone{padding:28px 14px}
body.embed .dropzone .cloud{width:38px;height:38px}
body.embed .list{grid-template-columns:1fr}
body.embed .storage span.full{display:none}
@media (max-width:640px){
  .app{padding:14px 13px 40px}
  .storage .bar{width:64px}
  .list{grid-template-columns:1fr}
  .storage span.full{display:none}
}
</style>
</head>
<body>
<div class="app">
  <header class="top">
    <div class="brand">
      <svg viewBox="0 0 64 64" aria-hidden="true"><defs><linearGradient id="bg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#6366f1"/><stop offset="1" stop-color="#22d3ee"/></linearGradient></defs><rect width="64" height="64" rx="17" fill="url(#bg1)"/><path d="M32 14c6 8 12 13 12 21a12 12 0 1 1-24 0c0-8 6-13 12-21z" fill="#fff" opacity=".95"/></svg>
      <span>Drop</span><small>KAZAMATA</small>
    </div>
    <div class="spacer"></div>
    <div class="storage" id="storage">
      <div class="bar"><i id="usedbar"></i></div>
      <span id="usedtxt">—</span>
    </div>
    <button class="iconbtn" id="btnSetting" title="设置">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="3.2"/><path d="M19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a1.9 1.9 0 1 1-2.7 2.7l-.1-.1a1.6 1.6 0 0 0-1.8-.3 1.6 1.6 0 0 0-1 1.5V21a1.9 1.9 0 1 1-3.8 0v-.1a1.6 1.6 0 0 0-1-1.5 1.6 1.6 0 0 0-1.8.3l-.1.1a1.9 1.9 0 1 1-2.7-2.7l.1-.1a1.6 1.6 0 0 0 .3-1.8 1.6 1.6 0 0 0-1.5-1H3a1.9 1.9 0 1 1 0-3.8h.1a1.6 1.6 0 0 0 1.5-1 1.6 1.6 0 0 0-.3-1.8l-.1-.1a1.9 1.9 0 1 1 2.7-2.7l.1.1a1.6 1.6 0 0 0 1.8.3H9a1.6 1.6 0 0 0 1-1.5V3a1.9 1.9 0 1 1 3.8 0v.1a1.6 1.6 0 0 0 1 1.5 1.6 1.6 0 0 0 1.8-.3l.1-.1a1.9 1.9 0 1 1 2.7 2.7l-.1.1a1.6 1.6 0 0 0-.3 1.8V9a1.6 1.6 0 0 0 1.5 1H21a1.9 1.9 0 1 1 0 3.8h-.1a1.6 1.6 0 0 0-1.5 1z"/></svg>
    </button>
  </header>

  <section id="loginView" class="login-wrap" <?php echo $logged ? 'hidden' : ''; ?>>
    <form class="login" id="loginForm">
      <svg class="drop-logo" viewBox="0 0 64 64" aria-hidden="true"><defs><linearGradient id="bg2" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#6366f1"/><stop offset="1" stop-color="#22d3ee"/></linearGradient></defs><rect width="64" height="64" rx="17" fill="url(#bg2)"/><path d="M32 14c6 8 12 13 12 21a12 12 0 1 1-24 0c0-8 6-13 12-21z" fill="#fff" opacity=".95"/></svg>
      <h1>私人内容，未经允许无法访问</h1>
      <p>请输入访问口令</p>
      <input type="password" id="pwd" placeholder="访问口令" autocomplete="current-password" required>
      <button class="btn primary block" style="margin-top:14px" type="submit">进入 Drop</button>
    </form>
  </section>

  <main id="mainView" <?php echo $logged ? '' : 'hidden'; ?>>
    <div class="dropzone" id="dropzone">
      <svg class="cloud" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5"/><path d="M4 15v3.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V15"/></svg>
      <h2>拖入文件，或点击选择</h2>
      <p>支持多选、截图粘贴 · 单次总量不超过 2 GB</p>
      <div class="pill">文件不会公开，链接需口令访问</div>
      <input type="file" id="fileInput" multiple hidden>
    </div>

    <div class="toolrow">
      <select id="expireSel">
        <option value="1">保留 1 天</option>
        <option value="7" selected>保留 7 天</option>
        <option value="30">保留 30 天</option>
        <option value="0">永久保留</option>
      </select>
      <span class="hint" id="hintText">选择有效期后，拖入或粘贴文件即开始上传</span>
    </div>

    <div class="queue" id="queue"></div>

    <div class="textbox">
      <textarea id="textInput" rows="1" placeholder="也可以粘贴文本或网址，一键存到 Drop…"></textarea>
      <button class="btn" id="btnText">发送</button>
    </div>

    <div class="listhead">
      <h3>最近的 Drop</h3><span class="count" id="listCount"></span>
      <div class="spacer"></div>
      <button class="btn ghost" id="btnReload" style="height:32px;padding:0 12px;font-size:12px">刷新</button>
    </div>
    <div class="list" id="list"></div>
  </main>
</div>

<div class="sheet" id="sheet">
  <div class="inner">
    <h3>设置</h3>
    <div class="kv"><span>存储占用</span><b id="setUsed">—</b></div>
    <div class="kv"><span>单次上限</span><b>2 GB</b></div>
    <div class="kv"><span>服务器</span><b>drop.kazamata.uk</b></div>
    <div class="field">
      <label>访问口令</label>
      <input type="text" id="setToken" spellcheck="false">
    </div>
    <div class="tip">带口令的分享链接可直接在手机或其它设备上打开；口令泄露后请及时修改服务器配置。</div>
    <div class="rowbtns">
      <button class="btn" id="btnPurge">清理过期</button>
      <button class="btn" id="btnLogout">退出登录</button>
    </div>
    <button class="btn ghost block" id="btnCloseSheet">关闭</button>
  </div>
</div>

<div id="toast"></div>

<script>
(function(){
  'use strict';
  var $ = function(s, r){ return (r||document).querySelector(s); };
  var API = 'api.php';
  var CHUNK = 8 * 1024 * 1024;
  var MAX_DROP = 2 * 1024 * 1024 * 1024;
  var state = { token: '', items: [], stats: null, uploading: false };

  /* ---------- 工具 ---------- */
  function fmtSize(n){
    if (n === 0) return '0 B';
    if (n < 1024) return n + ' B';
    var u = ['KB','MB','GB','TB'], i = -1, v = n;
    do { v /= 1024; i++; } while (v >= 1024 && i < u.length - 1);
    return (v >= 100 ? v.toFixed(0) : v.toFixed(1)) + ' ' + u[i];
  }
  function fmtAgo(ts){
    var d = Math.floor(Date.now()/1000) - ts;
    if (d < 60) return '刚刚';
    if (d < 3600) return Math.floor(d/60) + ' 分钟前';
    if (d < 86400) return Math.floor(d/3600) + ' 小时前';
    if (d < 86400*7) return Math.floor(d/86400) + ' 天前';
    var dt = new Date(ts*1000);
    return (dt.getMonth()+1) + '月' + dt.getDate() + '日';
  }
  function leftText(expireAt){
    if (!expireAt) return '永久';
    var s = expireAt - Math.floor(Date.now()/1000);
    if (s <= 0) return '已过期';
    if (s < 3600) return Math.ceil(s/60) + ' 分钟后过期';
    if (s < 86400) return Math.ceil(s/3600) + ' 小时后过期';
    return Math.ceil(s/86400) + ' 天后过期';
  }
  function extOf(name){
    var m = /\.([a-z0-9]{1,5})$/i.exec(name || '');
    return m ? m[1].toUpperCase() : 'FILE';
  }
  var toastTimer;
  function toast(msg){
    var t = $('#toast');
    t.textContent = msg;
    t.classList.add('show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(function(){ t.classList.remove('show'); }, 2400);
  }
  function show(view){
    var login = view === 'login';
    $('#loginView').hidden = !login;
    $('#mainView').hidden = login;
  }

  /* ---------- API ---------- */
  function post(action, data){
    var fd = new FormData();
    fd.append('action', action);
    if (data) for (var k in data) fd.append(k, data[k]);
    var headers = {};
    if (state.token) headers['X-Drop-Token'] = state.token;
    return fetch(API, { method:'POST', body:fd, headers:headers, credentials:'same-origin' })
      .then(function(r){
        return r.json().catch(function(){ throw new Error('服务器返回异常（' + r.status + '）'); })
          .then(function(j){
            if (!r.ok || j.ok === false) {
              var e = new Error(j.error || ('请求失败（' + r.status + '）'));
              e.status = r.status; e.payload = j; throw e;
            }
            return j;
          });
      });
  }
  function get(action, params){
    var q = new URLSearchParams(Object.assign({action:action}, params||{}));
    var headers = {};
    if (state.token) headers['X-Drop-Token'] = state.token;
    return fetch(API + '?' + q.toString(), { headers:headers, credentials:'same-origin' })
      .then(function(r){ return r.json(); });
  }

  /* ---------- 登录 ---------- */
  function doLogin(pwd){
    return post('login', { password: pwd }).then(function(){
      state.token = pwd;
      try { localStorage.setItem('drop_token', pwd); } catch(e){}
      show('main');
      loadList();
    });
  }

  /* ---------- 列表 ---------- */
  function loadList(){
    return get('list').then(function(j){
      if (!j || j.ok !== true) return;
      state.items = j.items || [];
      state.stats = j.stats;
      renderStorage();
      renderList();
    }).catch(function(){});
  }
  function renderStorage(){
    if (!state.stats) return;
    var pct = Math.min(100, state.stats.used / state.stats.quota * 100);
    $('#usedbar').style.width = Math.max(1, pct) + '%';
    var txt = fmtSize(state.stats.used) + ' / ' + fmtSize(state.stats.quota);
    $('#usedtxt').innerHTML = '<span class="full">' + txt + '</span><span class="full">· </span>' + fmtSize(state.stats.used);
    $('#setUsed').textContent = txt;
  }
  function iconCard(item){
    var f = item.files[0];
    var thumb = null;
    if (f && f.thumb) thumb = API + '?action=thumb&id=' + item.id + '&i=0';
    return thumb;
  }
  function renderList(){
    var box = $('#list');
    $('#listCount').textContent = state.items.length ? '（' + state.items.length + '）' : '';
    if (!state.items.length){
      box.innerHTML = '<div class="empty">还没有内容，拖入文件开始吧</div>';
      return;
    }
    var html = '';
    state.items.forEach(function(it){
      var isText = !it.files.length;
      var f = it.files[0];
      var thumb = iconCard(it);
      var title = isText ? '文本片段' : (it.files.length > 1 ? f.name + ' 等 ' + it.files.length + ' 个文件' : f.name);
      var sub = isText ? '文本 · ' + fmtAgo(it.created) : fmtSize(it.size) + ' · ' + fmtAgo(it.created);
      var expTxt = leftText(it.expire_at);
      var expCls = (it.expire_at && it.expire_at - Math.floor(Date.now()/1000) < 86400) ? ' warn' : '';
      html += '<div class="card" data-id="' + it.id + '">';
      if (isText){
        html += '<div class="note">' + esc(it.note) + '</div>';
      } else {
        html += '<div class="thumb">';
        html += thumb
          ? '<img src="' + thumb + '" alt="" loading="lazy">'
          : '<span class="ext">' + extOf(f.name) + '</span>';
        html += '</div>';
        html += '<div class="meta"><b title="' + esc(title) + '">' + esc(title) + '</b><span>' + sub + '</span></div>';
        if (it.files.length > 1){
          html += '<div class="files">';
          it.files.slice(0, 4).forEach(function(ff, i){
            html += '<a href="' + API + '?action=file&id=' + it.id + '&i=' + i + '"><span>' + esc(ff.name) + '</span><em>' + fmtSize(ff.size) + '</em></a>';
          });
          if (it.files.length > 4) html += '<a><span>…还有 ' + (it.files.length - 4) + ' 个</span></a>';
          html += '</div>';
        }
      }
      html += '<div class="acts">';
      html += '<span class="badge' + expCls + '">' + expTxt + '</span>';
      html += '<div class="spacer" style="flex:1"></div>';
      if (isText){
        html += '<button class="btn" data-act="copytext">复制</button>';
      } else {
        html += '<a class="btn" href="' + API + '?action=file&id=' + it.id + '&i=0">下载</a>';
        if (it.files.length === 1 && (f.type||'').indexOf('image/') === 0){
          html += '<a class="btn" href="' + API + '?action=file&id=' + it.id + '&i=0&inline=1" target="_blank" rel="noopener">查看</a>';
        }
      }
      html += '<button class="btn" data-act="link">链接</button>';
      html += '<button class="btn danger" data-act="del" title="删除">删除</button>';
      html += '</div></div>';
    });
    box.innerHTML = html;
    Array.prototype.forEach.call(box.querySelectorAll('.card'), function(card){
      var id = card.getAttribute('data-id');
      card.addEventListener('click', function(ev){
        var btn = ev.target.closest('[data-act]');
        if (!btn) return;
        var act = btn.getAttribute('data-act');
        var it = state.items.filter(function(x){ return x.id === id; })[0];
        if (!it) return;
        if (act === 'del') delItem(it);
        else if (act === 'link') copyLink(it);
        else if (act === 'copytext') { copy(it.note); toast('已复制文本'); }
      });
    });
  }
  function esc(s){
    return String(s == null ? '' : s).replace(/[&<>"']/g, function(c){
      return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
    });
  }
  function delItem(it){
    if (!confirm('确定删除这个 Drop？删除后无法恢复。')) return;
    post('delete', { id: it.id }).then(function(){
      state.items = state.items.filter(function(x){ return x.id !== it.id; });
      renderList(); toast('已删除');
    }).catch(function(e){ toast(e.message); });
  }
  function copy(text){
    if (navigator.clipboard && navigator.clipboard.writeText){
      return navigator.clipboard.writeText(text);
    }
    var ta = document.createElement('textarea');
    ta.value = text; document.body.appendChild(ta); ta.select();
    document.execCommand('copy'); document.body.removeChild(ta);
    return Promise.resolve();
  }
  function copyLink(it){
    var base = location.origin + location.pathname;
    var link = base + '#k=' + encodeURIComponent(state.token || '') + '&id=' + it.id;
    copy(link).then(function(){ toast('链接已复制，可在其它设备打开'); });
  }

  /* ---------- 上传 ---------- */
  function pickFiles(files){
    var list = Array.prototype.slice.call(files || []);
    if (!list.length) return;
    if (state.uploading) { toast('请等待当前上传完成'); return; }
    var total = list.reduce(function(s, f){ return s + f.size; }, 0);
    if (total > MAX_DROP) { toast('单次 Drop 不能超过 2 GB（当前 ' + fmtSize(total) + '）'); return; }
    if (state.stats && state.stats.used + total > state.stats.quota) { toast('存储空间不足'); return; }
    uploadFiles(list);
  }

  function uploadFiles(files){
    state.uploading = true;
    var expire = parseInt($('#expireSel').value, 10);
    var meta = files.map(function(f){ return { name: f.name, size: f.size, type: f.type || '' }; });
    var queue = $('#queue');
    var rows = [];
    queue.innerHTML = '';
    files.forEach(function(f){
      var row = document.createElement('div');
      row.className = 'qitem';
      row.innerHTML = '<div class="qname"><b>' + esc(f.name) + '</b><span>' + fmtSize(f.size) + '</span><div class="qbar"><i></i></div></div><div class="qpct">0%</div>';
      queue.appendChild(row);
      rows.push(row);
    });

    post('init', { files: JSON.stringify(meta), expire_days: expire }).then(function(res){
      var id = res.id;
      var chain = Promise.resolve();
      files.forEach(function(f, i){
        chain = chain.then(function(){
          return uploadOne(id, i, f, function(pct){
            rows[i].querySelector('.qbar i').style.width = pct + '%';
            rows[i].querySelector('.qpct').textContent = Math.floor(pct) + '%';
          });
        });
      });
      return chain.then(function(){ return post('finish', { id: id }); }).then(function(){
        queue.innerHTML = '';
        toast('已保存到 Drop');
        state.uploading = false;
        return loadList();
      });
    }).catch(function(e){
      state.uploading = false;
      toast(e.message || '上传失败');
      setTimeout(function(){
        Array.prototype.forEach.call(queue.querySelectorAll('.qpct'), function(el){ el.textContent = '失败'; });
        setTimeout(function(){ queue.innerHTML = ''; }, 1800);
      }, 200);
    });
  }

  function uploadOne(id, i, file, onProgress){
    var off = 0, c = 0;
    function send(blob){
      var tries = 0;
      function attempt(){
        var fd = new FormData();
        fd.append('action', 'chunk');
        fd.append('id', id);
        fd.append('i', i);
        fd.append('c', c);
        fd.append('chunk', blob, 'chunk');
        var headers = {};
        if (state.token) headers['X-Drop-Token'] = state.token;
        return fetch(API, { method:'POST', body:fd, headers:headers, credentials:'same-origin' })
          .then(function(r){
            return r.json().catch(function(){ throw new Error('网络异常（' + r.status + '）'); }).then(function(j){
              if (r.status === 409 && j && j.expect !== undefined){
                off = j.received; c = j.expect;
                return 'resync';
              }
              if (!r.ok || j.ok === false) throw new Error(j.error || '分片上传失败');
              off += blob.size; c += 1;
              onProgress(off / file.size * 100);
              return 'ok';
            });
          })
          .catch(function(err){
            tries += 1;
            if (tries >= 4) throw new Error(err.message || '上传中断，请重试');
            return sleep(800 * tries).then(attempt);
          });
      }
      return attempt();
    }
    return get('progress', { id: id }).then(function(j){
      if (j && j.ok && j.files && j.files[i]) { off = j.files[i].received; c = j.files[i].chunks; }
      if (off > 0) onProgress(off / file.size * 100);
      function next(){
        if (off >= file.size) return Promise.resolve();
        var blob = file.slice(off, Math.min(off + CHUNK, file.size));
        return send(blob).then(next);
      }
      return next();
    });
  }
  function sleep(ms){ return new Promise(function(r){ setTimeout(r, ms); }); }

  /* ---------- 文本 ---------- */
  function sendText(){
    var ta = $('#textInput');
    var v = ta.value.trim();
    if (!v) { toast('请输入内容'); return; }
    var expire = parseInt($('#expireSel').value, 10);
    post('text', { text: v, expire_days: expire }).then(function(){
      ta.value = ''; ta.style.height = 'auto';
      toast('已发送');
      loadList();
    }).catch(function(e){ toast(e.message); });
  }

  /* ---------- 事件绑定 ---------- */
  var dz = $('#dropzone'), fi = $('#fileInput');
  dz.addEventListener('click', function(){ fi.click(); });
  fi.addEventListener('change', function(){ pickFiles(fi.files); fi.value = ''; });
  ['dragenter','dragover'].forEach(function(ev){
    dz.addEventListener(ev, function(e){ e.preventDefault(); dz.classList.add('over'); });
    document.addEventListener(ev, function(e){ e.preventDefault(); });
  });
  ['dragleave','drop'].forEach(function(ev){
    dz.addEventListener(ev, function(e){ e.preventDefault(); dz.classList.remove('over'); });
  });
  dz.addEventListener('drop', function(e){
    e.preventDefault();
    if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) pickFiles(e.dataTransfer.files);
  });
  document.addEventListener('drop', function(e){ e.preventDefault(); });
  document.addEventListener('paste', function(e){
    if ($('#mainView').hidden) return;
    var cd = e.clipboardData;
    if (!cd) return;
    if (cd.files && cd.files.length){ e.preventDefault(); pickFiles(cd.files); return; }
    var t = cd.getData('text');
    if (t && document.activeElement !== $('#textInput') && document.activeElement !== $('#setToken')){
      e.preventDefault();
      $('#textInput').value = t;
      sendText();
    }
  });

  $('#btnText').addEventListener('click', sendText);
  $('#textInput').addEventListener('input', function(){
    this.style.height = 'auto';
    this.style.height = Math.min(180, this.scrollHeight) + 'px';
  });
  $('#textInput').addEventListener('keydown', function(e){
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') sendText();
  });
  $('#btnReload').addEventListener('click', function(){ loadList().then(function(){ toast('已刷新'); }); });

  $('#loginForm').addEventListener('submit', function(e){
    e.preventDefault();
    var v = $('#pwd').value;
    if (!v) return;
    var btn = this.querySelector('button');
    btn.disabled = true;
    doLogin(v).catch(function(err){
      toast(err.message || '口令不正确');
    }).then(function(){ btn.disabled = false; });
  });

  $('#btnSetting').addEventListener('click', function(){
    $('#setToken').value = state.token || localStorage.getItem('drop_token') || '';
    $('#sheet').classList.add('open');
  });
  $('#btnCloseSheet').addEventListener('click', function(){ $('#sheet').classList.remove('open'); });
  $('#sheet').addEventListener('click', function(e){ if (e.target === this) this.classList.remove('open'); });
  $('#btnLogout').addEventListener('click', function(){
    post('logout', {}).catch(function(){}).then(function(){
      try { localStorage.removeItem('drop_token'); } catch(e){}
      state.token = ''; location.reload();
    });
  });
  $('#btnPurge').addEventListener('click', function(){
    post('purge', {}).then(function(j){ toast('已清理 ' + (j.removed || 0) + ' 项'); loadList(); })
      .catch(function(e){ toast(e.message); });
  });

  /* ---------- 启动 ---------- */
  var embed = /[?&]embed=1\b/.test(location.search) || window.innerWidth < 520;
  if (embed) document.body.classList.add('embed');

  var hash = new URLSearchParams(location.hash.replace(/^#/, ''));
  var hk = hash.get('k');
  var wantId = hash.get('id');

  function boot(){
    if (hk) {
      state.token = hk;
      doLogin(hk).then(function(){
        if (location.hash) history.replaceState(null, '', location.pathname + location.search);
        if (wantId) setTimeout(function(){
          var card = document.querySelector('.card[data-id="' + wantId + '"]');
          if (card) { card.scrollIntoView({ block:'center' }); card.style.borderColor = 'rgba(99,102,241,.8)'; }
        }, 350);
      }).catch(function(){
        state.token = '';
        show('login');
      });
      return;
    }
    try { state.token = localStorage.getItem('drop_token') || ''; } catch(e){}
    get('me').then(function(j){
      if (j && j.logged_in){ show('main'); loadList(); }
      else show('login');
    }).catch(function(){ show(<?php echo $logged ? '"main"' : '"login"'; ?>); if (<?php echo $logged ? 'true' : 'false'; ?>) loadList(); });
  }
  boot();
})();
</script>
</body>
</html>
