// React hook to make components reactive to store changes.
function useStore() {
  const [, setT] = React.useState(0);
  React.useEffect(() => window.store.subscribe(() => setT(t => t + 1)), []);
  return window.store;
}
window.useStore = useStore;

// Sign-in modal — Google OAuth + Email magic link via Supabase (fsnCloud).
// No passwords. No Apple (not configured).
const { useState: useStateAU } = React;

function AuthModal({ open, onClose }) {
  const [email, setEmail]   = useStateAU('');
  const [loading, setLoad]  = useStateAU(false);
  const [sent, setSent]     = useStateAU(false);
  const [err, setErr]       = useStateAU(null);

  if (!open) return null;

  const cloudReady = window.fsnCloud?.enabled;

  const googleSignIn = async () => {
    if (!cloudReady) return;
    setLoad(true); setErr(null);
    try {
      await window.fsnCloud.signInWithGoogle();
      // Page will redirect — no need to call onClose
    } catch (e) { setErr(e.message); setLoad(false); }
  };

  const sendMagicLink = async () => {
    if (!email.trim()) { setErr('Enter your email address.'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) { setErr('Invalid email address.'); return; }
    setLoad(true); setErr(null);
    try {
      await window.fsnCloud.signInWithMagicLink(email.trim());
      setSent(true);
    } catch (e) { setErr(e.message); }
    setLoad(false);
  };

  const reset = () => { setSent(false); setEmail(''); setErr(null); };

  return (
    <div className="loc-card-overlay" onClick={onClose}>
      <div className="loc-card auth-card" onClick={e => e.stopPropagation()}>
        <div className="loc-card-head">
          <div>
            <div className="loc-kicker">WELCOME TO FULL SEND NOMAD</div>
            <h2 className="loc-name">Sign in</h2>
            <div className="auth-sub">
              Save playbooks, favorites &amp; get full AI features — including Claude-powered deep dives, the Concierge, and city stats.
            </div>
          </div>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>

        <div className="auth-body">
          {sent ? (
            <div className="auth-sent">
              <div className="auth-sent-icon">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
                  <path d="M3 8l9 6 9-6M3 8v10a1 1 0 001 1h16a1 1 0 001-1V8M3 8l9 6"/>
                </svg>
              </div>
              <div className="auth-sent-title">Check your email</div>
              <div className="auth-sent-sub">
                We sent a magic link to <strong>{email}</strong>. Click it to sign in — no password needed.
              </div>
              <button className="reset-btn" style={{ marginTop: 16 }} onClick={reset}>Use a different email</button>
            </div>
          ) : (
            <>
              {!cloudReady ? (
                <div className="auth-err">Cloud auth is not configured. Contact the site admin.</div>
              ) : (
                <>
                  <button className="auth-oauth google" onClick={googleSignIn} disabled={loading}>
                    <svg width="16" height="16" viewBox="0 0 48 48">
                      <path fill="#4285f4" d="M44.5 20H24v8.5h11.8C34.7 33.5 30 37 24 37c-7.2 0-13-5.8-13-13s5.8-13 13-13c3.3 0 6.3 1.2 8.6 3.2l6-6C34.4 4.5 29.5 2.5 24 2.5 12.5 2.5 3 12 3 24s9.5 21.5 21 21.5c11.5 0 21-8 21-21.5 0-1.4-.1-2.7-.5-4z"/>
                    </svg>
                    {loading ? 'Redirecting…' : 'Continue with Google'}
                  </button>

                  <div className="auth-divider"><span>or use a magic link</span></div>

                  <input
                    className="settings-input"
                    type="email"
                    placeholder="your@email.com"
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && !loading && sendMagicLink()}
                    disabled={loading}
                    autoFocus
                  />
                  <div className="auth-magic-hint">No password — we'll email you a one-click sign-in link.</div>

                  {err && <div className="auth-err">{err}</div>}

                  <button className="ask-btn auth-submit" onClick={sendMagicLink} disabled={loading || !email.trim()}>
                    {loading ? 'Sending…' : 'Send magic link →'}
                  </button>
                </>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// Reusable inline sign-in prompt for AI feature gates.
// Shows within Deep Dive, Concierge, Add City panels when user is not signed in.
function SignInForAI({ feature, compact }) {
  const [emailMode, setEmailMode] = React.useState(false);
  const [email, setEmail]         = React.useState('');
  const [sent, setSent]           = React.useState(false);
  const [loading, setLoading]     = React.useState(false);
  const [err, setErr]             = React.useState(null);

  const googleSignIn = async () => {
    try { await window.fsnCloud.signInWithGoogle(); }
    catch (e) { setErr(e.message); }
  };

  const sendLink = async () => {
    if (!email.trim()) return;
    setLoading(true); setErr(null);
    try {
      await window.fsnCloud.signInWithMagicLink(email.trim());
      setSent(true);
    } catch (e) { setErr(e.message); }
    setLoading(false);
  };

  const openModal = () => window.dispatchEvent(new CustomEvent('expat:require-signin'));

  if (!window.fsnCloud?.enabled) {
    return (
      <div className="sia-wrap">
        <div className="sia-title">Sign in to use AI features</div>
        <div className="sia-sub">Cloud auth is not configured.</div>
      </div>
    );
  }

  if (sent) {
    return (
      <div className="sia-wrap">
        <div className="sia-check">✓</div>
        <div className="sia-title">Check your email</div>
        <div className="sia-sub">Magic link sent to <strong>{email}</strong>. Click it to sign in, then come back.</div>
      </div>
    );
  }

  return (
    <div className="sia-wrap">
      <div className="sia-lock">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
          <rect x="3" y="11" width="18" height="11" rx="2"/>
          <path d="M7 11V7a5 5 0 0110 0v4"/>
        </svg>
      </div>
      <div className="sia-title">Sign in to use {feature || 'AI features'}</div>
      <div className="sia-sub">
        AI features are free for signed-in users — Deep Dive, Concierge, Ask anything, Add city stats.
        Sign in once and they work everywhere.
      </div>
      {!emailMode ? (
        <div className="sia-btns">
          <button className="auth-oauth google sia-google" onClick={googleSignIn}>
            <svg width="14" height="14" viewBox="0 0 48 48">
              <path fill="#4285f4" d="M44.5 20H24v8.5h11.8C34.7 33.5 30 37 24 37c-7.2 0-13-5.8-13-13s5.8-13 13-13c3.3 0 6.3 1.2 8.6 3.2l6-6C34.4 4.5 29.5 2.5 24 2.5 12.5 2.5 3 12 3 24s9.5 21.5 21 21.5c11.5 0 21-8 21-21.5 0-1.4-.1-2.7-.5-4z"/>
            </svg>
            Continue with Google
          </button>
          <button className="sia-magic-btn" onClick={() => setEmailMode(true)}>Use email magic link →</button>
        </div>
      ) : (
        <div className="sia-email-form">
          <input
            className="settings-input"
            type="email"
            placeholder="your@email.com"
            value={email}
            onChange={e => setEmail(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && !loading && sendLink()}
            autoFocus
          />
          {err && <div className="auth-err" style={{ marginTop: 6 }}>{err}</div>}
          <div className="sia-email-row">
            <button className="ask-btn" onClick={sendLink} disabled={loading || !email.trim()}>
              {loading ? 'Sending…' : 'Send magic link →'}
            </button>
            <button className="reset-btn" onClick={() => setEmailMode(false)}>Back</button>
          </div>
        </div>
      )}
    </div>
  );
}

window.AuthModal   = AuthModal;
window.SignInForAI = SignInForAI;
