// Atlas · Home
const { useState: useStateHome, useCallback: useCallbackHome } = React;

const PAGE_SIZE = 5;

const TYPE_LABELS = {
  tech:     { label: "Technology Landscape" },
  company:  { label: "Company Landscape" },
  lit:      { label: "Literature Review" },
  position: { label: "Competitive Position" },
};

const STATUS_PILL = {
  complete:      { label: "Complete",       bg: "var(--success-tint)",       color: "var(--success)" },
  "draft-ready": { label: "Draft ready",    bg: "rgba(99,102,241,0.08)",     color: "#6366f1" },
  researching:   { label: "Researching…",   bg: "rgba(251,191,36,0.12)",     color: "#d97706" },
  "in-progress": { label: "In progress",    bg: "var(--warm-tint)",          color: "var(--warm)" },
};

function ReportTypeBadge({ type }) {
  const t = TYPE_LABELS[type] || { label: type || "Report" };
  return (
    <span style={{
      display: "inline-block",
      fontSize: 10.5, fontFamily: "var(--mono)",
      letterSpacing: "0.05em", textTransform: "uppercase",
      color: "var(--ink-4)",
      background: "var(--bg-2)",
      border: "1px solid var(--line)",
      borderRadius: 4,
      padding: "2px 7px",
    }}>{t.label}</span>
  );
}

function StatusPill({ r }) {
  const key = r.hasApproved ? "complete"
    : r.hasDraft ? "draft-ready"
    : r.isResearching ? "researching"
    : "in-progress";
  const s = STATUS_PILL[key];
  return (
    <span style={{
      display: "inline-block", fontSize: 11, fontFamily: "var(--mono)",
      background: s.bg, color: s.color,
      borderRadius: 20, padding: "2px 9px",
      animation: key === "researching" ? "pulse-opacity 1.5s ease-in-out infinite" : undefined,
    }}>{s.label}
      <style>{`@keyframes pulse-opacity { 0%,100% { opacity:1; } 50% { opacity:0.5; } }`}</style>
    </span>
  );
}

