// 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, trialPlan = null }) {
  const me = (typeof window.useVandayMe === "function") ? window.useVandayMe() : null;
  const currentName = (me && me.org && me.org.name) || "";
  // Social publishing is Growth/Pro only now — beta users don't get it, so the
  // "included" line and the connect-accounts step are gated on the entitlement.
  const socialAvailable = me?.limits?.socialPublishing === true;
  // Trial variant: when the user just started a 14-day plan trial, the modal
  // uses trial language + the plan's real limits instead of the beta copy.
  const PLAN_LABELS = { starter: "Starter", growth: "Growth", pro: "Pro" };
  const isTrial = !!trialPlan;
  const planLabel = PLAN_LABELS[trialPlan] || "";
  const trialGB = Math.round((me?.limits?.maxStorageBytes || 5 * 1024 * 1024 * 1024) / (1024 * 1024 * 1024));
  const trialSeats = me?.limits?.maxSeats || 3;

  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
      // "Skip for now" or "Upload your images".
      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,
          // Cap the card to the viewport (the wrapper has 24px padding on each
          // side, so 48px total) and let it scroll internally on short screens
          // — otherwise the bottom of the card (including the action buttons)
          // is pushed off-screen on small laptops. Reported by a beta user.
          maxHeight: "calc(100vh - 48px)",
          overflowY: "auto",
          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">
              {isTrial ? `Welcome to Vanday ${planLabel}` : "Welcome to Vanday Beta"}
            </div>
            <div style={{ fontSize: 12.5, opacity: 0.65, marginTop: 2 }}>
              {isTrial ? "14-day free trial · full access" : "Free plan · early access"}
            </div>
          </div>
        </div>

        <p style={{ fontSize: 14, lineHeight: 1.55, margin: "0 0 16px", opacity: 0.85 }}>
          {isTrial ? (
            <>Your <strong>14-day {planLabel} trial</strong> is live — full access, no card required.
            Add a plan before it ends to keep everything, and we'll remind you as the trial winds down.</>
          ) : (
            <>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 your images — <strong>{isTrial ? `${trialGB}GB storage` : "5GB of storage"}</strong></li>
              {isTrial && <li>✓ Up to <strong>{trialSeats} team members</strong></li>}
              <li>✓ AI keyword tagging</li>
              <li>✓ Auto-generated crops</li>
              <li>✓ Download originals + crops</li>
              <li>✓ Shareable gallery links</li>
              {socialAvailable && (
                <li>✓ Publish to <strong>Instagram, Facebook, LinkedIn, X &amp; Pinterest</strong></li>
              )}
            </ul>
          </div>
          <div>
            <div style={{ fontWeight: 600, marginBottom: 8, opacity: 0.7 }}>{isTrial ? "Your trial" : "Coming soon"}</div>
            <ul style={{ margin: 0, padding: 0, listStyle: "none", lineHeight: 1.7, opacity: 0.65 }}>
              {isTrial ? (
                <>
                  <li>· 14 days, full access</li>
                  <li>· No card required to start</li>
                  <li>· Reminders before it ends</li>
                  <li>· Add a plan anytime to keep going</li>
                </>
              ) : (
                <>
                  {!socialAvailable && <li>· Social publishing to Instagram, Facebook &amp; more</li>}
                  <li>· Larger team workspaces</li>
                  <li>· Higher upload limits</li>
                  <li>· Custom branded portals</li>
                  <li>· IPTC metadata support</li>
                </>
              )}
            </ul>
          </div>
        </div>

        {socialAvailable && (
          <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 upload anytime from the library"
          >
            Skip for now
          </button>
          <button
            type="button"
            disabled={saving}
            onClick={() => finish(() => {
              onClose();
              if (window.__vandayUploadToInbox) window.__vandayUploadToInbox();
            })}
            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…" : "Upload your images"}
          </button>
        </div>
      </div>
    </div>
  );
}

window.WelcomeModal = WelcomeModal;
