// Create board flow — a 2-step wizard rendered as a paper card with soft
// transitions: recipient details → admin password. The board has no
// scheduled reveal; admins lock and send manually when they're ready.

function CreateBoardScreen({ palette, onCancel }) {
  const [step, setStep] = React.useState(0);
  const [name, setName] = React.useState("Gill Tan");
  const [team, setTeam] = React.useState("Atlas Design");
  const [note, setNote] = React.useState("A small wall of goodbye notes — drop in whatever you'd like to say.");
  const [coverColor, setCoverColor] = React.useState(palette.notes[0]);
  const [adminPassword, setAdminPassword] = React.useState("");
  const [creating, setCreating] = React.useState(false);
  const [createError, setCreateError] = React.useState(null);
  const isMobile = useIsMobile();

  const next = () => setStep((s) => Math.min(1, s + 1));
  const back = () => setStep((s) => Math.max(0, s - 1));

  const trimmedName = name.trim();
  const canCreate = trimmedName.length > 0
    && adminPassword.length >= 4
    && !creating;

  const handleCreate = async () => {
    if (!canCreate) return;
    setCreating(true);
    setCreateError(null);
    try {
      const { board } = await API.createBoard({
        recipientName: trimmedName,
        team: team.trim() || null,
        password: adminPassword,
      });
      // Hand the next page a one-shot signal to auto-open the invite modal.
      sessionStorage.setItem("fw:just-created", board.slug);
      // Hard-navigate so the App boots fresh against the new slug. The
      // creator is already an admin (board_admins row inserted by the
      // server) and the cookie carries their identity.
      window.location.href = `/b/${encodeURIComponent(board.slug)}`;
    } catch (err) {
      setCreating(false);
      setCreateError(err.message || "Couldn't create the board. Try again?");
    }
  };

  return (
    <div style={{
      position: "absolute", inset: 0, background: palette.bg,
      overflowY: "auto",
      // Tighter padding on phones so the form has room to breathe without
      // forcing a horizontal scroll past a fixed-width sidebar.
      padding: isMobile ? "72px 16px 32px" : "96px 40px 80px",
      display: "flex", justifyContent: "center", alignItems: "flex-start",
    }}>
      <div className="paper-noise" />

      <div style={{
        position: "relative", width: "100%", maxWidth: 920,
        display: "grid",
        // Mobile: single column, preview drops below (or hides) so the form
        // doesn't compete for horizontal space. Desktop: form + sticky
        // preview side by side.
        gridTemplateColumns: isMobile ? "1fr" : "1fr 380px",
        gap: isMobile ? 24 : 36,
        alignItems: "start",
      }}>
        {/* Left: form */}
        <div style={{ position: "relative", minWidth: 0 }}>
          <div className="chip" style={{ marginBottom: 14 }}>
            <span style={{ color: palette.accent }}>● </span>step {step + 1} of 2
          </div>
          <h1 style={{
            fontFamily: "var(--serif)",
            fontSize: isMobile ? 36 : 52,
            margin: 0, lineHeight: 1.05, fontWeight: 400, letterSpacing: "-0.01em",
          }}>
            {step === 0 && <span>Who's it <em>for?</em></span>}
            {step === 1 && <span>Who can <em>help?</em></span>}
          </h1>

          <p style={{
            fontFamily: "var(--serif)", fontStyle: "italic", color: "var(--ink-2)",
            fontSize: isMobile ? 16 : 19,
            marginTop: isMobile ? 10 : 14,
            marginBottom: isMobile ? 24 : 36,
            lineHeight: 1.4,
          }}>
            {step === 0 && "Just enough to set the scene. You can change everything later."}
            {step === 1 && "Pick a password. Anyone with it can manage the board."}
          </p>

          {step === 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: isMobile ? 18 : 24, maxWidth: isMobile ? "none" : 480 }}>
              <Field label="Their name">
                <input className="txt" value={name} onChange={(e) => setName(e.target.value)} />
              </Field>
              <Field label="Team or context (optional)">
                <input className="txt" value={team} onChange={(e) => setTeam(e.target.value)}
                       placeholder="e.g. Atlas Design" />
              </Field>
              <Field label="A note for contributors">
                <textarea className="txt" rows={3} value={note} onChange={(e) => setNote(e.target.value)} />
              </Field>
              <Field label="Cover color">
                <div style={{ display: "flex", gap: 10, marginTop: 6 }}>
                  {palette.notes.slice(0, 6).map((c) => (
                    <button key={c} onClick={() => setCoverColor(c)} style={{
                      width: 32, height: 32, borderRadius: "50%",
                      background: c, border: coverColor === c ? "2px solid var(--ink)" : "1px solid var(--line)",
                      cursor: "pointer", padding: 0,
                    }} />
                  ))}
                  <CustomColorButton
                    value={coverColor}
                    onPick={setCoverColor}
                    style={{ width: 32, height: 32, borderRadius: "50%" }}
                  />
                </div>
              </Field>
            </div>
          )}

          {step === 1 && (
            <div style={{ display: "flex", flexDirection: "column", gap: isMobile ? 18 : 24, maxWidth: isMobile ? "none" : 480 }}>
              <Field label="Admin password">
                <input className="txt" type="password" value={adminPassword}
                       autoFocus
                       onChange={(e) => setAdminPassword(e.target.value)}
                       placeholder="Pick something memorable"
                       minLength={4} />
                <div style={{ marginTop: 8, fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.5 }}>
                  Anyone you share this with can manage notes, lock the board for reveal,
                  and edit settings. <strong>You don't need to remember it</strong> — your
                  browser stays signed in. Set it again later in admin settings.
                </div>
              </Field>

              <div style={{
                padding: 18, background: "rgba(31,27,23,0.04)",
                borderRadius: 12, color: "var(--ink-2)", fontSize: 13,
                lineHeight: 1.5,
                display: "flex", gap: 12, alignItems: "flex-start",
              }}>
                <IconUsers size={16} style={{ marginTop: 2, color: "var(--ink-2)" }} />
                <span>
                  <strong>Contributors</strong> just need the board link. They'll be
                  asked their name once and can post notes from there. No password.
                </span>
              </div>
            </div>
          )}

          {/* Step nav */}
          <div style={{ display: "flex", gap: 12, marginTop: 44, alignItems: "center", flexWrap: "wrap" }}>
            {step > 0 && (
              <button className="btn btn-ghost" onClick={back} disabled={creating}>
                <IconArrowLeft size={14} /> Back
              </button>
            )}
            {step < 1 && (
              <button className="btn btn-primary" onClick={next}>
                Continue <IconArrowRight size={14} />
              </button>
            )}
            {step === 1 && (
              <button className="btn btn-coral"
                      onClick={handleCreate}
                      disabled={!canCreate}
                      style={{
                        opacity: canCreate ? 1 : 0.5,
                        cursor: canCreate ? "pointer" : "not-allowed",
                      }}>
                {creating ? "Creating…" : (
                  <>Create board <IconArrowRight size={14} /></>
                )}
              </button>
            )}
            <div style={{ flex: 1 }} />
            <button className="btn btn-ghost" onClick={onCancel} disabled={creating}>Cancel</button>
          </div>
          {createError && (
            <div style={{
              marginTop: 14, padding: "10px 14px", borderRadius: 10,
              background: "rgba(232,126,90,0.10)", color: "var(--ink)",
              fontSize: 13, lineHeight: 1.5,
              border: "1px solid rgba(232,126,90,0.35)",
            }}>{createError}</div>
          )}
        </div>

        {/* Right (or below, on mobile): preview */}
        <CreatePreview name={name} team={team} color={coverColor} accent={palette.accent} isMobile={isMobile} />
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div>
      <div className="chip" style={{ marginBottom: 4 }}>{label}</div>
      {children}
    </div>
  );
}