function StepHome({ goNew, goView, reports, setReports, user, onUpgrade }) {
  const [query, setQuery] = useStateHome("");
  const [page, setPage] = useStateHome(0);
  const [deletingId, setDeletingId] = useStateHome(null);
  const [refreshingId, setRefreshingId] = useStateHome(null);
  const [refreshError, setRefreshError] = useStateHome(null);

  const firstName = user ? user.name.split(" ")[0] : "there";
  const isUnlimited = user?.email?.endsWith("@notedsource.com") || ["ramyayoub13@gmail.com", "michael.reksulak.work@gmail.com"].includes(user?.email);
  const atLimit = !isUnlimited && (user?.profile?.reports_started || 0) >= 2;

  // Sort newest first by id (which starts with YYYY-MM-DD)
  const sorted = [...(reports || [])].sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));

  const filtered = sorted.filter((r) => {
    if (!query.trim()) return true;
    const q = query.toLowerCase();
    return (r.title || r.id || "").toLowerCase().includes(q);
  });

  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
  const pageReports = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
  const hasReports = reports && reports.length > 0;

  const handleRefresh = async (r) => {
    setRefreshingId(r.id);
    setRefreshError(null);
    try {
      const res = await fetch(`/api/report/${r.id}/refresh`, { method: "POST" });
      if (!res.ok) throw new Error("Refresh failed");
      const data = await res.json();
      const newReport = {
        id: data.newId,
        title: data.title,
        type: r.type,
        created: data.created,
        hasDraft: false,
        hasExport: false,
        refreshedFrom: r.id,
      };
      setReports && setReports((prev) => [newReport, ...(prev || [])]);
      setPage(0);
      goView && goView(newReport);
    } catch (e) {
      setRefreshError(`Could not refresh "${r.title || r.id}"`);
      setTimeout(() => setRefreshError(null), 4000);
    } finally {
      setRefreshingId(null);
    }
  };

  const handleDelete = async (r) => {
    if (!confirm(`Delete "${r.title || r.id}"? This cannot be undone.`)) return;
    setDeletingId(r.id);
    try {
      const res = await fetch(`/api/report/${r.id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Delete failed");
      setReports && setReports((prev) => prev.filter((x) => x.id !== r.id));
      // adjust page if needed
      const newFiltered = (reports || []).filter((x) => x.id !== r.id && (query.trim() ? (x.title || x.id || "").toLowerCase().includes(query.toLowerCase()) : true));
      const newPages = Math.ceil(newFiltered.length / PAGE_SIZE);
      if (page >= newPages && page > 0) setPage(page - 1);
    } catch (e) {
      alert("Could not delete report: " + e.message);
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <div className="canvas-inner">
      <div className="home-page">

        {/* Hero */}
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "flex-start",
          paddingBottom: 32, marginBottom: 32, borderBottom: "1px solid var(--line)",
        }}>
          <div>
            <h2 style={{ fontFamily: "var(--serif)", fontSize: 26, fontWeight: 500, margin: "0 0 6px", letterSpacing: "-0.015em" }}>
              Welcome back, {firstName}.
            </h2>
            <p style={{ margin: 0, fontSize: 14, color: "var(--ink-3)", lineHeight: 1.5 }}>
              {hasReports
                ? `You have ${reports.length} report${reports.length > 1 ? "s" : ""}.`
                : "Ready when you are. Start your first report below."}
            </p>
          </div>
          {atLimit ? (
            <button className="btn accent lg" onClick={onUpgrade} style={{ flexShrink: 0, marginTop: 4 }}>
              Get full access →
            </button>
          ) : (
            <button className="btn primary lg" onClick={goNew} style={{ flexShrink: 0, marginTop: 4 }}>
              <Icon name="plus" size={14} /> New report
            </button>
          )}
        </div>

        {/* Empty state */}
        {!hasReports && (
          <div style={{
            display: "flex", flexDirection: "column", alignItems: "center",
            padding: "64px 32px", textAlign: "center",
            border: "1px dashed var(--line-2)", borderRadius: "var(--radius-lg)",
          }}>
            <div style={{
              width: 48, height: 48, borderRadius: "50%",
              background: "var(--bg-2)", border: "1px solid var(--line)",
              display: "flex", alignItems: "center", justifyContent: "center",
              marginBottom: 20,
            }}>
              <Icon name="bookOpen" size={20} style={{ color: "var(--ink-3)" }} />
            </div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 18, color: "var(--ink-2)", marginBottom: 8, fontWeight: 500 }}>
              No reports yet
            </div>
            <div style={{ fontSize: 13, color: "var(--ink-4)", lineHeight: 1.65, maxWidth: 340, marginBottom: 6 }}>
              Landscapes, literature reviews, and reports you generate with Atlas will appear here.
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-4)", marginBottom: 24 }}>
              Your first report is included at no charge.
            </div>
            {atLimit ? (
              <button className="btn accent" onClick={onUpgrade}>
                Get full access →
              </button>
            ) : (
              <button className="btn primary" onClick={goNew}>
                <Icon name="plus" size={13} /> New report
              </button>
            )}
          </div>
        )}

        {/* Search + list */}
        {hasReports && (
          <>
            {/* Search bar */}
            <div style={{ marginBottom: 12, position: "relative", maxWidth: 260 }}>
              <span style={{
                position: "absolute", left: 8, top: "50%", transform: "translateY(-50%)",
                color: "var(--ink-4)", pointerEvents: "none", display: "flex",
              }}>
                <Icon name="search" size={12} />
              </span>
              <input
                type="text"
                value={query}
                onChange={(e) => { setQuery(e.target.value); setPage(0); }}
                placeholder="Search reports…"
                style={{
                  width: "100%", boxSizing: "border-box",
                  padding: "5px 24px 5px 26px",
                  fontSize: 12, fontFamily: "var(--sans)",
                  border: "1px solid var(--line-2)", borderRadius: "var(--radius)",
                  background: "var(--bg)", color: "var(--ink)",
                  outline: "none",
                }}
              />
              {query && (
                <button
                  onClick={() => { setQuery(""); setPage(0); }}
                  style={{
                    position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)",
                    background: "none", border: "none", cursor: "pointer", color: "var(--ink-4)",
                    display: "flex", padding: 2,
                  }}
                ><Icon name="x" size={11} /></button>
              )}
            </div>

            {/* List header */}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
              <div style={{ fontSize: 11, fontFamily: "var(--mono)", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-4)" }}>
                {query ? `${filtered.length} result${filtered.length !== 1 ? "s" : ""}` : `Reports · ${reports.length}`}
              </div>
              {totalPages > 1 && (
                <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 12, color: "var(--ink-3)", fontFamily: "var(--mono)" }}>
                  <button
                    className="btn ghost sm"
                    disabled={page === 0}
                    onClick={() => setPage(page - 1)}
                    style={{ padding: "2px 7px" }}
                  >‹</button>
                  <span>{page + 1} / {totalPages}</span>
                  <button
                    className="btn ghost sm"
                    disabled={page >= totalPages - 1}
                    onClick={() => setPage(page + 1)}
                    style={{ padding: "2px 7px" }}
                  >›</button>
                </div>
              )}
            </div>

            {/* No search results */}
            {filtered.length === 0 && (
              <div style={{ padding: "32px 0", textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>
                No reports match "{query}"
              </div>
            )}

            {/* Report rows */}
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {pageReports.map((r, i) => (
                <div
                  key={r.id}
                  style={{
                    display: "grid",
                    gridTemplateColumns: "1fr 140px 110px 300px",
                    alignItems: "center",
                    gap: 16,
                    padding: "14px 16px",
                    background: i % 2 === 0 ? "var(--bg)" : "var(--bg-2)",
                    borderRadius: "var(--radius)",
                    border: "1px solid var(--line)",
                  }}
                >
                  {/* Title + type */}
                  <div style={{ minWidth: 0 }}>
                    <div style={{
                      fontFamily: "var(--serif)", fontSize: 14.5, fontWeight: 500,
                      color: "var(--ink)", marginBottom: 4,
                      overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                    }}>
                      {r.title || r.id}
                    </div>
                    <div style={{ display: "flex", gap: 5, alignItems: "center", flexWrap: "wrap" }}>
                      <ReportTypeBadge type={r.type} />
                      {r.refreshedFrom && (
                        <span style={{
                          fontSize: 10, fontFamily: "var(--mono)", letterSpacing: "0.05em",
                          textTransform: "uppercase", color: "var(--ink-4)",
                          background: "rgba(99,102,241,0.08)", color: "#6366f1",
                          border: "1px solid rgba(99,102,241,0.2)",
                          borderRadius: 4, padding: "2px 6px",
                        }}>Refreshed</span>
                      )}
                    </div>
                  </div>

                  {/* Status */}
                  <div>
                    <div style={{ fontSize: 10, fontFamily: "var(--mono)", color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4 }}>Status</div>
                    <StatusPill r={r} />
                  </div>

                  {/* Date */}
                  <div>
                    <div style={{ fontSize: 10, fontFamily: "var(--mono)", color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4 }}>Created</div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-2)" }}>{r.created || r.date || "—"}</div>
                  </div>

                  {/* Actions */}
                  <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
                    {/* Download — available once approved; prefers exported format, falls back to markdown */}
                    {r.hasApproved && (
                      <a
                        className="btn ghost sm"
                        href={`/api/report/${r.id}/download/${r.exportFormats && r.exportFormats.length > 0 ? r.exportFormats[0] : "md"}`}
                        download
                        title="Download report"
                        style={{ textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}
                      >
                        <Icon name="download" size={12} /> Download
                      </a>
                    )}
                    {/* Refresh — only available once approved */}
                    <button
                      className="btn ghost sm"
                      disabled={refreshingId === r.id || !r.hasApproved}
                      onClick={() => handleRefresh(r)}
                      title={r.hasApproved ? "Re-run this report with fresh research" : "Approve the report before refreshing"}
                      style={{ opacity: r.hasApproved ? 1 : 0.35, cursor: r.hasApproved ? "pointer" : "not-allowed" }}
                    >
                      <Icon name="refresh" size={12} style={{ transform: refreshingId === r.id ? "rotate(360deg)" : "none", transition: "transform 0.9s ease-in-out" }} />
                      {refreshingId === r.id ? "…" : "Refresh"}
                    </button>
                    <button className="btn ghost sm" onClick={() => goView && goView(r)}>
                      Open
                    </button>
                    <button
                      className="btn ghost sm"
                      disabled={deletingId === r.id}
                      onClick={() => handleDelete(r)}
                      style={{ color: "var(--rose)", borderColor: "transparent" }}
                    >
                      {deletingId === r.id ? "…" : <Icon name="trash" size={13} />}
                    </button>
                  </div>
                </div>
              ))}
            </div>

            {/* Bottom pagination (only when >1 page) */}
            {totalPages > 1 && (
              <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 8, marginTop: 16 }}>
                <button className="btn ghost sm" disabled={page === 0} onClick={() => setPage(page - 1)}>‹ Prev</button>
                {Array.from({ length: totalPages }, (_, i) => (
                  <button
                    key={i}
                    className={`btn ${i === page ? "primary" : "ghost"} sm`}
                    onClick={() => setPage(i)}
                    style={{ minWidth: 28 }}
                  >{i + 1}</button>
                ))}
                <button className="btn ghost sm" disabled={page >= totalPages - 1} onClick={() => setPage(page + 1)}>Next ›</button>
              </div>
            )}
          </>
        )}
      </div>

      {/* Refresh error toast */}
      {refreshError && (
        <div style={{
          position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)",
          background: "#1D1D1F", color: "#F5F5F7",
          fontSize: 13, padding: "10px 18px", borderRadius: 8,
          boxShadow: "0 4px 16px rgba(0,0,0,0.18)", zIndex: 999,
        }}>{refreshError}</div>
      )}
    </div>
  );
}

window.StepHome = StepHome;
