// Home — your boards list. Fetches the current user's boards from the API
// (boards where you're an admin) so the cards reflect real data, not the
// old seeded sample list.

function HomeScreen({ onCreate, palette }) {
  const [boards, setBoards] = React.useState(null);   // null = loading
  const [loadError, setLoadError] = React.useState(null);
  const isMobile = useIsMobile();

  React.useEffect(() => {
    let cancelled = false;
    API.listMyBoards()
      .then((data) => { if (!cancelled) setBoards(data.boards || []); })
      .catch((err) => { if (!cancelled) setLoadError(err.message || "Couldn't load your boards"); });
    return () => { cancelled = true; };
  }, []);

  const openBoard = (slug) => { location.href = `/b/${encodeURIComponent(slug)}`; };

  return (
    <div style={{
      position: "absolute", inset: 0, overflowY: "auto",
      background: palette.bg,
    }}>
      <div className="paper-noise" />

      <div style={{
        maxWidth: 1080, margin: "0 auto",
        padding: isMobile ? "84px 20px 80px" : "112px 48px 96px",
        position: "relative",
      }}>
        {/* Hero */}
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: isMobile ? 12 : 32 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="chip" style={{ marginBottom: isMobile ? 12 : 18 }}>
              <span style={{ color: palette.accent }}>●</span> a board for goodbyes
            </div>
            <h1 className="wordmark" style={{ fontSize: isMobile ? 56 : 92, margin: 0, lineHeight: 0.95 }}>
              <em>Fare<span className="comma" style={{ color: palette.accent }}>,</span> well<span className="comma" style={{ color: palette.accent }}>.</span></em>
            </h1>
            <p style={{
              fontFamily: "var(--serif)", fontSize: isMobile ? 18 : 22, fontStyle: "italic",
              color: "var(--ink-2)", margin: isMobile ? "12px 0 0" : "18px 0 0", maxWidth: 520,
              lineHeight: 1.4,
            }}>
              A soft, slow place to gather notes, photos and small kindnesses
              for someone who's moving on.
            </p>
          </div>

          <button className="btn btn-coral"
                  style={{
                    padding: isMobile ? "12px 14px" : "14px 22px",
                    fontSize: 14,
                    flex: "0 0 auto",
                  }}
                  onClick={onCreate}
                  title="Start a new board"
                  aria-label="Start a new board">
            <IconPlus size={isMobile ? 16 : 15} />{!isMobile && <span>Start a new board</span>}
          </button>
        </div>

        <hr className="dashed-line" style={{ margin: "56px 0 32px" }} />

        {/* Board list */}
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 22 }}>
          <h2 style={{ fontFamily: "var(--serif)", fontSize: 28, margin: 0, fontWeight: 400 }}>Your boards</h2>
          {boards && (
            <span className="chip">{boards.length === 1 ? "1 board" : `${boards.length} boards`}</span>
          )}
        </div>

        {loadError && (
          <div style={{
            padding: "12px 16px", borderRadius: 12, fontSize: 13, marginBottom: 22,
            background: "rgba(232,126,90,0.10)", color: "var(--ink)",
            border: "1px solid rgba(232,126,90,0.35)",
          }}>{loadError}</div>
        )}

        <div style={{
          display: "grid", gap: 22,
          gridTemplateColumns: "repeat(auto-fill, minmax(290px, 1fr))",
        }}>
          {boards && boards.map((b) => (
            <BoardCard key={b.id} board={b} palette={palette} onClick={() => openBoard(b.slug)} />
          ))}
          {/* Always offer the "new board" affordance, even mid-load. */}
          <button onClick={onCreate} style={{
            border: `1.5px dashed #D6CFC0`,
            borderRadius: 18, padding: 32, background: "transparent",
            display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
            gap: 10, color: "var(--ink-2)", cursor: "pointer",
            minHeight: 240, fontFamily: "var(--sans)",
            transition: "border-color .15s, color .15s, background .15s",
          }} onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--ink)"; e.currentTarget.style.color = "var(--ink)"; }}
             onMouseLeave={(e) => { e.currentTarget.style.borderColor = "#D6CFC0"; e.currentTarget.style.color = "var(--ink-2)"; }}>
            <IconPlus size={22} />
            <span style={{ fontSize: 14, fontWeight: 500 }}>New board</span>
          </button>
        </div>

        {boards && boards.length === 0 && !loadError && (
          <div style={{
            marginTop: 32, padding: "20px 24px", borderRadius: 14,
            background: "rgba(31,27,23,0.03)", border: "1px dashed var(--line-2)",
            color: "var(--ink-2)", fontFamily: "var(--serif)", fontStyle: "italic",
            fontSize: 17,
          }}>
            No boards yet — start one for someone who's moving on.
          </div>
        )}

        {/* Footer note */}
        <div style={{ marginTop: 72, color: "var(--ink-3)", fontSize: 12, fontFamily: "var(--mono)" }}>
          v.0.7  ·  made for warm goodbyes. -- K.
        </div>
      </div>
    </div>
  );
}

