// Auth — email + magic link, mobile-first web app

function AuthLogo({ size = 68 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: size * 0.28,
      background: C.coral,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 8px 22px rgba(255,107,91,0.35)',
      color: '#fff',
    }}>
      <svg width={size*0.52} height={size*0.52} viewBox="0 0 24 24" fill="none">
        <path d="M12 2.5c2 3.5 0 5.5-1 7 1-0.5 2.5-0.5 3.5.5 2 2 3.5 4.5 3.5 7.5a6 6 0 1 1-12 0c0-2 .8-3.5 2-4.5.2 1.5.7 2.3 1.5 2.5-.5-2-.5-5 2.5-13z"
          fill="#fff"/>
      </svg>
    </div>
  );
}

function AuthShell({ children }) {
  return (
    <div style={{
      minHeight: '100%', background: C.cream,
      display: 'flex', flexDirection: 'column',
      padding: 'calc(env(safe-area-inset-top, 12px) + 24px) 24px calc(env(safe-area-inset-bottom, 0px) + 20px)',
    }}>
      {children}
    </div>
  );
}

// ─── Screen 1: Email entry ───
function AuthSignIn({ onSent, mode = 'signin', busy = false, onToggleMode = () => {} }) {
  const isSignup = mode === 'signup';
  const [email, setEmail] = React.useState('');
  const [remember, setRemember] = React.useState(true);
  const [error, setError] = React.useState(null);
  const canContinue = email.includes('@') && email.includes('.') && !busy;
  const submit = async () => {
    setError(null);
    try { await onSent(email.trim().toLowerCase(), remember); }
    catch (e) { setError(e.message || 'something went wrong'); }
  };

  return (
    <AuthShell>
      <div style={{ paddingTop: 40 }}>
        <AuthLogo/>
        <h1 style={{
          margin: '28px 0 8px',
          fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
          fontSize: 44, lineHeight: 1.02, letterSpacing: -0.8,
          color: C.navy, fontWeight: 400,
        }}>
          {isSignup ? "let's plan something" : 'welcome back'}
        </h1>
        <div style={{
          fontFamily: '"DM Sans",system-ui', fontSize: 15, color: C.inkMuted,
          lineHeight: 1.45, letterSpacing: -0.1, maxWidth: 300,
        }}>
          {isSignup
            ? 'drop your email — we\'ll send a magic link to get you started. no passwords, ever.'
            : 'enter your email — we\'ll send a magic link. no passwords, ever.'}
        </div>
      </div>

      <div style={{ marginTop: 28 }}>
        <label style={{
          fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700,
          color: C.inkMuted, letterSpacing: 1, textTransform: 'uppercase',
          display: 'block', padding: '0 4px 8px',
        }}>Email</label>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: C.white, borderRadius: 14,
          padding: '14px 14px', boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.04)',
        }}>
          <svg width="18" height="18" viewBox="0 0 20 20" fill="none" style={{ color: C.inkMuted, flexShrink: 0 }}>
            <rect x="2" y="4.5" width="16" height="11" rx="2" stroke="currentColor" strokeWidth="1.6"/>
            <path d="M2.5 5.5L10 11l7.5-5.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinejoin="round"/>
          </svg>
          <input
            value={email}
            onChange={e => setEmail(e.target.value)}
            placeholder="you@gmail.com"
            type="email"
            autoComplete="email"
            style={{
              flex: 1, border: 'none', background: 'transparent', outline: 'none',
              fontFamily: '"DM Sans",system-ui', fontSize: 16, color: C.navy,
              minWidth: 0, padding: 0,
            }}/>
        </div>

        {/* Remember me */}
        <div style={{
          marginTop: 14,
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '0 4px',
        }}>
          <button onClick={() => setRemember(!remember)} style={{
            width: 22, height: 22, borderRadius: 6,
            border: `1.8px solid ${remember ? C.coral : 'rgba(30,42,74,0.25)'}`,
            background: remember ? C.coral : 'transparent',
            cursor: 'pointer', padding: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            {remember && (
              <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                <path d="M3 6.8l2.4 2.4L10.2 4" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )}
          </button>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 14, fontWeight: 600, color: C.navy }}>
              Remember me
            </div>
            <div style={{ fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.inkMuted, marginTop: 1 }}>
              stay signed in on this device for 30 days
            </div>
          </div>
        </div>

        <button
          disabled={!canContinue}
          onClick={submit}
          style={{
            width: '100%', marginTop: 22, height: 54, borderRadius: 999,
            border: 'none',
            background: canContinue
              ? `linear-gradient(180deg, ${C.coral}, ${C.coralDeep})`
              : 'rgba(30,42,74,0.1)',
            color: canContinue ? '#fff' : C.inkMuted,
            fontFamily: '"DM Sans",system-ui',
            fontWeight: 700, fontSize: 16, letterSpacing: -0.1,
            cursor: canContinue ? 'pointer' : 'default',
            boxShadow: canContinue ? '0 6px 18px rgba(255,107,91,0.4)' : 'none',
            transition: 'all 180ms ease',
          }}>
          {busy ? 'Sending…' : (isSignup ? 'Create my account' : 'Send magic link')}
        </button>
        {error && (
          <div style={{
            marginTop: 10, fontFamily: '"DM Sans",system-ui',
            fontSize: 12.5, color: C.coralDeep, textAlign: 'center',
          }}>{error}</div>
        )}

        <div style={{
          marginTop: 22, textAlign: 'center',
          fontFamily: '"DM Sans",system-ui', fontSize: 13, color: C.inkMuted,
        }}>
          {isSignup ? "already have an account? " : "new here? "}
          <button onClick={onToggleMode} style={{
            background: 'transparent', border: 'none', padding: 0,
            color: C.navy, fontWeight: 600, fontFamily: 'inherit', fontSize: 13,
            textDecoration: 'underline', textUnderlineOffset: 3, cursor: 'pointer',
          }}>
            {isSignup ? 'sign in' : 'create an account'}
          </button>
        </div>

        {/* Legal note on signup */}
        {isSignup && (
          <div style={{
            marginTop: 14, textAlign: 'center',
            fontFamily: '"DM Sans",system-ui', fontSize: 11.5, color: C.inkMuted,
            lineHeight: 1.55, padding: '0 20px',
          }}>
            by creating an account, you agree to our{' '}
            <span style={{ color: C.navy, textDecoration: 'underline', textUnderlineOffset: 2 }}>terms</span>
            {' '}and{' '}
            <span style={{ color: C.navy, textDecoration: 'underline', textUnderlineOffset: 2 }}>privacy policy</span>.
          </div>
        )}
      </div>

      <div style={{ flex: 1 }}/>

      {/* Install PWA hint */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        background: 'rgba(138,168,150,0.14)',
        padding: '10px 14px', borderRadius: 14,
        fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.sage,
        fontWeight: 600, letterSpacing: -0.05, lineHeight: 1.4,
      }}>
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" style={{ flexShrink: 0 }}>
          <rect x="3" y="2" width="12" height="14" rx="2.5" stroke={C.sage} strokeWidth="1.5"/>
          <circle cx="9" cy="13" r="1" fill={C.sage}/>
        </svg>
        <div>Tip: tap <b>Share → Add to Home Screen</b> to use Shephrd like an app.</div>
      </div>
    </AuthShell>
  );
}

