// Data room / files page backed by D1 project_files

function Files({ go, route }) {
  const { snapshot } = window.useGGGSnapshot ? window.useGGGSnapshot() : { snapshot: null };
  const routeProjectId = route?.projectId || "";
  const project = window.GGGApi?.resolveActiveProject?.(snapshot, routeProjectId) || snapshot?.projects?.[0];
  const files = (snapshot?.files || []).filter((file) => !project?.id || file.project_id === project.id);
  const inputRef = React.useRef(null);
  const [error, setError] = React.useState("");
  const [status, setStatus] = React.useState("");
  React.useEffect(() => {
    if (project?.id && !routeProjectId && window.location.pathname === "/document") {
      window.history.replaceState({}, "", `/document/${encodeURIComponent(project.id)}`);
    }
  }, [project?.id, routeProjectId]);
  const upload = async (selectedFiles) => {
    setError("");
    setStatus("");
    if (!project?.id) {
      setError("请先创建项目，再上传资料。");
      return;
    }
    try {
      if (window.GGGApi?.setActiveProjectId) window.GGGApi.setActiveProjectId(project.id);
      const saved = await window.GGGApi.uploadProjectFiles(project.id, selectedFiles);
      setStatus(`已保存 ${saved.length} 个文件`);
    } catch (err) {
      setError(err.message || "上传失败");
    } finally {
      if (inputRef.current) inputRef.current.value = "";
    }
  };
  const remove = async (file) => {
    if (!confirm(`确认删除文件 ${file.file_name}？`)) return;
    setError("");
    setStatus("");
    try {
      await window.GGGApi.deleteProjectFile(file.id);
      setStatus("文件已删除");
    } catch (err) {
      setError(err.message || "删除失败");
    }
  };

  return (
    <AppShell go={go} current="document" pageBreadcrumbs={[
      { label: "项目", go: () => go("project") },
      { label: project?.name || "出海项目", go: () => project?.id ? go("project", project.id) : go("project") },
      { label: "资料解析" },
    ]}>
      <div className="page page-narrow">
        <div className="page-header">
          <div>
            <h1 className="page-title">资料解析</h1>
            <p className="page-sub">{project?.name ? `当前项目：${project.name}` : "请先选择项目"}。产品目录、报价单、认证文件和图片都从当前项目读取。</p>
          </div>
          <button className="btn btn-primary" onClick={() => inputRef.current?.click()}><Icon name="upload" size={14} /> 上传资料</button>
        </div>

        <input ref={inputRef} type="file" multiple accept=".docx,.pdf,.xlsx,.csv,.jpg,.jpeg,.png,.webp,.txt,.md" style={{ display: "none" }} onChange={(event) => upload(event.target.files)} />
        {(status || error) && <div className={error ? "form-alert" : "callout info"} style={{ marginBottom: 16 }}>{error || status}</div>}

        <div className="upload-zone" style={{ marginBottom: 18 }} onClick={() => inputRef.current?.click()} onDragOver={(event) => event.preventDefault()} onDrop={(event) => { event.preventDefault(); upload(event.dataTransfer.files); }}>
          <Icon name="upload" size={28} color="var(--accent)" />
          <h4 style={{ marginTop: 12 }}>拖入文件，或点击浏览</h4>
          <p>支持 .docx · .pdf · .xlsx · .csv · .jpg · .png · .webp · 单文件最大 50MB</p>
        </div>

        <div className="card card-pad">
          <div className="project-list-head" style={{ padding: 0, borderBottom: "none", marginBottom: 14 }}>
            <h3>已上传资料 <span style={{ color: "var(--muted)", fontWeight: 400, fontSize: 13 }}>· {files.length} 个文件</span></h3>
            <button className="btn btn-ghost btn-sm"><Icon name="filter" size={14} /> 筛选</button>
          </div>
          <div className="col-flex">
            {files.map((file) => {
              const meta = parseJson(file.extracted_metadata, {});
              return (
                <div key={file.id} className="file-row">
                  <div className="ico">{meta.ext || fileExt(file.file_name)}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="name">{file.file_name}</div>
                    <div className="meta">{meta.summary || `${Math.round(file.file_size / 1000)} KB · ${file.status}`}</div>
                  </div>
                  <span className={"badge badge-" + (meta.tone || "ocean")}><span className="badge-dot"></span>{meta.statusLabel || file.status}</span>
                  <div className="row-flex" style={{ gap: 4 }}>
                    <button className="btn-link" style={{ fontSize: 12 }} onClick={() => window.GGGApi.downloadProjectFile(file.id)}>下载</button>
                    <button className="btn-link" style={{ fontSize: 12, color: "var(--red)" }} onClick={() => remove(file)}>删除</button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="callout info" style={{ marginTop: 18 }}>
          <div className="callout-title">AI 已提取关键信息</div>
          15 个 SKU · 3 个规格层级 · 平均出厂价 ¥18.50 · 已识别 FDA、SGS 认证 · 缺失：包装尺寸、装柜数。
        </div>
      </div>
    </AppShell>
  );
}

function fileExt(name = "") {
  const ext = name.split(".").pop() || "FILE";
  return ext.slice(0, 3).toUpperCase();
}

window.Files = Files;
