// Vanday — first-sign-in welcome modal.
//
// Shown to free-beta users once, when their `onboardedAt` is null. Lists what
// the beta plan includes / doesn't include, and explicitly tells them we'll
// reach out when paid plans + more features launch.

function WelcomeModal({ open, onClose }) {
  const me = (typeof window.useVandayMe === "function") ? window.useVandayMe() : null;
  const currentName = (me && me.org && me.org.name) || "";

  const [wsName, setWsName] = React.useState("");
  const [savedFor, setSavedFor] = React.useState(null);
  const [saving, setSaving] = React.useState(false);

  // Seed the input with the auto-generated default once /api/me arrives, but
  // only the first time so we don't clobber what the user is typing.
  React.useEffect(() => {
    if (currentName && savedFor === null && wsName === "") {
      setWsName(currentName);
      setSavedFor(currentName);
    }
  }, [currentName, savedFor, wsName]);

  // Persist the workspace name (if changed) before running the close action.
  // Naming is best-effort: a failed save must never trap the user in the modal.
  const finish = React.useCallback(async (after) => {
    const name = wsName.trim().replace(/\s+/g, " ");
    if (name && name !== savedFor && !saving) {
      setSaving(true);
      try {
        await window.VandayAPI.setOrgName(name);
        if (window.VandayMe) await window.VandayMe.fetchMe();
        setSavedFor(name);
      } catch (e) {
        console.warn("[welcome] couldn't save workspace name:", e && e.message);
      } finally {
        setSaving(false);
      }
    }
    if (typeof after === "function") after();
  }, [wsName, savedFor, saving]);

  if (!open) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="vanday-welcome-title"
      // Intentionally NOT dismissing on backdrop click — too easy to lose the
      // welcome by mis-clicking outside the dialog. User must explicitly hit
      // "Got it" or "Connect accounts".
      style={{
        position: "fixed", inset: 0, zIndex: 9999,
        background: "rgba(8, 12, 22, 0.55)",
        display: "grid", placeItems: "center",
        padding: 24, backdropFilter: "blur(4px)",
      }}
    >
      <div
        style={{
          background: "var(--surface, #fff)",
          color: "var(--text, #111)",
          width: "100%", maxWidth: 520,
          borderRadius: 14,
          boxShadow: "0 20px 60px rgba(0,0,0,0.25)",
          padding: "32px 32px 24px",
          fontFamily: "inherit",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
          <div
            style={{
              width: 40, height: 40, borderRadius: 10,
              background: "var(--brand, #5b6cff)",
              color: "white",
              display: "grid", placeItems: "center",
              fontWeight: 700, fontSize: 18,
            }}
          >v.</div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 17 }} id="vanday-welcome-title">
              Welcome to Vanday Beta
            </div>
            <div style={{ fontSize: 12.5, opacity: 0.65, marginTop: 2 }}>
              Free plan · early access
            </div>
          </div>
        </div>

        <p style={{ fontSize: 14, lineHeight: 1.55, margin: "0 0 16px", opacity: 0.85 }}>
          You're on the <strong>free beta plan</strong>. Try out the core of Vanday and
          let us know what you think — we'll email you the moment paid plans
          and additional features become available.
        </p>

        <div style={{ margin: "0 0 20px" }}>
          <label
            htmlFor="vanday-ws-name"
            style={{ display: "block", fontWeight: 600, fontSize: 13, marginBottom: 6 }}
          >
            Name your workspace
          </label>
          <input
            id="vanday-ws-name"
            type="text"
            value={wsName}
            onChange={(e) => setWsName(e.target.value)}
            maxLength={60}
            placeholder="e.g. Vanday Studio"
            style={{
              width: "100%",
              padding: "10px 12px",
              borderRadius: 8,
              border: "1px solid var(--border)",
              background: "var(--surface)",
              color: "var(--text)",
              fontSize: 14,
              fontFamily: "inherit",
              boxSizing: "border-box",
            }}
          />
          <div style={{ fontSize: 12, opacity: 0.6, marginTop: 6 }}>
            This is the name you'll see in the top-left. You can change it later in
            Settings → Workspace.
          </div>
        </div>

        <div
          style={{
            display: "grid",
            gridTemplateColumns: "1fr 1fr",
            gap: 16,
            margin: "12px 0 22px",
            fontSize: 13,
          }}
        >
          <div>
            <div style={{ fontWeight: 600, marginBottom: 8 }}>Included</div>
            <ul style={{ margin: 0, padding: 0, listStyle: "none", lineHeight: 1.7 }}>
              <li>✓ Upload up to <strong>100 images</strong></li>
              <li>✓ AI keyword tagging</li>
              <li>✓ Auto-generated crops</li>
              <li>✓ Download originals + crops</li>
              <li>✓ Publish to <strong>Instagram, Facebook, LinkedIn, X &amp; Pinterest</strong></li>
            </ul>
          </div>
          <div>
            <div style={{ fontWeight: 600, marginBottom: 8, opacity: 0.7 }}>Coming soon</div>
            <ul style={{ margin: 0, padding: 0, listStyle: "none", lineHeight: 1.7, opacity: 0.65 }}>
              <li>· Shareable gallery links</li>
              <li>· Larger team workspaces</li>
              <li>· Higher upload limits</li>
              <li>· Custom branded portals</li>
            </ul>
          </div>
        </div>

        <div
          style={{
            background: "var(--accent-soft, oklch(0.94 0.04 38))",
            border: "1px solid color-mix(in oklch, var(--accent, oklch(0.58 0.16 32)) 22%, transparent)",
            borderRadius: 10,
            padding: "14px 16px",
            margin: "0 0 18px",
            fontSize: 13,
            lineHeight: 1.55,
          }}
        >
          <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4 }}>
            One last step — connect your social accounts
          </div>
          <div style={{ opacity: 0.85 }}>
            To publish from Vanday, hook up your Instagram, Facebook, LinkedIn,
            X, or Pinterest accounts. You can skip and come back to this anytime
            in <strong>Settings → Connections</strong>.
          </div>
        </div>

        <p style={{ fontSize: 12.5, lineHeight: 1.55, margin: "0 0 22px", opacity: 0.65 }}>
          We've also added a few sample images to your library to get you started.
          Feel free to delete them whenever you like — they're marked with a
          <em> Demo</em> badge.
        </p>

        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <button
            type="button"
            disabled={saving}
            onClick={() => finish(onClose)}
            style={{
              padding: "9px 16px",
              borderRadius: 8,
              border: "1px solid var(--border)",
              background: "var(--surface)",
              color: "var(--text-muted)",
              fontWeight: 500,
              fontSize: 14,
              cursor: saving ? "default" : "pointer",
              opacity: saving ? 0.6 : 1,
            }}
            title="You can connect anytime from Settings → Connections"
          >
            Skip for now
          </button>
          <button
            type="button"
            disabled={saving}
            onClick={() => finish(() => {
              try { localStorage.setItem("vanday_settings_section", "connections"); } catch {}
              if (window.__vandayGoto) window.__vandayGoto("settings");
              onClose();
            })}
            style={{
              padding: "9px 18px",
              borderRadius: 8,
              border: "none",
              background: "var(--accent, #c8553d)",
              color: "white",
              fontWeight: 500,
              fontSize: 14,
              cursor: saving ? "default" : "pointer",
              opacity: saving ? 0.7 : 1,
            }}
          >
            {saving ? "Saving…" : "Connect accounts"}
          </button>
        </div>
      </div>
    </div>
  );
}

window.WelcomeModal = WelcomeModal;
