// kova/auth.jsx — authentication surfaces
// ----------------------------------------------------------------
// PRODUCT NOTE — architecture v7 §4.1 says: "KOVA does not build password login."
// The canonical path is Cloudflare Access in front of every tenant with SSO via
// Microsoft Entra ID / Google Workspace / Google OAuth. Password login below is
// added at product owner's explicit request. If this contradiction needs to be
// resolved, see strategy decision D-LOGIN (to be added) before shipping.
//
// All other surfaces (/session bootstrap, /access-pending, /access-denied) are
// drawn from architecture §4.3 verbatim.
// ----------------------------------------------------------------

const { useState, useEffect } = React;
const { Btn, Input, Field, Chip, Kbd, Icon, Spinner } = window.K;


/* ============================================================
   PROVIDER BUTTON
   ============================================================ */
const ProviderBtn = ({ kind, label, meta, onClick, disabled }) => {
  const monogram = { google: 'G', microsoft: '◰', sso: 'S', email: '✉' }[kind] || '•';
  return (
    <button type="button" className="k-provider" onClick={onClick} disabled={disabled}>
      <span className={`k-provider-mark is-${kind}`}>{monogram}</span>
      <span className="k-provider-label">{label}</span>
      {meta && <span className="k-provider-meta">{meta}</span>}
    </button>
  );
};


/* ============================================================
   LOGIN PAGE — primary entry
   ============================================================ */
const LoginPage = ({ tenant = 'Acme Jewels', tenantId = 'acme', onAuthStart, onForgotPassword }) => {
  const [mode, setMode] = useState('chooser');    // 'chooser' | 'email' | 'submitting' | 'error'
  const [email, setEmail] = useState(`rohan@${tenantId}.com`);
  const [password, setPassword] = useState('');
  const [errorMsg, setErrorMsg] = useState('');

  const goSSO = (provider) => onAuthStart?.({ method: provider, tenant, tenantId });

  const submitEmail = (e) => {
    e?.preventDefault();
    if (!password) { setErrorMsg('Password is required.'); setMode('error'); return; }
    if (password.length < 4) { setErrorMsg('Incorrect email or password.'); setMode('error'); return; }
    setErrorMsg(''); setMode('submitting');
    onAuthStart?.({ method: 'password', tenant, email });
  };

  return (
    <div className="k-auth-card">
      <header className="k-auth-brand">
        <div className="k-auth-brand-mark">K</div>
        <div className="k-auth-brand-name">KOVA</div>
      </header>

      <h1 className="k-auth-title">Sign in to your workspace</h1>
      <p className="k-auth-sub">
        Use your work account, or sign in with email and password.
      </p>

      <div className="k-auth-tenant-chip">
        <span className="l">Workspace</span>
        <span>·</span>
        <strong>{tenantId}.kova.app</strong>
        <span style={{ marginLeft: 'auto', color: 'var(--mute-2)', fontFamily: 'var(--font-mono)', fontSize: 10 }}>
          {tenant}
        </span>
      </div>

      {mode === 'chooser' && (
        <>
          <div style={{ marginTop: 22 }}>
            <ProviderBtn kind="google" label="Continue with Google" meta="Workspace" onClick={() => goSSO('google')} />
            <ProviderBtn kind="microsoft" label="Continue with Microsoft" meta="Entra ID" onClick={() => goSSO('microsoft')} />
          </div>

          <div className="k-auth-or">or</div>

          <Btn onClick={() => setMode('email')} style={{ width: '100%', justifyContent: 'center', height: 40 }}>
            Sign in with email
          </Btn>
        </>
      )}

      {(mode === 'email' || mode === 'error' || mode === 'submitting') && (
        <form className="k-auth-form" onSubmit={submitEmail} style={{ marginTop: 22 }}>
          <Field label="Email">
            <Input value={email} onChange={setEmail} prefix="✉" />
          </Field>
          <Field label="Password" error={mode === 'error' ? errorMsg : undefined}>
            <Input
              value={password}
              onChange={setPassword}
              suffix={
                <button type="button"
                  onClick={() => onForgotPassword?.()}
                  style={{ border: 0, background: 'transparent', color: 'var(--accent)', fontSize: 11.5, cursor: 'pointer' }}>
                  Forgot
                </button>
              }
              error={mode === 'error'}
            />
          </Field>

          <Btn variant="primary"
               type="submit"
               loading={mode === 'submitting'}
               style={{ width: '100%', justifyContent: 'center', height: 40 }}>
            {mode === 'submitting' ? 'Signing in…' : 'Sign in'}
          </Btn>

          <div className="k-auth-row">
            <button type="button" onClick={() => setMode('chooser')}
                    style={{ background: 'transparent', border: 0, color: 'var(--mute)', cursor: 'pointer', padding: 0, fontSize: 12 }}>
              ← Use SSO instead
            </button>
            <a href="#contact-admin">Need an account?</a>
          </div>
        </form>
      )}

      <div className="k-auth-security">
        <span className="k-auth-security-dot"></span>
        <span>Protected by SSO · Cloudflare Access · audited on every action</span>
      </div>

      <div style={{ marginTop: 14, textAlign: 'center' }}>
        <button type="button"
                onClick={() => onAuthStart?.({ method: 'dev', _devLogin: true })}
                style={{ border: 0, background: 'transparent', color: 'var(--mute)',
                         fontSize: 11, cursor: 'pointer', fontFamily: 'var(--font-mono)' }}>
          Dev login · pick a role →
        </button>
      </div>
    </div>
  );
};


