/* global React, ReactDOM */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "cyan",
  "intensity": 8,
  "showOrbs": true,
  "adminMode": false,
  "atmosphere": "neon",
  "surface": "glass",
  "geometry": "soft"
} /*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useState({ page: 'home', param: null });
  const [user, setUser] = useState(null);
  const [authReady, setAuthReady] = useState(false);
  const [authMode, setAuthMode] = useState(null);
  const [checkoutEA, setCheckoutEA] = useState(null);
  const [toast, setToast] = useState(null);

  // ── Read "page" query param on first load (used by NOWPayments redirect) ──
  useEffect(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      const pageParam = params.get('page');
      const validPages = ['home','marketplace','detail','auth','checkout','dashboard','agent','about','thank-you'];
      if (pageParam && validPages.includes(pageParam)) {
        setRoute({ page: pageParam, param: params.get('id') || null });
      }
    } catch (e) {}
  }, []);

  // ── Restore Firebase auth session on load ──────────────────────────
  useEffect(() => {
    if (!window.fb) {setAuthReady(true);return;}
    const unsubscribe = window.fb.auth.onAuthStateChanged(async (fbUser) => {
      if (fbUser) {
        const profile = await window.fb.getUserProfile(fbUser.uid).catch(() => null);
        setUser({
          uid: fbUser.uid,
          name: profile?.name || fbUser.displayName || fbUser.email.split('@')[0],
          email: fbUser.email,
          balance: profile?.balance || 0,
          plan: profile?.plan || 'starter',
          photoURL: fbUser.photoURL || null
        });
      } else {
        setUser(null);
      }
      setAuthReady(true);
    });
    return () => unsubscribe();
  }, []);

  // ── Accent color tweak ─────────────────────────────────────────────
  useEffect(() => {
    const colors = {
      cyan: '#00E5FF', magenta: '#FF2DAA', green: '#00FF94', violet: '#7C5CFF', amber: '#FFB800'
    };
    document.documentElement.style.setProperty('--cyan', colors[t.accent] || '#00E5FF');
  }, [t.accent]);

  // ── Admin mode: ON when signed in as an admin account, OR via the
  //    Tweaks toggle (which only exists inside the editor, never on the
  //    live deployed site — so public visitors can never edit).
  useEffect(() => {
    const effective = !!(window.fb?.isAdmin(user) || t.adminMode);
    window.__effAdminMode = effective;
    document.body.classList.toggle('eff-admin-mode', effective);
    // If admin turns off / signs out, force edit-mode off so the page locks
    if (!effective && window.__effEditMode) {
      window.__effEditMode = false;
      document.body.classList.remove('eff-edit-mode');
      window.dispatchEvent(new CustomEvent('eff_edit_mode_changed'));
    }
    window.dispatchEvent(new CustomEvent('eff_admin_changed'));
  }, [user, t.adminMode]);

  // ── Expressive feel tweaks: atmosphere / surface / geometry ────────
  useEffect(() => {
    const b = document.body;
    b.classList.remove('atm-neon', 'atm-stealth', 'atm-daybreak');
    b.classList.add(`atm-${t.atmosphere || 'neon'}`);
  }, [t.atmosphere]);

  useEffect(() => {
    const b = document.body;
    b.classList.remove('surf-glass', 'surf-solid', 'surf-wire');
    b.classList.add(`surf-${t.surface || 'glass'}`);
  }, [t.surface]);

  useEffect(() => {
    const radii = {
      sharp: { sm: '0px', md: '0px', lg: '2px', xl: '4px' },
      soft:  { sm: '6px', md: '10px', lg: '16px', xl: '24px' },
      round: { sm: '14px', md: '20px', lg: '28px', xl: '40px' },
    };
    const r = radii[t.geometry] || radii.soft;
    const root = document.documentElement.style;
    root.setProperty('--r-sm', r.sm);
    root.setProperty('--r-md', r.md);
    root.setProperty('--r-lg', r.lg);
    root.setProperty('--r-xl', r.xl);
  }, [t.geometry]);

  const go = (page, param = null) => {
    setRoute({ page, param });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const onBuy = (ea) => {
    if (!user) {setAuthMode('signup');return;}
    setCheckoutEA(ea);
    go('checkout');
  };

  const onCheckoutComplete = (ea) => {
    setToast({ text: `${ea.name} deployed successfully`, color: 'green' });
    setTimeout(() => setToast(null), 3000);
    go('dashboard');
  };

  const handleSignOut = async () => {
    try {
      await window.fb.signOut();
      setToast({ text: 'Signed out · See you again', color: 'cyan' });
      setTimeout(() => setToast(null), 2500);
      go('home');
    } catch (e) {}
  };

  let body;
  switch (route.page) {
    case 'home':body = <HomePage go={go} onBuy={onBuy} />;break;
    case 'marketplace':body = <MarketplacePage go={go} onBuy={onBuy} />;break;
    case 'detail':body = <DetailPage eaId={route.param} go={go} onBuy={onBuy} user={user} onAuth={setAuthMode} />;break;
    case 'auth':body = <AuthPage mode="login" go={go} onLogin={() => setAuthMode('login')} />;break;
    case 'checkout':body = <CheckoutPage ea={checkoutEA} go={go} onComplete={onCheckoutComplete} user={user} />;break;
    case 'thank-you':body = <ThankYouPage go={go} />;break;
    case 'dashboard':
      if (!user) {body = <AuthPage mode="login" go={go} onLogin={() => setAuthMode('login')} />;break;}
      body = <DashboardPage user={user} go={go} onBuy={onBuy} />;break;
    case 'agent':body = <AgentPage go={go} onBuy={onBuy} />;break;
    case 'about':body = <AboutPage go={go} />;break;
    default:body = <HomePage go={go} onBuy={onBuy} />;
  }

  return (
    <>
      {t.showOrbs && <NeonBackground />}
      {!t.showOrbs && <><div className="grid-bg" /><div className="scanlines" /></>}

      <div className="app" data-screen-label={route.page}>
        <Nav current={route.page} go={go} user={user} onAuth={setAuthMode} onSignOut={handleSignOut} />
        <main>{body}</main>
        <Footer go={go} />
      </div>

      <FloatingActions go={go}/>
      <FollowFAB/>
      <PageEditToggle/>
      <AdminIndicator/>

      {authMode &&
      <AuthModal
        mode={authMode}
        onClose={() => setAuthMode(null)}
        onSwitch={(m) => setAuthMode(m)}
        onSuccess={(name) => {
          setAuthMode(null);
          setToast({ text: `Welcome, ${name} · System online`, color: 'green' });
          setTimeout(() => setToast(null), 3000);
        }} />

      }

      {toast &&
      <div style={{
        position: 'fixed', bottom: 24, right: 24, zIndex: 200,
        background: 'rgba(5,6,13,0.95)', backdropFilter: 'blur(12px)',
        border: `1px solid var(--${toast.color})`,
        borderRadius: 8, padding: '14px 20px',
        boxShadow: `0 0 24px rgba(0,255,148,0.4)`,
        display: 'flex', gap: 12, alignItems: 'center',
        animation: 'toastIn 0.3s ease'
      }}>
          <span className="dot dot-pulse" style={{ color: `var(--${toast.color})` }} />
          <span className="font-mono text-sm">{toast.text}</span>
        </div>
      }

      <TweaksPanel title="Tweaks">
        <TweakSection label="Atmosphere" />
        <TweakRadio
          label="Mood"
          value={t.atmosphere}
          options={['neon', 'stealth', 'daybreak']}
          onChange={(v) => setTweak('atmosphere', v)} />
        <TweakSection label="Surface" />
        <TweakRadio
          label="Panel treatment"
          value={t.surface}
          options={['glass', 'solid', 'wire']}
          onChange={(v) => setTweak('surface', v)} />
        <TweakSection label="Geometry" />
        <TweakRadio
          label="Edges"
          value={t.geometry}
          options={['sharp', 'soft', 'round']}
          onChange={(v) => setTweak('geometry', v)} />

        <TweakSection label="Admin" />
        <TweakToggle label="Admin mode (edit + upload)" value={t.adminMode} onChange={(v) => setTweak('adminMode', v)} />
        <TweakSection label="Brand accent" />
        <TweakRadio
          label="Primary"
          value={t.accent}
          options={['cyan', 'magenta', 'green', 'violet', 'amber']}
          onChange={(v) => setTweak('accent', v)} />
        
        <TweakSection label="Motion" />
        <TweakToggle label="Show floating orbs" value={t.showOrbs} onChange={(v) => setTweak('showOrbs', v)} />
        <TweakSlider label="Motion intensity" value={t.intensity} min={1} max={10} step={1} onChange={(v) => setTweak('intensity', v)} />
      </TweaksPanel>
    </>);

}

/* ============================================================
   AdminIndicator — small badge so you can always tell whether
   editing/upload is currently unlocked (admin mode on).
   ============================================================ */
