// First-run onboarding for AI access.
//
// Self-serve users choose between included platform credits and bringing their
// own provider key. Company-managed users see a no-decision welcome screen:
// their admin has already handled AI access, billing, seats, and provider setup.

const ONBOARDING_VERSION = "v1";
const ONBOARDING_PREFIX = `pl.onboarding.${ONBOARDING_VERSION}.`;

function onboardingUserKey(user) {
  return `${ONBOARDING_PREFIX}${user?.id || user?.email || "anonymous"}`;
}

function safeJsonParse(value) {
  try { return value ? JSON.parse(value) : null; } catch { return null; }
}

function readOnboarding(user) {
  try { return safeJsonParse(window.localStorage.getItem(onboardingUserKey(user))); } catch { return null; }
}

function saveOnboarding(user, payload = {}) {
  const record = {
    ...payload,
    completedAt: new Date().toISOString(),
    version: ONBOARDING_VERSION,
  };
  try { window.localStorage.setItem(onboardingUserKey(user), JSON.stringify(record)); } catch {}
  return record;
}

window.Onboarding = {
  hasCompleted: (user) => !!readOnboarding(user)?.completedAt,
  read: readOnboarding,
  save: saveOnboarding,
};

const { useState: useStateOnb, useEffect: useEffectOnb } = React;

const ONBOARDING_PROVIDERS = [
  {
    id: "openai",
    name: "OpenAI",
    tagline: "Use your OpenAI account",
    keyPrefix: "sk-...",
    mark: "AI",
    markStyle: { background: "#10A37F", color: "white" },
  },
  {
    id: "anthropic",
    name: "Anthropic",
    tagline: "Use your Anthropic account",
    keyPrefix: "sk-ant-...",
    mark: "AN",
    markStyle: { background: "#D97757", color: "white" },
  },
];

function effectiveCompanyName(user, aiAccess) {
  return user?.companyLicenseName || aiAccess?.companyName || user?.company || "your company";
}

function OnboardingChoice({ icon, title, body, selected, onClick, children }) {
  return (
    <button
      type="button"
      className={`onboarding-choice ${selected ? "is-selected" : ""}`}
      onClick={onClick}
    >
      <span className="onboarding-choice-icon"><Icon name={icon} size={22}/></span>
      <span className="onboarding-choice-copy">
        <span className="onboarding-choice-title">{title}</span>
        <span className="onboarding-choice-body">{body}</span>
        {children}
      </span>
    </button>
  );
}

function CompanyManagedOnboarding({ user, aiAccess, onComplete }) {
  const company = effectiveCompanyName(user, aiAccess);
  const seats = user?.companyLicenseSeats || aiAccess?.companySeats || null;
  return (
    <div className="screen onboarding-screen">
      <main className="onboarding-shell">
        <div className="onboarding-brand">
          <img src="assets/cabl-logo.png" alt="CABL"/>
          <span>CABL Procurement Lab</span>
        </div>

        <section className="onboarding-panel onboarding-company-panel">
          <div className="onboarding-kicker">Company access</div>
          <h1 className="display-sm">You're ready to use CABL.</h1>
          <p className="onboarding-lede">
            {company} has already set up AI access for this workspace. You do not need to choose a model,
            paste an API key, or think about credits before starting a negotiation.
          </p>

          <div className="onboarding-assurance-grid">
            <div>
              <Icon name="shield-check" size={22}/>
              <strong>Managed by your organization</strong>
              <span>Your admin handles seats, provider setup, and billing.</span>
            </div>
            <div>
              <Icon name="key-round" size={22}/>
              <strong>No personal API key needed</strong>
              <span>AI requests use the company setup, not an individual user's key.</span>
            </div>
            <div>
              <Icon name="briefcase-business" size={22}/>
              <strong>{seats ? `${seats} seats covered` : "Company license covered"}</strong>
              <span>Your role is to prepare the case, not manage infrastructure.</span>
            </div>
          </div>

          <div className="onboarding-note">
            If your company wants Azure OpenAI, Anthropic, Vertex, or a private tenant, that is configured with
            the CABL team before employees are invited.
          </div>

          <div className="onboarding-actions">
            <button className="btn-primary big" onClick={() => onComplete({ choice: "company_managed" })}>
              <IconText name="arrow-right" after>Enter workspace</IconText>
            </button>
          </div>
        </section>
      </main>
    </div>
  );
}

