/* ============================================
   INGESTION DASHBOARD — Upload + live polling
   ============================================ */
function IngestionScreen({ onNavigate }) {
  const [drag, setDrag] = useState(false);
  const [tasks, setTasks] = useState([]);             // [{task_id, filename, status, processed_pages, total_pages, ...}]
  const [activeTaskId, setActiveTaskId] = useState(localStorage.getItem(window.API.TASK_KEY));
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState(null);
  const fileInputRef = useRef(null);

  // Resume polling on mount if there's a task_id in localStorage.
  useEffect(() => {
    if (!activeTaskId) return;
    let stop = false;
    const tick = async () => {
      try {
        const data = await window.API.status(activeTaskId);
        if (stop) return;
        setTasks((prev) => {
          const i = prev.findIndex((t) => t.task_id === activeTaskId);
          if (i === -1) return [data, ...prev];
          const next = [...prev];
          next[i] = data;
          return next;
        });
        if (data.status === "COMPLETED" || data.status === "FAILED") {
          localStorage.removeItem(window.API.TASK_KEY);
          setActiveTaskId(null);
        } else {
          setTimeout(tick, 3000);
        }
      } catch (err) {
        // 404 or 401 — give up on this task
        if (err.status === 404 || err.status === 401) {
          localStorage.removeItem(window.API.TASK_KEY);
          setActiveTaskId(null);
        } else if (!stop) {
          setTimeout(tick, 5000);
        }
      }
    };
    tick();
    return () => { stop = true; };
  }, [activeTaskId]);

  const onPick = async (file) => {
    if (!file) return;
    if (!file.name.toLowerCase().endsWith(".pdf")) {
      setError("Only PDF files are accepted.");
      return;
    }
    setError(null);
    setUploading(true);
    try {
      const res = await window.API.upload(file);
      localStorage.setItem(window.API.TASK_KEY, res.task_id);
      setTasks((prev) => [
        { task_id: res.task_id, filename: res.filename, status: "QUEUED", processed_pages: 0, total_pages: null },
        ...prev,
      ]);
      setActiveTaskId(res.task_id);
    } catch (err) {
      setError(err.message || "Upload failed.");
    } finally {
      setUploading(false);
    }
  };

  const onDropFile = (e) => {
    e.preventDefault();
    setDrag(false);
    onPick(e.dataTransfer.files?.[0]);
  };

  const stats = {
    queued: tasks.filter((t) => t.status === "QUEUED").length,
    processing: tasks.filter((t) => t.status === "PROCESSING").length,
    failed: tasks.filter((t) => t.status === "FAILED").length,
    completed: tasks.filter((t) => t.status === "COMPLETED").length,
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Ingestion Dashboard</h1>
          <p className="page-subtitle">Upload a PDF — progress polled every 3 seconds.</p>
        </div>
        <div className="row">
          <button className="btn btn--ghost" onClick={() => activeTaskId && setActiveTaskId(activeTaskId)} title="Polling refresh">
            <Icons.Refresh size={14} /> Refresh
          </button>
        </div>
      </div>

      {/* Status strip — counts from this session only (no /api/tasks list yet) */}
      <div className="grid-4" style={{ marginBottom: 16 }}>
        <StatCard label="Queued" value={String(stats.queued)} sub="Awaiting worker" icon={<Icons.History />} />
        <StatCard label="Processing" value={String(stats.processing)} sub="Embedding" icon={<Icons.Activity />} accent="var(--navy-700)" />
        <StatCard label="Failed" value={String(stats.failed)} sub="Check error" icon={<Icons.AlertCircle />} accent="var(--status-danger)" />
        <StatCard label="Completed" value={String(stats.completed)} sub="This session" icon={<Icons.Check />} accent="var(--status-ok)" />
      </div>

      {/* Upload zone */}
      <input
        ref={fileInputRef}
        type="file"
        accept="application/pdf,.pdf"
        style={{ display: "none" }}
        onChange={(e) => { onPick(e.target.files?.[0]); e.target.value = ""; }}
      />
      <div
        onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={onDropFile}
        onClick={() => !uploading && fileInputRef.current?.click()}
        style={{
          border: `2px dashed ${drag ? "var(--orange-600)" : "var(--orange-500)"}`,
          background: drag ? "var(--orange-100)" : "var(--orange-50)",
          borderRadius: 8,
          padding: "32px 24px",
          textAlign: "center",
          marginBottom: 20,
          transition: "all 0.15s",
          cursor: uploading ? "wait" : "pointer",
          opacity: uploading ? 0.7 : 1,
        }}
      >
        <div style={{
          width: 56, height: 56, margin: "0 auto 12px",
          borderRadius: "50%",
          background: "white",
          display: "grid", placeItems: "center",
          color: "var(--orange-600)",
          boxShadow: "var(--shadow-sm)",
        }}>
          <Icons.Upload size={24} />
        </div>
        <h3 style={{ margin: "0 0 4px", fontSize: 16, fontWeight: 600, color: "var(--orange-700)" }}>
          {uploading ? "Uploading…" : "Drop a PDF here to ingest"}
        </h3>
        <p style={{ margin: "0 0 14px", color: "var(--ink-600)", fontSize: 13 }}>
          PDF only · max 500 MB · machine-readable (no OCR in v1)
        </p>
        <div className="row" style={{ justifyContent: "center", gap: 8 }}>
          <button className="btn btn--primary" disabled={uploading} onClick={(e) => { e.stopPropagation(); fileInputRef.current?.click(); }}>
            <Icons.Plus size={14} /> Choose File
          </button>
        </div>
        {error && (
          <div style={{
            marginTop: 14, padding: "8px 12px",
            background: "rgba(220, 38, 38, 0.08)",
            border: "1px solid rgba(220, 38, 38, 0.35)",
            borderRadius: 6, color: "#991b1b",
            fontSize: 12, display: "inline-block",
          }}>
            {error}
          </div>
        )}
      </div>

      {/* Processing queue table */}
      <Card title="Active Processing Queue" subtitle={tasks.length === 0 ? "No uploads in this session yet." : `${tasks.length} task(s) in this session`} bodyFlush>
        {tasks.length > 0 && (
          <table className="table">
            <thead>
              <tr>
                <th>Document</th>
                <th style={{ width: 130 }}>Status</th>
                <th style={{ width: 280 }}>Progress</th>
                <th style={{ width: 110 }}>Pages</th>
              </tr>
            </thead>
            <tbody>
              {tasks.map((r) => {
                const pct = r.total_pages && r.total_pages > 0
                  ? Math.min(100, Math.round((r.processed_pages / r.total_pages) * 100))
                  : (r.status === "COMPLETED" ? 100 : 0);
                const kind =
                  r.status === "COMPLETED" ? "complete" :
                  r.status === "FAILED" ? "failed" :
                  r.status === "PROCESSING" ? "processing" :
                  "pending";
                return (
                  <tr key={r.task_id}>
                    <td>
                      <div className="row gap-8">
                        <div style={{
                          width: 32, height: 32, borderRadius: 5,
                          background: r.status === "FAILED" ? "var(--status-failed-bg)" : r.status === "COMPLETED" ? "var(--status-complete-bg)" : "var(--navy-50)",
                          color: r.status === "FAILED" ? "var(--status-failed-fg)" : r.status === "COMPLETED" ? "var(--status-complete-fg)" : "var(--navy-700)",
                          display: "grid", placeItems: "center", flexShrink: 0,
                        }}><Icons.File size={14} /></div>
                        <div style={{ minWidth: 0 }}>
                          <div className="doc-name" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 360 }}>{r.filename}</div>
                          <div className="mono text-xs muted">{r.task_id.slice(0, 8)}</div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <Badge kind={kind}>
                        {r.status === "COMPLETED" ? "Completed" :
                          r.status === "FAILED" ? "Failed" :
                          r.status === "PROCESSING" ? "Processing" :
                          "Queued"}
                      </Badge>
                    </td>
                    <td>
                      <Progress
                        value={pct}
                        kind={r.status === "COMPLETED" ? "green" : r.status === "FAILED" ? undefined : undefined}
                      />
                      <div className="text-xs" style={{ marginTop: 4, color: r.status === "FAILED" ? "var(--status-failed-fg)" : "var(--ink-500)" }}>
                        {r.status === "FAILED" ? (r.error_message || "Failed") :
                          r.status === "COMPLETED" ? "Indexed" :
                          r.status === "PROCESSING" ? "Embedding chunks…" :
                          "Waiting for worker"}
                      </div>
                    </td>
                    <td className="mono text-xs">
                      {r.processed_pages || 0}{r.total_pages ? ` / ${r.total_pages}` : ""}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </Card>
    </>
  );
}

function StatCard({ label, value, sub, icon, accent }) {
  return (
    <div className="card" style={{ padding: "16px 18px" }}>
      <div className="row" style={{ justifyContent: "space-between", marginBottom: 8 }}>
        <span className="text-xs muted" style={{ textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>{label}</span>
        <span style={{ color: accent || "var(--ink-400)" }}>{icon}</span>
      </div>
      <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", color: accent || "var(--ink-900)", lineHeight: 1.1 }}>{value}</div>
      <div className="text-xs muted" style={{ marginTop: 4 }}>{sub}</div>
    </div>
  );
}

window.IngestionScreen = IngestionScreen;
window.StatCard = StatCard;