function BoardCard({ board, onClick, palette }) {
  const accent = palette?.notes?.[0] || "#FFD9A8";
  const initial = (board.recipientName || "?").trim()[0]?.toUpperCase() || "?";
  return (
    <button onClick={onClick} style={{
      position: "relative", textAlign: "left",
      background: "var(--paper)", border: "1px solid var(--line)",
      borderRadius: 18, padding: 0, overflow: "hidden",
      cursor: "pointer", minHeight: 240,
      transition: "transform .15s, box-shadow .15s, border-color .15s",
      display: "flex", flexDirection: "column",
      fontFamily: "var(--sans)",
    }} onMouseEnter={(e) => {
      e.currentTarget.style.transform = "translateY(-2px)";
      e.currentTarget.style.boxShadow = "var(--shadow-2)";
      e.currentTarget.style.borderColor = "var(--line-2)";
    }} onMouseLeave={(e) => {
      e.currentTarget.style.transform = "none";
      e.currentTarget.style.boxShadow = "none";
      e.currentTarget.style.borderColor = "var(--line)";
    }}>
      {/* Peek of the board — a small "for X" sticker as the visual */}
      <div style={{
        position: "relative", height: 130, overflow: "hidden",
        background: "#F8F4ED",
        borderBottom: "1px solid var(--line)",
        display: "grid", placeItems: "center",
      }}>
        <div style={{
          width: 76, height: 76, borderRadius: 10,
          background: accent,
          display: "grid", placeItems: "center",
          fontFamily: "var(--serif)", fontSize: 38, fontStyle: "italic",
          color: "var(--ink)",
          transform: "rotate(-4deg)",
          boxShadow: "var(--shadow-1)",
        }}>{initial}</div>
      </div>

      <div style={{ padding: "18px 18px 16px", display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12 }}>
          <h3 style={{ fontFamily: "var(--serif)", fontSize: 24, margin: 0, fontWeight: 400, letterSpacing: "-0.01em" }}>
            For {board.recipientName || "—"}
          </h3>
          {board.isAdmin && (
            <span style={{
              fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.08em",
              textTransform: "uppercase", color: "var(--coral)",
              padding: "2px 6px", border: "1px solid var(--coral)", borderRadius: 4,
            }}>admin</span>
          )}
        </div>
        {board.team && (
          <div style={{ color: "var(--ink-2)", fontSize: 13 }}>{board.team}</div>
        )}
        <div style={{ marginTop: "auto", display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--ink-3)", fontSize: 12 }}>
            <IconUsers size={13} /> {board.contributorCount === 1 ? "1 contributor" : `${board.contributorCount || 0} contributors`}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--ink-3)", fontSize: 12 }}>
            {board.noteCount === 1 ? "1 note" : `${board.noteCount || 0} notes`}
          </div>
        </div>
      </div>
    </button>
  );
}

Object.assign(window, { HomeScreen });