// ─── Screen 2: Magic link sent ───
function AuthLinkSent({ email, devLink, onResend, onBack }) {
  return (
    <AuthShell>
      <button onClick={onBack} style={{
        background: 'transparent', border: 'none', padding: 0,
        display: 'flex', alignItems: 'center', gap: 6,
        color: C.inkMuted, cursor: 'pointer',
        fontFamily: '"DM Sans",system-ui', fontSize: 14, fontWeight: 500,
      }}>
        <svg width="12" height="12" viewBox="0 0 12 12"><path d="M7 2L3 6l4 4" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
        Back
      </button>

      <div style={{ paddingTop: 60, textAlign: 'center' }}>
        {/* envelope with sparkle */}
        <div style={{
          width: 88, height: 88, borderRadius: 28,
          background: C.coralSoft,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative',
        }}>
          <svg width="46" height="46" viewBox="0 0 46 46" fill="none">
            <rect x="6" y="11" width="34" height="24" rx="3" fill="#fff" stroke={C.coral} strokeWidth="2"/>
            <path d="M7 12.5L23 24l16-11.5" stroke={C.coral} strokeWidth="2" fill="none" strokeLinejoin="round"/>
            <path d="M35 7l1.5 3 3 1.5-3 1.5L35 16l-1.5-3-3-1.5 3-1.5z" fill={C.coral}/>
          </svg>
        </div>

        <h1 style={{
          margin: '26px 0 10px',
          fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
          fontSize: 38, lineHeight: 1.05, letterSpacing: -0.6,
          color: C.navy, fontWeight: 400,
        }}>check your inbox</h1>

        <div style={{
          fontFamily: '"DM Sans",system-ui', fontSize: 15, color: C.inkMuted,
          lineHeight: 1.5, letterSpacing: -0.1, maxWidth: 300, margin: '0 auto',
        }}>
          we sent a magic link to<br/>
          <b style={{ color: C.navy, fontWeight: 600 }}>{email || 'you@gmail.com'}</b>
          <br/>tap it from your phone to sign in.
        </div>
      </div>

      <div style={{ marginTop: 36, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {devLink ? (
          <a href={devLink} style={{
            height: 54, borderRadius: 999, border: 'none', textDecoration: 'none',
            background: `linear-gradient(180deg, ${C.coral}, ${C.coralDeep})`,
            color: '#fff', fontFamily: '"DM Sans",system-ui',
            fontWeight: 700, fontSize: 16, letterSpacing: -0.1,
            cursor: 'pointer', boxShadow: '0 6px 18px rgba(255,107,91,0.4)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>Use dev magic link</a>
        ) : null}
        <button onClick={onResend} style={{
          height: 46, borderRadius: 999,
          border: `1.5px solid ${C.hairline}`,
          background: 'transparent', color: C.navy,
          fontFamily: '"DM Sans",system-ui',
          fontWeight: 600, fontSize: 14,
          cursor: 'pointer',
        }}>Resend link</button>
      </div>
      {devLink && (
        <div style={{
          marginTop: 10, fontFamily: '"DM Sans",system-ui',
          fontSize: 11.5, color: C.inkMuted, textAlign: 'center',
        }}>dev only — a real deployment will email this link</div>
      )}

      <div style={{ flex: 1 }}/>

      <div style={{
        fontFamily: '"DM Sans",system-ui', fontSize: 12, color: C.inkMuted,
        textAlign: 'center', lineHeight: 1.5,
      }}>
        didn't get it? check spam, or try a different email.
      </div>
    </AuthShell>
  );
}

Object.assign(window, { AuthSignIn, AuthLinkSent, AuthLogo });
