/* ============================================================
   TRELLIS — onboarding: Welcome → Google SSO → Ready
   Exports: AuthFlow, TrellisWordmark
   Backend: window.EHCW_AUTH (set by firebase-backend.js)
            Falls back to demo mode if EHCW_AUTH is null.
   ============================================================ */

function TrellisWordmark({ size = 44 }) {
  const fs = Math.max(14, size * 0.5);
  return (
    <span style={{
      fontFamily: "'Unbounded', var(--font-display)", fontWeight: 700,
      fontSize: fs, letterSpacing: '-0.025em', lineHeight: 1.15,
      whiteSpace: 'nowrap', display: 'inline-block', userSelect: 'none'
    }}>
      <span style={{
        background: 'linear-gradient(110deg, var(--accent), oklch(0.78 0.15 88))',
        WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent'
      }}>Un</span><span>stoppables</span><span style={{ color: 'var(--gold-deep)' }}>.</span>
    </span>
  );
}

function AuthShell({ children, step }) {
  return (
    <div style={{ position: 'relative', zIndex: 1, minHeight: '100vh', display: 'grid', placeItems: 'center', padding: '32px 20px' }}>
      <div style={{ width: '100%', maxWidth: 460, display: 'flex', flexDirection: 'column', gap: 22 }}>
        <div className="glass-strong" style={{
          borderRadius: 'var(--radius-xl)', padding: 'clamp(28px, 5vw, 48px)',
          boxShadow: 'var(--shadow-pop)', animation: 'trellis-pop .5s var(--ease-spring)'
        }}>
          {children}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 8 }}>
          {[0, 1, 2].map(i => (
            <span key={i} style={{
              width: i === step ? 26 : 8, height: 8, borderRadius: 99,
              background: i === step ? 'var(--accent)' : 'var(--hairline-strong)',
              transition: 'all .4s var(--ease-spring)'
            }}></span>
          ))}
        </div>
        <div style={{ opacity: 0.85 }}><PoweredBy compact={true} /></div>
        <div className="t-faint" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 10, fontSize: 11.5, marginTop: -8 }}>
          <a href="privacy.html" target="_blank" rel="noopener" style={{ color: 'inherit', textDecoration: 'none', fontWeight: 600 }}>Privacy Policy</a>
          <span style={{ opacity: 0.5 }}>·</span>
          <a href="terms.html" target="_blank" rel="noopener" style={{ color: 'inherit', textDecoration: 'none', fontWeight: 600 }}>Terms of Use</a>
        </div>
      </div>
    </div>
  );
}