function AdminIndicator() {
  const [on, setOn] = useState(!!window.__effAdminMode);
  useEffect(() => {
    const h = () => setOn(!!window.__effAdminMode);
    window.addEventListener('eff_admin_changed', h);
    return () => window.removeEventListener('eff_admin_changed', h);
  }, []);
  if (!on) return null;
  return (
    <div style={{
      position: 'fixed', bottom: 24, left: 24, zIndex: 96,
      display: 'flex', alignItems: 'center', gap: 8,
      background: 'rgba(5,6,13,0.92)', backdropFilter: 'blur(8px)',
      border: '1px solid var(--green, #00FF94)', borderRadius: 999,
      padding: '8px 14px', boxShadow: '0 0 18px rgba(0,255,148,0.35)',
    }}>
      <span className="dot dot-pulse" style={{ color: 'var(--green, #00FF94)' }} />
      <span className="font-mono" style={{ fontSize: 11, letterSpacing: '0.12em', color: 'var(--green, #00FF94)' }}>
        ADMIN MODE · EDITING UNLOCKED
      </span>
    </div>
  );
}

/* ============================================================
   AuthModal — Firebase auth (sign-in / sign-up / Google / reset)
   ============================================================ */
function AuthModal({ mode, onClose, onSwitch, onSuccess }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [error, setError] = useState('');
  const [info, setInfo] = useState('');
  const [loading, setLoading] = useState(false);
  const [resetting, setResetting] = useState(false);

  async function submit(e) {
    e.preventDefault();
    setError('');setInfo('');setLoading(true);
    try {
      const fbUser = mode === 'signup' ?
      await window.fb.signUp(email, password, name || email.split('@')[0]) :
      await window.fb.signIn(email, password);
      onSuccess(fbUser.displayName || name || email.split('@')[0]);
    } catch (err) {
      setError(window.fb.errorMessage(err));
    } finally {
      setLoading(false);
    }
  }

  async function google() {
    setError('');setInfo('');setLoading(true);
    try {
      const fbUser = await window.fb.signInWithGoogle();
      onSuccess(fbUser.displayName || fbUser.email.split('@')[0]);
    } catch (err) {
      setError(window.fb.errorMessage(err));
    } finally {
      setLoading(false);
    }
  }

  async function reset() {
    if (!email) {setError('Enter your email above first.');return;}
    setError('');setInfo('');setResetting(true);
    // Debug mode: add ?debug=1 to the site URL to see the real channel + error,
    // even when not signed in (useful while configuring email delivery).
    const debug = window.__effAdminMode || /[?&]debug=1/.test(window.location.search);
    try {
      const r = await window.fb.resetPassword(email);
      if (r && r.ok) {
        let msg = `Reset link sent to ${email}. Check your inbox (and spam).`;
        if (debug) {
          if (r.channel === 'resend') msg += ' [via Resend ✓]';
          else if (r.channel === 'firebase') msg += ` [Resend FAILED → Firebase fallback. Reason: ${r.fnError || 'unknown'}]`;
        }
        setInfo(msg);
      } else {
        setError((r && (r.error || r.fnError)) || 'Could not send reset email.');
      }
    } catch (err) {
      setError(window.fb.errorMessage(err));
    } finally {
      setResetting(false);
    }
  }

  return (
    <Modal onClose={onClose}>
      <div className="text-center mb-6"><Logo size={48} /></div>
      <h2 style={{ fontSize: 24, textAlign: 'center' }}>
        {mode === 'login' ? 'Welcome back' : 'Create your account'}
      </h2>
      <p className="text-muted text-sm text-center mt-2 mb-6">
        {mode === 'login' ? 'Sign in to access your dashboard' : 'Deploy your first EA in under 4 minutes'}
      </p>

      {/* Google sign-in */}
      <button className="btn btn-ghost btn-block btn-lg" onClick={google} disabled={loading} type="button">
        <svg width="18" height="18" viewBox="0 0 24 24" style={{ marginRight: 8 }}>
          <path fill="#4285F4" d="M22.5 12.3c0-.9-.1-1.7-.2-2.5H12v4.8h5.9c-.3 1.4-1 2.6-2.2 3.4v2.8h3.6c2.1-2 3.2-4.8 3.2-8.5z" />
          <path fill="#34A853" d="M12 23c2.9 0 5.4-1 7.2-2.6l-3.6-2.8c-1 .7-2.3 1.1-3.6 1.1-2.8 0-5.2-1.9-6-4.4H2.3v2.8C4.1 20.5 7.8 23 12 23z" />
          <path fill="#FBBC05" d="M6 13.3c-.2-.6-.3-1.2-.3-1.8 0-.6.1-1.2.3-1.8V6.9H2.3C1.6 8.3 1.2 10.1 1.2 12c0 1.9.4 3.7 1.1 5.1L6 13.3z" />
          <path fill="#EA4335" d="M12 5.4c1.6 0 3 .5 4.1 1.6l3-3C17.4 2.2 14.9 1 12 1 7.8 1 4.1 3.5 2.3 7.1L6 9.9c.8-2.5 3.2-4.5 6-4.5z" />
        </svg>
        Continue with Google
      </button>

      <div className="flex-center mt-4 gap-3">
        <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
        <span className="text-xs text-muted font-mono">OR</span>
        <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
      </div>

      <form className="mt-4" onSubmit={submit}>
        <div className="flex-col gap-4">
          {mode === 'signup' &&
          <div className="field">
              <label>USER NAME</label>
              <input className="input" placeholder="ALPHA_OPERATOR" value={name} onChange={(e) => setName(e.target.value)} />
            </div>
          }
          <div className="field">
            <label>Email</label>
            <input className="input" type="email" placeholder="operator@domain.com" required value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" />
          </div>
          <div className="field">
            <label>Password</label>
            <input className="input" type="password" placeholder="••••••••" required value={password} onChange={(e) => setPassword(e.target.value)} autoComplete={mode === 'signup' ? 'new-password' : 'current-password'} />
          </div>

          {error &&
          <div className="panel" style={{ padding: 10, background: 'rgba(255,59,92,0.08)', borderColor: 'rgba(255,59,92,0.3)' }}>
              <span className="text-red font-mono text-xs">⚠ {error}</span>
            </div>
          }
          {info &&
          <div className="panel" style={{ padding: 10, background: 'rgba(0,255,148,0.08)', borderColor: 'rgba(0,255,148,0.3)' }}>
              <span className="text-green font-mono text-xs">✓ {info}</span>
            </div>
          }

          <button className="btn btn-primary btn-lg btn-block btn-sheen mt-2" type="submit" disabled={loading}>
            {loading ?
            <span className="typing"><span /><span /><span /></span> :
            mode === 'login' ? 'Sign In →' : 'Create Account →'}
          </button>

          {mode === 'login' &&
          <a className="text-xs text-cyan text-center" style={{ cursor: 'pointer' }} onClick={reset}>
              {resetting ? 'Sending...' : 'Forgot password?'}
            </a>
          }
        </div>
      </form>

      <div className="text-center mt-6 text-sm text-muted">
        {mode === 'login' ? "Don't have an account? " : 'Already have an account? '}
        <a className="text-cyan" style={{ cursor: 'pointer' }} onClick={() => onSwitch(mode === 'login' ? 'signup' : 'login')}>
          {mode === 'login' ? 'Sign up' : 'Sign in'}
        </a>
      </div>
    </Modal>);

}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);