function CreatePreview({ name, team, color, accent, isMobile }) {
  return (
    <div style={{
      // Sticky preview only makes sense in a 2-column desktop layout; on
      // mobile it sits as a normal block under the form.
      position: isMobile ? "static" : "sticky",
      top: isMobile ? undefined : 96,
      background: "#fff",
      borderRadius: isMobile ? 16 : 20, overflow: "hidden",
      border: "1px solid var(--line)", boxShadow: "var(--shadow-2)",
    }}>
      <div style={{
        height: isMobile ? 140 : 180,
        background: color, position: "relative",
        display: "grid", placeItems: "center",
        backgroundImage: `repeating-linear-gradient(45deg, rgba(255,255,255,0.18) 0 6px, transparent 6px 18px)`,
      }}>
        <div style={{
          position: "absolute", top: 14, left: 14,
          fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em",
          textTransform: "uppercase", color: "rgba(31,27,23,0.6)",
        }}>preview</div>
        <div className="wordmark" style={{ fontSize: isMobile ? 28 : 36, color: "var(--ink)" }}>
          <em>For</em>
        </div>
      </div>

      <div style={{ padding: isMobile ? 18 : 22 }}>
        <h3 style={{
          fontFamily: "var(--serif)",
          fontSize: isMobile ? 26 : 32,
          margin: 0, lineHeight: 1.05, fontWeight: 400,
          wordBreak: "break-word",
        }}>
          {name || "Their name"}
        </h3>
        {team && <div style={{ color: "var(--ink-2)", marginTop: 6, fontSize: 14 }}>{team}</div>}
        <hr style={{ border: "none", borderTop: "1px dashed var(--line-2)", margin: isMobile ? "16px 0" : "20px 0" }} />
        <div style={{ display: "flex", flexDirection: "column", gap: 10, fontSize: 13, color: "var(--ink-2)" }}>
          <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <IconUsers size={14} /> Invite contributors next
          </span>
          <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <IconGift size={14} /> Lock and send when you're ready
          </span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CreateBoardScreen });