/* ============================================================
   SESSION BOOTSTRAP — architecture §4.3 states
   checking_access → creating_user → creating_workspaces → loading_modules → ready
   ============================================================ */
const BOOTSTRAP_STEPS = [
  ['checking_access',     'Checking your access…',          'Validating session with identity provider.'],
  ['creating_user',       'Creating your user record…',     'First-time sign-in · provisioning.'],
  ['creating_workspaces', 'Setting up your workspaces…',    'Designer · Inventory · or CEO workspaces per role.'],
  ['loading_modules',     'Loading your modules…',          'Role-filtered surfaces being mounted.'],
  ['ready',               'Welcome.',                       'Opening home.'],
];

const SessionBootstrap = ({ method, tenant, onReady, onError }) => {
  const [stepIdx, setStepIdx] = useState(0);

  useEffect(() => {
    if (stepIdx >= BOOTSTRAP_STEPS.length - 1) {
      const t = setTimeout(() => onReady?.(), 700);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setStepIdx(i => i + 1), [800, 600, 700, 600, 0][stepIdx] || 600);
    return () => clearTimeout(t);
  }, [stepIdx, onReady]);

  const providerLabel = {
    google: 'Signed in via Google Workspace',
    microsoft: 'Signed in via Microsoft Entra ID',
    password: 'Signed in via email and password',
    sso: 'Signed in via SSO',
  }[method] || 'Signed in';

  const current = BOOTSTRAP_STEPS[stepIdx];

  return (
    <div className="k-auth-card is-wide">
      <div className="k-auth-stage-state">
        <div className="k-auth-stage-mark">K</div>
        <Chip variant="info" dot>{providerLabel}</Chip>
        <div className="k-auth-state-text">{current[1]}</div>
        <div className="k-auth-state-sub">{current[2]}</div>

        <div className="k-auth-steps">
          {BOOTSTRAP_STEPS.map(([key, label], i) => {
            const state = i < stepIdx ? 'done' : i === stepIdx ? 'now' : 'pending';
            return (
              <div key={key} className={`k-auth-step is-${state}`}>
                <span className="k-auth-step-dot" />
                <span>{label.replace(/…$/, '')}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};


/* ============================================================
   ACCESS PENDING — admin needs to assign role
   ============================================================ */
const AccessPending = ({ email, tenant, onSignOut, onContactAdmin }) => (
  <div className="k-auth-card k-auth-state-pending">
    <div className="k-auth-stage-state">
      <div className="k-auth-stage-mark">!</div>
      <div className="k-auth-state-text">Access pending admin approval</div>
      <div className="k-auth-state-sub">
        Your identity is verified, but you haven’t been assigned a role in <b>{tenant}</b> yet.
        An administrator must complete provisioning before you can enter the workspace.
      </div>

      <div className="k-auth-steps">
        <div className="k-auth-step is-done">
          <span className="k-auth-step-dot" />
          <span>Identity verified · {email}</span>
        </div>
        <div className="k-auth-step is-now">
          <span className="k-auth-step-dot" />
          <span>Awaiting admin role assignment</span>
        </div>
        <div className="k-auth-step">
          <span className="k-auth-step-dot" />
          <span>Workspaces created and modules loaded</span>
        </div>
      </div>

      <div className="k-auth-actions">
        <Btn onClick={onContactAdmin}>Contact admin</Btn>
        <Btn variant="ghost" onClick={onSignOut}>Sign out</Btn>
      </div>
    </div>
  </div>
);


/* ============================================================
   ACCESS DENIED — RBAC denial
   ============================================================ */
const AccessDenied = ({ email, tenant, reason, onSignOut, onRetry }) => (
  <div className="k-auth-card k-auth-state-error">
    <div className="k-auth-stage-state">
      <div className="k-auth-stage-mark">✕</div>
      <div className="k-auth-state-text">Access denied</div>
      <div className="k-auth-state-sub">
        {reason || `Your account does not have access to ${tenant}. If this is unexpected, contact an administrator.`}
      </div>

      <div className="k-auth-steps">
        <div className="k-auth-step is-done">
          <span className="k-auth-step-dot" />
          <span>Identity verified · {email || 'unknown'}</span>
        </div>
        <div className="k-auth-step">
          <span className="k-auth-step-dot" style={{ background: 'var(--danger-soft)', color: 'var(--danger)' }} />
          <span style={{ color: 'var(--danger)' }}>Tenant denied access</span>
        </div>
      </div>

      <div className="k-auth-actions">
        <Btn variant="ghost" onClick={onRetry}>Try a different account</Btn>
        <Btn variant="primary" onClick={onSignOut}>Sign out</Btn>
      </div>
    </div>
  </div>
);


/* ============================================================
   IDP ERROR — provider returned an error
   ============================================================ */
const IdpError = ({ provider, errorCode, onRetry, onSignOut }) => (
  <div className="k-auth-card k-auth-state-error">
    <div className="k-auth-stage-state">
      <div className="k-auth-stage-mark">!</div>
      <div className="k-auth-state-text">Identity provider error</div>
      <div className="k-auth-state-sub">
        We couldn’t verify your session with {provider || 'the identity provider'}.
        Your data is unchanged. Try again or sign out and start over.
      </div>
      {errorCode && (
        <div style={{ marginTop: 14, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mute)' }}>
          err.idp · {errorCode}
        </div>
      )}
      <div className="k-auth-actions">
        <Btn variant="primary" onClick={onRetry}>Retry</Btn>
        <Btn variant="ghost" onClick={onSignOut}>Sign out</Btn>
      </div>
    </div>
  </div>
);


/* ============================================================
   DEV LOGIN — role switcher (architecture §4.3 /dev-login)
   Local-only · disabled in production.
   ============================================================ */
const ROLES = [
  { id: 'ceo',           name: 'CEO',                   mod: 'home',      modules: 'HOME · ORBIT · VAULT · PRICE · KRAFT · APPROVALS · MONITOR (read) · ADMIN (read) · WIKI',
    persona: 'Rohan Patel',     focus: 'Cross-company dashboards · approvals · trust layer' },
  { id: 'hom',           name: 'Head of Merchandising', mod: 'orbit',     modules: 'HOME · ORBIT · VAULT (edit) · KRAFT (edit) · WIKI',
    persona: 'Priya Shah',      focus: 'Trend review · brief drafting · KRAFT brief intake · signal triage' },
  { id: 'designer',      name: 'Designer',              mod: 'kraft',     modules: 'HOME · KRAFT · WIKI',
    persona: 'Vikram Sharma',   focus: 'Private KRAFT workspace · brief-to-CAD lineage' },
  { id: 'inventory',     name: 'Inventory Manager',     mod: 'vault',     modules: 'HOME · VAULT · APPROVALS · WIKI',
    persona: 'Asha Iyer',       focus: 'Deadstock queue · co-sign on transfers and reprices' },
  { id: 'pricing',       name: 'Pricing Lead',          mod: 'price',     modules: 'HOME · PRICE · APPROVALS · WIKI',
    persona: 'Karan Mehta',     focus: 'Quotes · margin · rate updates · ceiling approvals' },
  { id: 'admin',         name: 'Platform Admin',        mod: 'admin',     modules: 'HOME · ADMIN · CONNECT · MONITOR · WIKI',
    persona: 'Neha Bose',       focus: 'SSO · users · roles · audit · feature flags' },
  { id: 'implementation',name: 'Implementation Eng',    mod: 'monitor',   modules: 'HOME · MONITOR · CONNECT · ADMIN (edit)',
    persona: 'Sami Khan',       focus: 'Connectors · run telemetry · curator queue · heartbeats' },
];

const DevLoginPage = ({ tenant = 'Acme Jewels', onPickRole }) => (
  <div className="k-dev-login">
    <div className="k-dev-login-card">
      <header className="k-auth-brand">
        <div className="k-auth-brand-mark">K</div>
        <div className="k-auth-brand-name">KOVA</div>
      </header>

      <div className="k-dev-login-head">
        <div>
          <h1 className="k-auth-title">Pick a persona</h1>
          <p className="k-auth-sub">
            Dev login bypasses SSO and signs you in as the selected role. The rail, available modules,
            and approval power all change per role. Local only · disabled in production.
          </p>
        </div>
        <Chip variant="mute">tenant · {tenant.toLowerCase().replace(/\s/g, '')}.kova.app</Chip>
      </div>

      <div className="k-dev-login-warning">
        <span>!</span>
        <span>This route should be off in production. Architecture v7 §4.3.</span>
      </div>

      <div className="k-dev-login-grid">
        {ROLES.map(r => (
          <button key={r.id}
                  type="button"
                  className="k-role-tile"
                  style={{ '--m-mod': `var(--m-${r.mod})` }}
                  onClick={() => onPickRole?.(r)}>
            <span className="k-role-tile-mark">{r.id}</span>
            <span className="k-role-tile-name">{r.name}</span>
            <span className="t-meta" style={{ color: 'var(--ink-2)' }}>{r.persona}</span>
            <span className="k-role-tile-modules">{r.focus}</span>
            <span className="k-role-tile-modules" style={{ marginTop: 6, fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--mute-2)' }}>
              {r.modules}
            </span>
          </button>
        ))}
      </div>
    </div>
  </div>
);


/* ============================================================
   SIGNED OUT — explicit post-logout page (architecture §4.3 /sign-out)
   ============================================================ */
const SignedOutPage = ({ user = 'Rohan', tenant = 'Acme Jewels', method, onSignInAgain }) => {
  const providerLabel = {
    google: 'Google Workspace',
    microsoft: 'Microsoft Entra ID',
    password: 'email & password',
    sso: 'SSO',
  }[method] || 'SSO';

  return (
    <div className="k-auth-card">
      <header className="k-auth-brand">
        <div className="k-auth-brand-mark">K</div>
        <div className="k-auth-brand-name">KOVA</div>
      </header>

      <div className="k-auth-stage-state">
        <div className="k-auth-stage-mark" style={{ background: 'var(--success-soft)', color: 'var(--success)' }}>✓</div>
        <div className="k-auth-state-text">You’ve been signed out.</div>
        <div className="k-auth-state-sub">
          Your session for <b>{tenant}</b> has ended and your access token has been revoked.
          Any in-flight workflow remains queued in CONNECT and is unaffected.
        </div>

        <div className="k-auth-steps">
          <div className="k-auth-step is-done">
            <span className="k-auth-step-dot" />
            <span>Identity verified · {user.toLowerCase()}@acme.com</span>
          </div>
          <div className="k-auth-step is-done">
            <span className="k-auth-step-dot" />
            <span>Signed in via {providerLabel}</span>
          </div>
          <div className="k-auth-step is-done">
            <span className="k-auth-step-dot" />
            <span>Session ended · cookies cleared</span>
          </div>
        </div>

        <div className="k-auth-actions">
          <Btn variant="primary" onClick={onSignInAgain} kbd="⏎">Sign in again</Btn>
        </div>
      </div>

      <div className="k-auth-security">
        <span className="k-auth-security-dot"></span>
        <span>Sign-out is audited · architecture v7 §11 admin telemetry</span>
      </div>
    </div>
  );
};


/* ============================================================
   AUTH SHELL — wraps any auth view with the same surrounding chrome
   ============================================================ */
const AuthShell = ({ children, hint }) => (
  <div className="k-auth">
    <div className="k-auth-stage">{children}</div>
    <footer className="k-auth-foot">
      <div className="k-auth-foot-links">
        <a href="#privacy">Privacy</a>
        <a href="#terms">Terms</a>
        <a href="#status">Status</a>
        <a href="#contact-admin">Contact admin</a>
      </div>
      <div className="k-auth-foot-key">
        <span>{hint || 'KOVA · architecture v7'}</span>
        <Kbd>?</Kbd>
        <span>shortcuts</span>
      </div>
    </footer>
  </div>
);

/* ============================================================
   EXPORT
   ============================================================ */
Object.assign(window.K, {
  ProviderBtn, LoginPage, SessionBootstrap, AccessPending, AccessDenied, IdpError, SignedOutPage, AuthShell,
  DevLoginPage, ROLES,
});