function SelfServeOnboarding({ user, aiAccess, creditStatus, onComplete }) {
  const [choice, setChoice] = useStateOnb("platform");
  const [provider, setProvider] = useStateOnb(window.ByoKey?.provider?.() || "openai");
  const [keyInput, setKeyInput] = useStateOnb("");
  const [rememberKey, setRememberKey] = useStateOnb(true);
  const [reveal, setReveal] = useStateOnb(false);
  const [status, setStatus] = useStateOnb(null);
  const [busy, setBusy] = useStateOnb(false);
  const selectedProvider = ONBOARDING_PROVIDERS.find((p) => p.id === provider) || ONBOARDING_PROVIDERS[0];
  const creditLine = creditStatus
    ? `You currently have ${Math.floor(creditStatus.remaining)} weekly credits available.`
    : "Weekly credits are included with the built-in AI setup.";

  useEffectOnb(() => {
    setStatus(null);
  }, [choice, provider]);

  function usePlatformCredits() {
    window.ByoKey?.remove?.("openai");
    window.ByoKey?.remove?.("anthropic");
    onComplete({ choice: "platform_credits" });
  }

  async function validateAndContinue() {
    if (!keyInput.trim()) {
      setStatus({ kind: "error", message: "Paste a key first. If you do not already have one, choose included credits." });
      return;
    }
    setBusy(true);
    setStatus({ kind: "info", message: `Checking the ${selectedProvider.name} key...` });
    try {
      const resp = await fetch("/api/validate-key", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ provider, apiKey: keyInput.trim() }),
      });
      const data = await resp.json().catch(() => ({}));
      if (!data.valid) {
        setStatus({ kind: "error", message: data.error || `${selectedProvider.name} rejected this key.` });
        return;
      }
      window.ByoKey.write(keyInput.trim(), { provider, persist: rememberKey });
      onComplete({ choice: "byo_key", provider, rememberedOnDevice: rememberKey });
    } catch {
      setStatus({ kind: "error", message: "Couldn't check the key. You can choose included credits and add a key later." });
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="screen onboarding-screen">
      <main className="onboarding-shell">
        <div className="onboarding-brand">
          <img src="assets/cabl-logo.png" alt="CABL"/>
          <span>CABL Procurement Lab</span>
        </div>

        <section className="onboarding-panel">
          <div className="onboarding-kicker">First setup</div>
          <h1 className="display-sm">How should we power your negotiation preparation?</h1>
          <p className="onboarding-lede">
            Procurement Lab can run in two ways: with the built-in AI setup or with your own AI provider account.
          </p>

          <div className="onboarding-choice-grid">
            <OnboardingChoice
              icon="coins"
              title="Use the built-in AI setup"
              body="Default option. No setup required. Procurement Lab is ready to use immediately — you do not need an OpenAI or Anthropic account, and you do not need to enter an API key. This option uses your Procurement Lab credits."
              selected={choice === "platform"}
              onClick={() => setChoice("platform")}
            >
              <span className="onboarding-choice-meta">{creditLine}</span>
            </OnboardingChoice>

            {aiAccess?.allowUserKeys !== false && (
              <OnboardingChoice
                icon="key-round"
                title="Connect my own AI account"
                body="For users or teams who already have an OpenAI or Anthropic account and want Procurement Lab to send AI requests through that account. Your AI provider charges your account directly instead of using Procurement Lab credits."
                selected={choice === "byo"}
                onClick={() => setChoice("byo")}
              >
                <span className="onboarding-choice-meta">Not sure? Use the built-in AI setup. You can connect your own AI account later from Settings.</span>
              </OnboardingChoice>
            )}
          </div>

          {choice === "platform" && (
            <div className="onboarding-explain">
              <h2>Good for</h2>
              <ul>
                <li><Icon name="check" size={15}/><span>Starting right away</span></li>
                <li><Icon name="check" size={15}/><span>Running regular negotiation preparation</span></li>
                <li><Icon name="check" size={15}/><span>Avoiding technical setup</span></li>
              </ul>
              <div className="onboarding-note">{creditLine}</div>
              <div className="onboarding-actions">
                <button className="btn-primary big" onClick={usePlatformCredits}>
                  <IconText name="arrow-right" after>Use the built-in AI setup</IconText>
                </button>
              </div>
            </div>
          )}

          {choice === "byo" && (
            <div className="onboarding-key-panel">
              <h2>Connect your AI account</h2>
              <p>
                This gives you more control over your AI provider, billing, and internal setup. Good for using your
                company's existing AI provider account, having AI usage billed directly to your company, and meeting
                internal privacy, security, or compliance requirements.
              </p>
              <p>
                You will need an API key from OpenAI or Anthropic. Your key is only used to send requests to your
                provider and is not stored on our servers.
              </p>

              <div className="onboarding-provider-row">
                {ONBOARDING_PROVIDERS.map((p) => (
                  <button
                    key={p.id}
                    type="button"
                    className={`onboarding-provider ${provider === p.id ? "is-selected" : ""}`}
                    onClick={() => setProvider(p.id)}
                  >
                    <span className="provider-mark" style={p.markStyle}>{p.mark}</span>
                    <span>
                      <strong>{p.name}</strong>
                      <small>{p.tagline}</small>
                    </span>
                  </button>
                ))}
              </div>

              <div className="settings-key-row onboarding-key-row">
                <input
                  type={reveal ? "text" : "password"}
                  className="settings-key-input"
                  placeholder={selectedProvider.keyPrefix}
                  value={keyInput}
                  onChange={(e) => setKeyInput(e.target.value)}
                  autoComplete="off"
                  spellCheck="false"
                />
                <button type="button" className="btn-ghost" onClick={() => setReveal((r) => !r)}>
                  <IconText name={reveal ? "eye-off" : "eye"}>{reveal ? "Hide" : "Show"}</IconText>
                </button>
              </div>

              <label className="onboarding-checkbox">
                <input
                  type="checkbox"
                  checked={rememberKey}
                  onChange={(e) => setRememberKey(e.target.checked)}
                />
                <span>Remember this key on this device so you do not have to paste it again.</span>
              </label>

              <div className="onboarding-note">
                We do not store this key on the server. It is saved only in this browser if you choose to remember it.
              </div>

              {status && <div className={`settings-status settings-status-${status.kind}`}>{status.message}</div>}

              <div className="onboarding-actions">
                <button className="btn-ghost" onClick={() => setChoice("platform")} disabled={busy}>
                  <IconText name="arrow-left">Use credits instead</IconText>
                </button>
                <button className="btn-primary big" onClick={validateAndContinue} disabled={busy}>
                  <IconText name={busy ? "rotate-cw" : "check"}>{busy ? "Checking..." : "Validate & continue"}</IconText>
                </button>
              </div>
            </div>
          )}
        </section>
      </main>
    </div>
  );
}

function OnboardingScreen({ user, aiAccess, creditStatus, onComplete }) {
  const companyManaged = aiAccess?.mode === "company_managed" || user?.aiAccessMode === "company_managed";

  function complete(payload) {
    if (payload?.choice === "company_managed") {
      window.ByoKey?.remove?.("openai");
      window.ByoKey?.remove?.("anthropic");
    }
    window.Onboarding.save(user, payload);
    onComplete(payload);
  }

  if (companyManaged) {
    return <CompanyManagedOnboarding user={user} aiAccess={aiAccess} onComplete={complete}/>;
  }

  return <SelfServeOnboarding user={user} aiAccess={aiAccess} creditStatus={creditStatus} onComplete={complete}/>;
}

window.OnboardingScreen = OnboardingScreen;
