// ---------- Signup / Onboarding flow ----------
// Lightweight multi-step that lands an org into the app shell + Apps directory.

const SignupPage = ({ onComplete, onBackToLanding }) => {
  const [step, setStep] = React.useState(0);
  const [orgName, setOrgName] = React.useState("");
  const [subdomain, setSubdomain] = React.useState("");
  const [fullName, setFullName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [role, setRole] = React.useState("Studio lead");
  const [size, setSize] = React.useState("3–8");
  const [focus, setFocus] = React.useState(["Listing films", "Brand reels"]);
  const [pickedApps, setPickedApps] = React.useState(new Set(["frame", "drive", "slack"]));

  const slug = subdomain || orgName.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");

  const focusOptions = ["Listing films", "Brand reels", "YouTube long-form", "Podcasts", "Documentary", "Launch campaigns", "Photography", "Live events"];

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

  const steps = [
    { id: "org",     label: "Workspace" },
    { id: "you",     label: "About you" },
    { id: "focus",   label: "Studio focus" },
    { id: "apps",    label: "Connect apps" },
  ];

  return (
    <div className="light-scroll" style={{ background: "var(--paper)", color: "var(--ink)", minHeight: "100vh", fontFamily: "var(--sans)" }}>
      {/* Decorative topo lines */}
      <svg style={{ position: "fixed", inset: 0, width: "100%", height: "100%", opacity: 0.05, pointerEvents: "none", zIndex: 0 }} viewBox="0 0 1280 800" preserveAspectRatio="xMidYMid slice">
        {Array.from({ length: 18 }).map((_, i) => {
          const y = 60 + i * 40;
          return <path key={i} d={`M -100 ${y} Q 320 ${y - 24 + (i % 3) * 8} 640 ${y} T 1380 ${y}`} stroke="var(--ink)" fill="none" strokeWidth="0.6" />;
        })}
      </svg>

      {/* Slim top nav */}
      <header style={{ position: "relative", zIndex: 1, padding: "20px 0", borderBottom: "1px solid rgba(8,12,16,0.06)" }}>
        <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <button onClick={onBackToLanding} style={{
            background: "transparent", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--sans)",
          }}>
            <HDLockup light markSize={28} />
          </button>
          <div style={{ fontSize: 12.5, color: "rgba(8,12,16,0.55)" }}>
            Already have an account? <button onClick={onComplete} style={{ background: "transparent", border: "none", color: "var(--ink)", fontWeight: 500, cursor: "pointer", textDecoration: "underline", textUnderlineOffset: 3, fontFamily: "var(--sans)", fontSize: 12.5 }}>Sign in</button>
          </div>
        </div>
      </header>

      <main style={{ position: "relative", zIndex: 1, padding: "48px 24px 80px" }}>
        <div style={{ maxWidth: 1080, margin: "0 auto", display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr)", gap: 64, alignItems: "start" }} className="md-stack">

          {/* Left: editorial side */}
          <div>
            <div className="micro" style={{ color: "rgba(8,12,16,0.45)", marginBottom: 14 }}>OPEN A HARBORDOCK</div>
            <h1 className="serif" style={{
              fontSize: 56, lineHeight: 1.05, letterSpacing: "-0.025em",
              fontWeight: 500, margin: 0,
            }}>
              Set up your studio<br />
              <span style={{ fontStyle: "italic", color: "rgba(8,12,16,0.55)" }}>in under two minutes.</span>
            </h1>
            <p style={{ fontSize: 16, lineHeight: 1.65, color: "rgba(8,12,16,0.62)", marginTop: 28, maxWidth: 460 }}>
              No credit card. The first 14 days are free, with every surface unlocked —
              including the branded client portal and every app connection.
            </p>

            {/* Step indicator */}
            <div style={{ marginTop: 40, display: "flex", flexDirection: "column", gap: 14 }}>
              {steps.map((s, i) => (
                <SignupStepIndicator
                  key={s.id}
                  index={i}
                  label={s.label}
                  state={i < step ? "done" : i === step ? "active" : "pending"}
                />
              ))}
            </div>

            <Card light style={{ marginTop: 36, padding: 18, background: "rgba(8,12,16,0.02)" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: "rgba(29,78,216,0.10)", border: "1px solid rgba(29,78,216,0.24)",
                  color: "var(--harbor)",
                  display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                }}><window.Icon.Shield size={16} /></div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>SOC 2 Type II · EU + US residency</div>
                  <div style={{ fontSize: 12, color: "rgba(8,12,16,0.55)", marginTop: 4, lineHeight: 1.55 }}>
                    Every project, asset, and approval is stored, versioned, and exportable.
                  </div>
                </div>
              </div>
            </Card>
          </div>

          {/* Right: form card */}
          <Card light style={{ padding: 0, overflow: "hidden", position: "sticky", top: 24, boxShadow: "0 30px 60px -24px rgba(8,12,16,0.20)" }}>
            <div style={{ padding: "20px 24px", borderBottom: "1px solid rgba(8,12,16,0.06)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div>
                <div className="micro" style={{ color: "rgba(8,12,16,0.45)", marginBottom: 4 }}>STEP {step + 1} OF {steps.length}</div>
                <div style={{ fontSize: 16, fontWeight: 600, color: "var(--ink)" }}>{steps[step].label}</div>
              </div>
              <div style={{ width: 80 }}>
                <div style={{ height: 4, background: "rgba(8,12,16,0.06)", borderRadius: 99, overflow: "hidden" }}>
                  <div style={{
                    width: `${((step + 1) / steps.length) * 100}%`, height: "100%",
                    background: "var(--harbor)", borderRadius: 99,
                    transition: "width 320ms cubic-bezier(.16,1,.3,1)",
                  }} />
                </div>
              </div>
            </div>

            <div style={{ padding: 24, minHeight: 320 }}>
              {step === 0 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                  <SignupField label="Studio / organization name" hint="What clients see at the top of every portal.">
                    <SignupInput value={orgName} onChange={setOrgName} placeholder="Winterhill Media" />
                  </SignupField>
                  <SignupField label="Workspace URL" hint="Used for your studio + client portals.">
                    <div style={{
                      display: "flex", alignItems: "center",
                      border: "1px solid rgba(8,12,16,0.12)", borderRadius: 8,
                      background: "white",
                    }}>
                      <span style={{ padding: "10px 4px 10px 12px", fontSize: 13, color: "rgba(8,12,16,0.55)" }}>harbor.dk/</span>
                      <input
                        value={slug}
                        onChange={(e) => setSubdomain(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""))}
                        placeholder="winterhill"
                        style={{
                          flex: 1, background: "transparent", border: "none", outline: "none",
                          padding: "10px 12px 10px 0", fontSize: 13, fontFamily: "var(--sans)",
                          color: "var(--ink)",
                        }}
                      />
                      {slug && (
                        <span style={{ padding: "0 12px", display: "inline-flex", alignItems: "center", gap: 4, color: "#16a34a", fontSize: 12 }}>
                          <window.Icon.Check size={12} stroke={2.4} /> available
                        </span>
                      )}
                    </div>
                  </SignupField>
                  <div style={{
                    padding: 12, borderRadius: 10,
                    background: "rgba(29,78,216,0.06)", border: "1px solid rgba(29,78,216,0.18)",
                    color: "var(--harbor)", display: "flex", gap: 10, alignItems: "flex-start",
                  }}>
                    <window.Icon.Sparkle size={14} stroke={2} />
                    <div style={{ fontSize: 12, color: "var(--ink)", lineHeight: 1.55 }}>
                      Atelier plans can swap this for your own domain — e.g. <span className="mono">review.winterhill.media</span>.
                    </div>
                  </div>
                </div>
              )}

              {step === 1 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                  <SignupField label="Your name">
                    <SignupInput value={fullName} onChange={setFullName} placeholder="Alex Winterhill" />
                  </SignupField>
                  <SignupField label="Work email" hint="We'll send a magic link to confirm.">
                    <SignupInput value={email} onChange={setEmail} placeholder="alex@winterhill.media" />
                  </SignupField>
                  <SignupField label="Your role">
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8 }}>
                      {["Studio lead", "Producer", "Editor", "Operations"].map(r => (
                        <SignupChip key={r} label={r} active={role === r} onClick={() => setRole(r)} light />
                      ))}
                    </div>
                  </SignupField>
                </div>
              )}

              {step === 2 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
                  <SignupField label="Studio size">
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
                      {["1–2", "3–8", "9–20", "20+"].map(s => (
                        <SignupChip key={s} label={s} active={size === s} onClick={() => setSize(s)} light />
                      ))}
                    </div>
                  </SignupField>
                  <SignupField label="What kinds of projects?" hint="Pick a few — we'll seed sensible templates.">
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                      {focusOptions.map(f => {
                        const active = focus.includes(f);
                        return (
                          <button
                            key={f}
                            onClick={() => setFocus(prev => active ? prev.filter(x => x !== f) : [...prev, f])}
                            style={{
                              padding: "7px 11px", borderRadius: 99, cursor: "pointer",
                              background: active ? "var(--ink)" : "white",
                              border: active ? "1px solid var(--ink)" : "1px solid rgba(8,12,16,0.12)",
                              color: active ? "white" : "var(--ink)",
                              fontSize: 12, fontFamily: "var(--sans)", fontWeight: 500,
                            }}
                          >
                            {active && "✓ "}{f}
                          </button>
                        );
                      })}
                    </div>
                  </SignupField>
                </div>
              )}

              {step === 3 && (
                <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                  <div style={{ fontSize: 13, color: "rgba(8,12,16,0.62)", lineHeight: 1.55 }}>
                    We pre-selected a few based on your focus. Connect any that fit — you can always add more from the <span style={{ color: "var(--ink)", fontWeight: 500 }}>Apps</span> tab later.
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {HD.apps.filter(a => a.featured).map(a => {
                      const active = pickedApps.has(a.id);
                      const tone = STATUS_TONES[a.accent];
                      const IconComp = window.Icon[a.icon] || window.Icon.Apps;
                      return (
                        <button
                          key={a.id}
                          onClick={() => {
                            const next = new Set(pickedApps);
                            if (active) next.delete(a.id); else next.add(a.id);
                            setPickedApps(next);
                          }}
                          style={{
                            display: "flex", alignItems: "center", gap: 12,
                            padding: "12px 14px", borderRadius: 10, cursor: "pointer", textAlign: "left",
                            background: active ? "rgba(29,78,216,0.06)" : "white",
                            border: active ? "1px solid rgba(29,78,216,0.30)" : "1px solid rgba(8,12,16,0.10)",
                            fontFamily: "var(--sans)",
                          }}
                        >
                          <div style={{
                            width: 36, height: 36, borderRadius: 8,
                            background: tone.bg, border: `1px solid ${tone.bd}`, color: tone.fg,
                            display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                          }}><IconComp size={16} /></div>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--ink)" }}>{a.name}</div>
                            <div style={{ fontSize: 11.5, color: "rgba(8,12,16,0.55)", marginTop: 2 }}>{a.tagline}</div>
                          </div>
                          <div style={{
                            width: 18, height: 18, borderRadius: 5,
                            background: active ? "var(--harbor)" : "transparent",
                            border: active ? "1px solid var(--harbor)" : "1px solid rgba(8,12,16,0.20)",
                            display: "flex", alignItems: "center", justifyContent: "center", color: "white",
                            flexShrink: 0,
                          }}>{active && <window.Icon.Check size={11} stroke={3} />}</div>
                        </button>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>

            <div style={{ padding: "16px 24px", borderTop: "1px solid rgba(8,12,16,0.06)", display: "flex", justifyContent: "space-between", gap: 8, background: "rgba(8,12,16,0.02)" }}>
              {step > 0
                ? <Button variant="ghost" light size="md" onClick={back} icon={<window.Icon.ChevronL size={12} />}>Back</Button>
                : <span />}
              {step < steps.length - 1 ? (
                <Button variant="secondary" light size="md" onClick={next} iconRight={<window.Icon.Arrow size={13} />}>
                  Continue
                </Button>
              ) : (
                <Button variant="secondary" light size="md" onClick={() => {
                  window.ToastEvents.emit({ kind: "success", title: `Welcome, ${fullName || "Studio"}`, body: `${orgName || "Your workspace"} is open. Apps will sync within a few minutes.` });
                  onComplete();
                }} iconRight={<window.Icon.Arrow size={13} />}>
                  Open my studio
                </Button>
              )}
            </div>
          </Card>
        </div>
      </main>
    </div>
  );
};

const SignupStepIndicator = ({ index, label, state }) => {
  const bg = state === "done" ? "var(--ink)" : state === "active" ? "white" : "transparent";
  const border = state === "pending" ? "1px solid rgba(8,12,16,0.16)" : "1px solid var(--ink)";
  const fg = state === "done" ? "white" : "var(--ink)";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, opacity: state === "pending" ? 0.5 : 1 }}>
      <div style={{
        width: 24, height: 24, borderRadius: 99,
        background: bg, border, color: fg,
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 11, fontWeight: 600, flexShrink: 0,
      }}>
        {state === "done" ? <window.Icon.Check size={12} stroke={3} /> : index + 1}
      </div>
      <span style={{ fontSize: 13.5, color: "var(--ink)", fontWeight: state === "active" ? 600 : 400 }}>{label}</span>
    </div>
  );
};

