/* Projects browser. Stage 00 — appears before Concept in the filmstrip.
   Lists all projects, lets you create / select / delete. */

const ScreenProjects = function ScreenProjects(props) {
  const onSelectProject = props.onSelectProject;
  const onNewProject = props.onNewProject;
  const currentProjectId = props.currentProjectId;

  const [projects, setProjects] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [refreshNonce, setRefreshNonce] = React.useState(0);

  const [apiReachable, setApiReachable] = React.useState(Boolean(window.CinematonAPI && window.CinematonAPI.live));

  React.useEffect(function () {
    const onLive = function () { setApiReachable(true); };
    window.addEventListener("cinematon:live", onLive);
    return function () { window.removeEventListener("cinematon:live", onLive); };
  }, []);

  React.useEffect(function () {
    if (!apiReachable) { setLoading(false); return; }
    let cancelled = false;
    setLoading(true);
    window.CinematonAPI.listProjects()
      .then(function (list) {
        if (cancelled) return;
        setProjects(Array.isArray(list) ? list : []);
        setLoading(false);
      })
      .catch(function (err) {
        if (cancelled) return;
        setError(err);
        setLoading(false);
      });
    return function () { cancelled = true; };
  }, [apiReachable, refreshNonce]);

  React.useEffect(function () {
    const onRefresh = function () { setRefreshNonce(function (n) { return n + 1; }); };
    window.addEventListener("cinematon:refresh-run", onRefresh);
    return function () { window.removeEventListener("cinematon:refresh-run", onRefresh); };
  }, []);

  const handleDelete = function (id, title) {
    if (!confirm("Delete project \"" + title + "\"? This cannot be undone.")) return;
    window.CinematonAPI.deleteProject(id)
      .then(function () { setRefreshNonce(function (n) { return n + 1; }); })
      .catch(function (err) { alert("Delete failed: " + err.message); });
  };

  const formatDate = function (iso) {
    if (!iso) return "";
    try {
      const d = new Date(iso);
      const month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][d.getMonth()];
      return month + " " + d.getDate() + ", " + d.getFullYear();
    } catch (e) { return iso; }
  };

  return (
    <div className="page" style={{ display: "grid", gridTemplateRows: "auto 1fr", height: "100%" }}>
      <PageHeader title="Projects" sub={apiReachable ? "Stage 00 / 09 - your project library" : "Stage 00 / 09 - API unreachable - showing prototype only"}>
        {apiReachable && (
          <span className="tag accent">{projects.length} {projects.length === 1 ? "project" : "projects"}</span>
        )}
        <button className="btn primary" onClick={onNewProject}>+ New Project</button>
      </PageHeader>

      <div className="scroll" style={{ padding: 28 }}>
        {!apiReachable && (
          <div className="card" style={{ padding: 28, maxWidth: 720, margin: "0 auto", textAlign: "center" }}>
            <div className="card-title" style={{ marginBottom: 12 }}>API unreachable</div>
            <p style={{ color: "var(--fg-muted)", lineHeight: 1.6, margin: 0 }}>
              The Cinematon server is not responding. The design prototype is still browsable
              with the sample <em>Room 4B</em> project, but you cannot create or load real projects until the
              server is reachable.
            </p>
          </div>
        )}

        {apiReachable && loading && (
          <div className="card" style={{ padding: 28, maxWidth: 720, margin: "0 auto", textAlign: "center", color: "var(--fg-muted)" }}>
            Loading your projects...
          </div>
        )}

        {apiReachable && error && (
          <div className="card" style={{ padding: 20, maxWidth: 720, margin: "0 auto", borderColor: "var(--bad)", color: "var(--bad)" }}>
            <strong>Error loading projects:</strong> {error.message || String(error)}
          </div>
        )}

        {apiReachable && !loading && !error && projects.length === 0 && (
          <div className="card" style={{
            padding: 56, maxWidth: 720, margin: "0 auto",
            textAlign: "center", border: "1px dashed var(--line)",
          }}>
            <div className="serif" style={{ fontSize: 24, marginBottom: 10 }}>No projects yet</div>
            <p style={{ color: "var(--fg-muted)", maxWidth: 460, margin: "0 auto 20px", lineHeight: 1.6 }}>
              Click <em>+ New Project</em> to create your first horror cinematic short. The agent will
              generate the brief, bible, characters, scenes, screenplay, shots, and prompt packets from
              your one-paragraph concept.
            </p>
            <button className="btn primary" onClick={onNewProject}>+ New Project</button>
          </div>
        )}

        {apiReachable && !loading && !error && projects.length > 0 && (
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))",
            gap: 16,
            maxWidth: 1280,
            margin: "0 auto",
          }}>
            {projects.map(function (p) {
              const isCurrent = p.id === currentProjectId;
              return (
                <div
                  key={p.id}
                  className="card"
                  style={{
                    padding: 18,
                    cursor: "pointer",
                    borderColor: isCurrent ? "var(--accent)" : undefined,
                    boxShadow: isCurrent ? "0 0 0 1px var(--accent-dim)" : undefined,
                    position: "relative",
                  }}
                  onClick={function () { if (onSelectProject) onSelectProject(p.id); }}
                >
                  <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <h3 className="serif" style={{ margin: 0, fontSize: 20, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {p.title || "Untitled"}
                      </h3>
                      <div className="mono dim" style={{ fontSize: 10, marginTop: 4, overflow: "hidden", textOverflow: "ellipsis" }}>
                        {p.id}
                      </div>
                    </div>
                    {isCurrent && <span className="tag accent" style={{ flex: "0 0 auto" }}>current</span>}
                  </div>

                  <div style={{ borderTop: "1px dashed var(--line-soft)", paddingTop: 12, marginTop: 4 }}>
                    <div className="row" style={{ justifyContent: "space-between", fontSize: 11.5, color: "var(--fg-muted)" }}>
                      <span><span className="dim">Genre:</span> {p.genre_plugin_id || "horror.v1"}</span>
                      <span><span className="dim">Runtime:</span> {p.target_runtime_seconds || 180}s</span>
                    </div>
                    <div className="row" style={{ justifyContent: "space-between", fontSize: 11.5, color: "var(--fg-muted)", marginTop: 6 }}>
                      <span><span className="dim">Created:</span> {formatDate(p.created_at)}</span>
                    </div>
                  </div>

                  <div className="row" style={{ marginTop: 16, gap: 8, justifyContent: "space-between" }}>
                    <button
                      className="btn ghost"
                      style={{ fontSize: 11, padding: "4px 10px", color: "var(--bad)", borderColor: "oklch(0.4 0.1 25)" }}
                      onClick={function (e) { e.stopPropagation(); handleDelete(p.id, p.title); }}
                    >
                      Delete
                    </button>
                    <button
                      className="btn primary"
                      style={{ fontSize: 11, padding: "4px 12px" }}
                      onClick={function (e) { e.stopPropagation(); if (onSelectProject) onSelectProject(p.id); }}
                    >
                      {isCurrent ? "Continue" : "Open"} ->
                    </button>
                  </div>
                </div>
              );
            })}

            {/* + New Project tile */}
            <button
              className="card"
              onClick={onNewProject}
              style={{
                padding: 18, minHeight: 180,
                display: "flex", flexDirection: "column",
                alignItems: "center", justifyContent: "center",
                border: "1px dashed var(--line)", background: "transparent",
                color: "var(--fg-muted)", cursor: "pointer",
              }}
            >
              <span style={{ fontSize: 36, lineHeight: 1, marginBottom: 8 }}>+</span>
              <span className="serif" style={{ fontSize: 16 }}>New Project</span>
              <span className="mono dim" style={{ fontSize: 10, marginTop: 4 }}>concept &rarr; render</span>
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

window.ScreenProjects = ScreenProjects;