function AuthFlow({ onComplete }) {
  const [step, setStep] = React.useState(0);
  const [authing, setAuthing] = React.useState(false);
  const [authError, setAuthError] = React.useState(null);
  const [authUser, setAuthUser] = React.useState(null);

  const startSSO = async () => {
    setAuthing(true);
    setAuthError(null);
    try {
      if (window.EHCW_AUTH) {
        // Real Firebase Auth — Google OAuth popup, @ehcw.ca enforced in firebase-backend.js
        const u = await window.EHCW_AUTH.signIn();
        setAuthUser(u);
        setStep(2);
      } else {
        // Demo mode — no Firebase config present
        await new Promise(r => setTimeout(r, 1400));
        setAuthUser({ displayName: 'Demo User', role: 'admin', email: 'demo@ehcw.ca' });
        setStep(2);
      }
    } catch (e) {
      // User cancelled the Google popup: code = 'auth/popup-closed-by-user'
      if (e.code !== 'auth/popup-closed-by-user') {
        setAuthError(e.message || 'Sign-in failed. Please try again.');
      }
    } finally {
      setAuthing(false);
    }
  };

  const firstName = authUser
    ? authUser.displayName.split(' ')[0]
    : 'there';
  const roleLabel = authUser
    ? (authUser.role === 'superadmin' ? 'Super Admin' : authUser.role === 'admin' ? 'Admin' : authUser.role === 'viewer' ? 'Viewer' : 'Caseworker')
    : 'Caseworker';

  if (step === 0) return (
    <AuthShell step={0}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 26, alignItems: 'flex-start' }}>
        <EhcwLogo height={34} />
        <TrellisWordmark size={52} />
        <div>
          <h1 style={{ fontSize: 'clamp(24px, 4vw, 30px)', fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.2 }}>
            A framework built<br />for the people who hold others up.
          </h1>
          <p className="t-soft" style={{ fontSize: 15.5, lineHeight: 1.65, marginTop: 14, marginBottom: 0 }}>
            Nourishing communities. Protecting survivors.<br />
            <strong>You are EHCW Unstoppables.</strong>
          </p>
        </div>
        <button onClick={() => setStep(1)} style={{
          width: '100%', padding: '15px 24px', borderRadius: 16, fontSize: 15.5, fontWeight: 700,
          fontFamily: 'var(--font-display)', background: 'var(--accent)', color: 'var(--accent-ink)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          boxShadow: '0 10px 26px -10px var(--accent)', transition: 'transform .2s var(--ease-spring)'
        }}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
          Get started <Icon name="chevR" size={17} stroke={2.4} />
        </button>
        <p className="t-faint" style={{ fontSize: 12.5, margin: 0, alignSelf: 'center' }}>
          Tip: the background follows your cursor. Go on, fidget.
        </p>
      </div>
    </AuthShell>
  );

  if (step === 1) return (
    <AuthShell step={1}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
        <TrellisWordmark size={36} />
        <div>
          <h2 style={{ fontSize: 23, fontWeight: 700, letterSpacing: '-0.02em' }}>Sign in with your EHCW account</h2>
          <p className="t-soft" style={{ fontSize: 14.5, lineHeight: 1.6, marginTop: 10, marginBottom: 0 }}>
            Use your <strong>@ehcw.ca</strong> Google account. No passwords, nothing new to remember.
          </p>
        </div>

        {authError && (
          <div style={{
            borderRadius: 13, padding: '11px 14px', background: 'oklch(0.95 0.04 35)',
            color: 'oklch(0.4 0.1 35)', fontSize: 13.5, fontWeight: 600,
            display: 'flex', alignItems: 'flex-start', gap: 8
          }}>
            <Icon name="alert" size={16} style={{ flexShrink: 0, marginTop: 1 }} />
            {authError}
          </div>
        )}

        <button onClick={startSSO} disabled={authing} style={{
          width: '100%', padding: '14px 20px', borderRadius: 16, fontSize: 15, fontWeight: 600,
          background: 'var(--glass-input)', border: '1px solid var(--hairline-strong)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
          backdropFilter: 'blur(10px)', opacity: authing ? 0.7 : 1, transition: 'all .2s', cursor: authing ? 'wait' : 'pointer'
        }}>
          <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true">
            <path fill="#4285F4" d="M23.5 12.27c0-.85-.08-1.66-.22-2.45H12v4.64h6.45a5.52 5.52 0 0 1-2.39 3.62v3h3.87c2.26-2.09 3.57-5.16 3.57-8.81z" />
            <path fill="#34A853" d="M12 24c3.24 0 5.95-1.08 7.93-2.91l-3.87-3c-1.07.72-2.45 1.15-4.06 1.15-3.12 0-5.77-2.11-6.71-4.95H1.29v3.1A12 12 0 0 0 12 24z" />
            <path fill="#FBBC05" d="M5.29 14.29A7.2 7.2 0 0 1 4.91 12c0-.8.14-1.57.38-2.29v-3.1H1.29a12 12 0 0 0 0 10.78l4-3.1z" />
            <path fill="#EA4335" d="M12 4.76c1.76 0 3.34.6 4.59 1.79l3.43-3.43A11.98 11.98 0 0 0 12 0 12 12 0 0 0 1.29 6.61l4 3.1C6.23 6.87 8.88 4.76 12 4.76z" />
          </svg>
          {authing ? 'Checking with Google…' : 'Continue with Google'}
        </button>

        {authing && (
          <div className="glass" style={{ borderRadius: 14, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, animation: 'trellis-rise .3s ease' }}>
            <Avatar initials="??" hue={290} size={30} />
            <div style={{ fontSize: 13.5 }}>
              <div style={{ fontWeight: 600 }}>Verifying…</div>
              <div className="t-faint mono" style={{ fontSize: 12 }}>@ehcw.ca</div>
            </div>
            <span className="t-faint" style={{ marginLeft: 'auto', fontSize: 12 }}>one moment</span>
          </div>
        )}

        <div style={{
          display: 'flex', alignItems: 'flex-start', gap: 9, padding: '11px 13px', borderRadius: 12,
          background: 'oklch(0.95 0.04 35 / 0.55)', border: '1px solid oklch(0.78 0.1 35 / 0.4)'
        }}>
          <Icon name="lock" size={14} style={{ color: 'var(--coral)', flexShrink: 0, marginTop: 1 }} />
          <span style={{ fontSize: 11.5, lineHeight: 1.55, color: 'oklch(0.42 0.1 35)' }}>
            <strong>Authorized EHCW personnel only.</strong> This is a restricted system. Unauthorized
            access or attempted access is prohibited, and is monitored, logged, and may be reported to
            the appropriate authorities.
          </span>
        </div>
        <button onClick={() => { setStep(0); setAuthError(null); }} className="t-faint" style={{ fontSize: 13, fontWeight: 600, alignSelf: 'center' }}>← Back</button>
      </div>
    </AuthShell>
  );

  // Step 2 — welcome screen with real user data (HARVEST is an array of cards)
  const harvestCount = (window.TRELLIS_DATA?.HARVEST || []).length;
  const visitsToday = (window.TRELLIS_DATA?.VISITS || []).filter(v => {
    if (!v.ts) return false;
    return v.ts.slice(0, 10) === new Date().toISOString().slice(0, 10);
  }).length;

  return (
    <AuthShell step={2}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 22, alignItems: 'center', textAlign: 'center' }}>
        <div style={{
          width: 72, height: 72, borderRadius: '50%', display: 'grid', placeItems: 'center',
          background: 'var(--leaf-soft)', color: 'var(--leaf)', animation: 'trellis-pop .6s var(--ease-spring)'
        }}>
          <Icon name="check" size={34} stroke={2.6} />
        </div>
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em' }}>
            Welcome, {firstName}.
          </h2>
          <p className="t-soft" style={{ fontSize: 14.5, lineHeight: 1.6, marginTop: 10, marginBottom: 0 }}>
            You're signed in as <strong>{roleLabel}</strong>.
            {harvestCount > 0
              ? ` Your Harvest board has ${harvestCount} card${harvestCount === 1 ? '' : 's'} waiting.`
              : ' Your inbox and calendar are being scanned for tasks.'}
          </p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, width: '100%' }}>
          {[
            [String(harvestCount || window.TRELLIS_DATA?.HARVEST?.cards?.length || '…'), 'cards picked'],
            [String(window.TRELLIS_DATA?.CLIENTS?.length || '…'), 'active clients'],
            [String(visitsToday || window.TRELLIS_DATA?.VISITS?.length || '…'), 'visits logged']
          ].map(([n, l]) => (
            <div key={l} className="glass" style={{ borderRadius: 14, padding: '12px 8px' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22 }}>{n}</div>
              <div className="t-faint" style={{ fontSize: 11.5, fontWeight: 600 }}>{l}</div>
            </div>
          ))}
        </div>
        <button onClick={onComplete} style={{
          width: '100%', padding: '15px 24px', borderRadius: 16, fontSize: 15.5, fontWeight: 700,
          fontFamily: 'var(--font-display)', background: 'var(--accent)', color: 'var(--accent-ink)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          boxShadow: '0 10px 26px -10px var(--accent)'
        }}>
          Enter Unstoppables <Icon name="chevR" size={17} stroke={2.4} />
        </button>
      </div>
    </AuthShell>
  );
}

Object.assign(window, { AuthFlow, TrellisWordmark });