const SignupField = ({ label, hint, children }) => (
  <div>
    <label style={{ display: "block", marginBottom: 6 }}>
      <span style={{ fontSize: 12.5, fontWeight: 500, color: "var(--ink)" }}>{label}</span>
      {hint && <span style={{ marginLeft: 8, fontSize: 11.5, color: "rgba(8,12,16,0.55)" }}>{hint}</span>}
    </label>
    {children}
  </div>
);

const SignupInput = ({ value, onChange, placeholder, type = "text" }) => (
  <input
    type={type}
    value={value}
    onChange={(e) => onChange(e.target.value)}
    placeholder={placeholder}
    style={{
      width: "100%", background: "white",
      border: "1px solid rgba(8,12,16,0.12)", borderRadius: 8,
      padding: "10px 12px", color: "var(--ink)", fontSize: 13.5,
      fontFamily: "var(--sans)", outline: "none",
    }}
    onFocus={(e) => (e.currentTarget.style.borderColor = "var(--harbor)")}
    onBlur={(e) => (e.currentTarget.style.borderColor = "rgba(8,12,16,0.12)")}
  />
);

const SignupChip = ({ label, active, onClick, light }) => (
  <button
    onClick={onClick}
    style={{
      padding: "9px 12px", borderRadius: 8, cursor: "pointer", textAlign: "center",
      background: active ? "var(--ink)" : "white",
      border: active ? "1px solid var(--ink)" : "1px solid rgba(8,12,16,0.12)",
      color: active ? "white" : "var(--ink)",
      fontSize: 12.5, fontFamily: "var(--sans)", fontWeight: 500,
    }}
  >
    {label}
  </button>
);

window.SignupPage = SignupPage;
