// web/screens/upload.jsx — Веб-загрузка фото пользователем (И4, §3.4).
// multipart POST /v1/upload → создаёт серию (владелец = текущий юзер).

function UploadScreen({ setRoute, me }) {
  const [files, setFiles] = React.useState([]);
  const [contentType, setContentType] = React.useState("photo");
  const [editorial, setEditorial] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [, toast] = useToasts();
  const inputRef = React.useRef(null);

  const quota = me && me.quota;
  const remaining = quota && quota.fileLimit >= 0 ? Math.max(0, quota.fileLimit - quota.filesUsed) : null;

  const addFiles = (list) => {
    const arr = Array.from(list).filter((f) => /\.(jpe?g|png)$/i.test(f.name));
    setFiles((prev) => [...prev, ...arr]);
  };
  const onDrop = (e) => { e.preventDefault(); addFiles(e.dataTransfer.files); };
  const removeAt = (i) => setFiles((p) => p.filter((_, j) => j !== i));

  const submit = async () => {
    if (!files.length) return;
    setBusy(true); setResult(null);
    try {
      const r = await api.upload(files, { contentType, isEditorial: editorial });
      setResult(r);
      if (r.shootId) {
        toast("Создана серия · " + r.accepted + " фото", "ok");
        setTimeout(() => setRoute("series", r.shootId), 800);
      } else {
        toast("Ничего не загружено", "error");
      }
    } catch (e) { toast("Ошибка: " + e.message, "error"); }
    finally { setBusy(false); }
  };

  return (
    <div className="page" style={{ padding: 22, maxWidth: 720 }}>
      <h1 style={{ fontSize: 20, margin: "0 0 4px" }}>Загрузить фото</h1>
      {remaining != null && (
        <div className="muted" style={{ fontSize: 12.5, marginBottom: 14 }}>Осталось по лимиту: {remaining} файлов</div>
      )}

      <div onDrop={onDrop} onDragOver={(e) => e.preventDefault()}
        onClick={() => inputRef.current && inputRef.current.click()}
        style={{ border: "2px dashed var(--line-2,#d7dad3)", borderRadius: 12, padding: 32, textAlign: "center", cursor: "pointer", background: "var(--surface,#fafafa)" }}>
        <div style={{ fontSize: 14 }}>⬆ Перетащите файлы сюда или нажмите, чтобы выбрать</div>
        <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>JPEG / PNG</div>
        <input ref={inputRef} type="file" multiple accept="image/*" style={{ display: "none" }}
          onChange={(e) => addFiles(e.target.files)} />
      </div>

      <div style={{ display: "flex", gap: 16, alignItems: "center", margin: "14px 0" }}>
        <label style={{ fontSize: 13 }}><input type="radio" checked={contentType === "photo"} onChange={() => setContentType("photo")} /> Фото</label>
        <label style={{ fontSize: 13 }}><input type="radio" checked={contentType === "video"} onChange={() => setContentType("video")} /> Видео</label>
        <label style={{ fontSize: 13 }}><input type="radio" checked={contentType === "vector"} onChange={() => setContentType("vector")} /> Vector</label>
        <label style={{ marginLeft: "auto", fontSize: 13 }}><input type="checkbox" checked={editorial} onChange={(e) => setEditorial(e.target.checked)} /> editorial</label>
      </div>

      {files.length > 0 && (
        <div style={{ border: "1px solid var(--line,#e4e6e1)", borderRadius: 10, overflow: "hidden", marginBottom: 14 }}>
          {files.map((f, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", padding: "7px 12px", borderTop: i ? "1px solid var(--line,#eee)" : "none", fontSize: 12.5 }}>
              <span style={{ flex: 1 }}>{f.name}</span>
              <span className="muted" style={{ fontSize: 11, marginRight: 10 }}>{Math.round(f.size / 1024)} КБ</span>
              <button onClick={(e) => { e.stopPropagation(); removeAt(i); }} style={{ border: "none", background: "none", cursor: "pointer", color: "var(--ink-3,#888)" }}>✕</button>
            </div>
          ))}
        </div>
      )}

      {result && result.rejected && result.rejected.length > 0 && (
        <div style={{ color: "var(--warn,#b8860b)", fontSize: 12.5, marginBottom: 10 }}>
          Не загружено: {result.rejected.join(", ")}
        </div>
      )}

      <button onClick={submit} disabled={busy || !files.length}
        style={{ padding: "10px 18px", fontSize: 14, fontWeight: 600, border: "none", borderRadius: 8, background: "var(--accent,#3f6f52)", color: "#fff", cursor: files.length ? "pointer" : "default", opacity: files.length && !busy ? 1 : 0.5 }}>
        {busy ? "Загружаем…" : "Создать серию" + (files.length ? " (" + files.length + ")" : "")}
      </button>
    </div>
  );
}

window.UploadScreen = UploadScreen;
