'use client';

import { useState, useEffect } from 'react';

function IconArrowRight() {
  return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12h14M12 5l7 7-7 7" /></svg>;
}
function IconGoogle() {
  return <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>;
}
function IconMicrosoft() {
  return <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><rect x="1" y="1" width="10" height="10" fill="#f25022"/><rect x="13" y="1" width="10" height="10" fill="#7fba00"/><rect x="1" y="13" width="10" height="10" fill="#00a4ef"/><rect x="13" y="13" width="10" height="10" fill="#ffb900"/></svg>;
}

const inputStyle = {
  width: '100%', padding: '13px 14px', borderRadius: 14,
  border: '1px solid rgba(232,232,229,.18)', background: 'rgba(255,255,255,.06)',
  color: '#E8E8E5', outline: 'none', fontSize: 14,
};
// Button visuals live in globals.css (.login-btn / --ghost / --inline) so they can
// carry hover + disabled states. Marketing-matched: solid Mars red primary, Mars
// outline secondary, uppercase mono labels, crisp corners.

export default function LoginClient({ authMode, nextPath = '/', errorCode = '', forceSupabase = false, initialView = '' }) {
  const isLocalServer = authMode === 'local';
  const safeNext = typeof nextPath === 'string' && nextPath.startsWith('/') ? nextPath : '/';

  // Personal (this device / local) vs Team (org via Supabase). Default to the
  // path that matches how the server is already running, but the user can switch.
  const defaultView = initialView === 'personal' || initialView === 'team'
    ? initialView
    : (isLocalServer && !forceSupabase ? 'personal' : 'team');
  const [view, setView] = useState(defaultView);

  const [mode, setMode] = useState('password');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState(errorCode ? 'Supabase could not complete sign-in. Try again.' : '');

  // Runtime auth config (mode + Supabase URL/anon key) is UI-driven and lives
  // server-side, so fetch it instead of reading build-time NEXT_PUBLIC_* vars.
  const [cfg, setCfg] = useState(null);
  const [resetting, setResetting] = useState(false);
  const [resetOpen, setResetOpen] = useState(false);
  const [recoveryToken, setRecoveryToken] = useState('');

  // "Join with a link" + inline "Create a team" (fresh-install team setup).
  const [inviteLink, setInviteLink] = useState('');
  const [ct, setCt] = useState({ url: '', anonKey: '', serviceKey: '' });
  const [ctBusy, setCtBusy] = useState('');

  useEffect(() => {
    let alive = true;
    fetch('/api/auth/config', { cache: 'no-store' })
      .then((r) => r.json())
      .then((d) => { if (alive) setCfg(d); })
      .catch(() => { if (alive) setCfg({ authMode, supabaseConfigured: false }); });
    return () => { alive = false; };
  }, [authMode]);

  const supabaseConfigured = Boolean(cfg?.supabaseUrl && cfg?.supabaseAnonKey);
  // Show the sign-in form when the server runs in supabase mode, the user asked
  // for it (?supabase=1), or Supabase has been configured (incl. just now via
  // the inline Create-a-team form).
  const showSignIn = !isLocalServer || forceSupabase || supabaseConfigured;

  async function resetToLocal() {
    if (!recoveryToken.trim()) { setMessage('Enter the recovery token to switch.'); return; }
    setResetting(true);
    setMessage('');
    try {
      const res = await fetch('/api/auth/config', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ action: 'save', mode: 'local', recoveryToken: recoveryToken.trim() }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) { window.location.assign('/'); return; }
      setResetting(false);
      setMessage(res.status === 403 ? 'Invalid recovery token.' : 'Could not switch to personal mode.');
    } catch {
      setResetting(false);
      setMessage('Could not switch to personal mode.');
    }
  }

  function joinWithLink(e) {
    e.preventDefault();
    const raw = inviteLink.trim();
    if (!raw) { setMessage('Paste your invite link first.'); return; }
    // Accept a full invite link (…/join#invite=<blob>) or a bare blob. The /join
    // page reads the #invite fragment and runs the bootstrap → sign-in → join
    // chain, so we just hand it the blob.
    const marker = '#invite=';
    const idx = raw.indexOf(marker);
    let blob = idx >= 0 ? raw.slice(idx + marker.length) : raw;
    blob = blob.split(/[?&\s]/)[0];
    if (!blob) { setMessage('That invite link looks incomplete.'); return; }
    window.location.href = `/join#invite=${blob}`;
  }

  async function createTeam(e) {
    e.preventDefault();
    setCtBusy('save');
    setMessage('');
    try {
      const res = await fetch('/api/auth/config', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          action: 'save', mode: 'supabase',
          url: ct.url.trim(), anonKey: ct.anonKey.trim(), serviceKey: ct.serviceKey.trim(),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        throw new Error(data.error === 'connection_failed'
          ? 'Could not connect to that Supabase project. Check the URL and keys.'
          : (data.error || 'Could not save team settings.'));
      }
      // Now configured + in supabase mode. Reflect it locally so the sign-in
      // form renders, then prompt sign-in (first sign-in becomes the owner).
      setCfg((c) => ({
        ...(c || {}), authMode: 'supabase', supabaseConfigured: true,
        supabaseUrl: ct.url.trim(), supabaseAnonKey: ct.anonKey.trim(),
      }));
      setMessage('Team created. Sign in to finish — your first sign-in makes you the owner.');
    } catch (err) {
      setMessage(err?.message || 'Could not create the team.');
    } finally {
      setCtBusy('');
    }
  }

  async function testTeam() {
    setCtBusy('test');
    setMessage('');
    try {
      const res = await fetch('/api/auth/config', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ action: 'test', url: ct.url.trim(), anonKey: ct.anonKey.trim() }),
      });
      const data = await res.json().catch(() => ({}));
      setMessage(data.ok ? 'Connection OK. Create the team to continue.' : 'Connection failed. Check the URL and anon key.');
    } catch {
      setMessage('Connection test failed.');
    } finally {
      setCtBusy('');
    }
  }

  async function supabaseClient() {
    const { createBrowserClient } = await import('@supabase/ssr');
    const url = cfg?.supabaseUrl;
    const anonKey = cfg?.supabaseAnonKey;
    if (!url || !anonKey) throw new Error('Supabase is not configured. Create a team or set it in Settings → Account.');
    return createBrowserClient(url, anonKey);
  }

  async function signIn(e) {
    e.preventDefault();
    setLoading(true); setMessage('');
    try {
      const supabase = await supabaseClient();
      const redirectTo = `${window.location.origin}/api/auth/callback?next=${encodeURIComponent(safeNext)}`;
      const result = mode === 'magic'
        ? await supabase.auth.signInWithOtp({ email, options: { emailRedirectTo: redirectTo } })
        : await supabase.auth.signInWithPassword({ email, password });
      if (result.error) throw result.error;
      if (mode === 'magic') setMessage(`Secure sign-in link sent to ${email}.`);
      else window.location.assign(safeNext);
    } catch (err) {
      setMessage(err?.message || 'Sign-in failed.');
    } finally {
      setLoading(false);
    }
  }

  async function sso(provider) {
    setLoading(true); setMessage('');
    try {
      const supabase = await supabaseClient();
      const { error } = await supabase.auth.signInWithOAuth({ provider, options: { redirectTo: `${window.location.origin}/api/auth/callback?next=${encodeURIComponent(safeNext)}` } });
      if (error) throw error;
    } catch (err) {
      setMessage(err?.message || 'SSO failed.');
      setLoading(false);
    }
  }

  // ── View renderers ──────────────────────────────────────────────────────────

  function renderPersonal() {
    // Fresh / local server → the operator landing.
    if (isLocalServer && !supabaseConfigured) {
      return (
        <>
          <div className="login-card-head"><p>This device</p><h2>Personal mode</h2></div>
          <p className="login-footnote" style={{ marginTop: 0 }}>
            You're the local owner — no account needed. Work stays on this machine and sharing uses the local signed-link registry.
          </p>
          {message ? <div className="login-message">{message}</div> : null}
          <a className="login-link-button" href={safeNext} style={{ margin: '20px 0 0' }}>Enter dashboard <IconArrowRight /></a>
          <button type="button" className="login-link-button login-link-button--ghost" style={{ margin: '12px 0 0', cursor: 'pointer' }} onClick={() => { setMessage(''); setView('team'); }}>
            Create or join a team <IconArrowRight />
          </button>
          <p className="login-footnote" style={{ textAlign: 'center' }}>Collaborate with others through a shared Supabase organization.</p>
        </>
      );
    }
    // Server is in team mode → switching to personal is gated by the recovery token.
    return (
      <>
        <div className="login-card-head"><p>This device</p><h2>Use it personally</h2></div>
        <div className="login-message login-message--warn">
          This server runs in <b>team mode</b>. Switching to personal (local) mode turns off organization sign-in for everyone on this server, so it needs the on-disk recovery token.
        </div>
        {message ? <div className="login-message">{message}</div> : null}
        {resetOpen ? (
          <div className="login-form">
            <label>Recovery token
              <input style={inputStyle} type="text" value={recoveryToken} onChange={(e) => setRecoveryToken(e.target.value)} placeholder="paste recovery token" autoComplete="off" />
            </label>
            <span className="login-footnote" style={{ marginTop: 0 }}>Found in <code>data/.auth-recovery-token</code> on the server machine.</span>
            <button type="button" className="login-btn" disabled={resetting} onClick={resetToLocal}>
              {resetting ? 'Switching…' : 'Switch to personal mode'}
            </button>
          </div>
        ) : (
          <button type="button" className="login-link-button login-link-button--ghost" style={{ cursor: 'pointer' }} onClick={() => setResetOpen(true)}>
            Switch to personal mode <IconArrowRight />
          </button>
        )}
      </>
    );
  }

  function renderSignIn() {
    return (
      <>
        {isLocalServer ? (
          <div className="login-message login-message--warn">
            Server is in <b>local mode</b>. You can sign in to test, but sessions persist only after switching to team mode in <a href="/settings/account">Settings → Account</a>.
          </div>
        ) : null}
        <div className="login-mode-toggle" role="tablist" aria-label="Sign-in method">
          <button type="button" className={mode === 'password' ? 'active' : ''} onClick={() => setMode('password')}>Password</button>
          <button type="button" className={mode === 'magic' ? 'active' : ''} onClick={() => setMode('magic')}>Magic link</button>
        </div>
        <form onSubmit={signIn} className="login-form">
          <label>Email<input style={inputStyle} type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" autoComplete="email" required /></label>
          {mode === 'password' ? <label>Password<input style={inputStyle} type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" autoComplete="current-password" required /></label> : null}
          <button type="submit" className="login-btn" disabled={loading}>{loading ? 'Working...' : mode === 'password' ? 'Sign in' : 'Send magic link'} {!loading ? <IconArrowRight /> : null}</button>
        </form>
        {(process.env.NEXT_PUBLIC_GOOGLE_SSO_ENABLED === 'true' || process.env.NEXT_PUBLIC_MICROSOFT_SSO_ENABLED === 'true') ? (
          <div className="login-sso">
            <span>or continue with</span>
            {process.env.NEXT_PUBLIC_GOOGLE_SSO_ENABLED === 'true' ? <button type="button" onClick={() => sso('google')} className="login-btn login-btn--ghost"><IconGoogle /> Google</button> : null}
            {process.env.NEXT_PUBLIC_MICROSOFT_SSO_ENABLED === 'true' ? <button type="button" onClick={() => sso('azure')} className="login-btn login-btn--ghost"><IconMicrosoft /> Microsoft</button> : null}
          </div>
        ) : null}
      </>
    );
  }

  function renderCreateTeam() {
    return (
      <form className="login-form login-create-team" onSubmit={createTeam}>
        <p className="login-footnote" style={{ marginTop: 0 }}>
          Connect a Supabase project to host your team. Your first sign-in becomes the owner. Keys are stored encrypted on this server, never in the browser.
        </p>
        <label>Supabase URL<input style={inputStyle} type="url" value={ct.url} onChange={(e) => setCt((s) => ({ ...s, url: e.target.value }))} placeholder="https://xxxx.supabase.co" autoComplete="off" required /></label>
        <label>Anon key<input style={inputStyle} type="text" value={ct.anonKey} onChange={(e) => setCt((s) => ({ ...s, anonKey: e.target.value }))} placeholder="eyJ…" autoComplete="off" required /></label>
        <label>Service-role key<input style={inputStyle} type="password" value={ct.serviceKey} onChange={(e) => setCt((s) => ({ ...s, serviceKey: e.target.value }))} placeholder="eyJ… (kept server-side)" autoComplete="off" required /></label>
        <div className="login-create-actions">
          <button type="button" className="login-btn login-btn--ghost login-btn--inline" disabled={Boolean(ctBusy)} onClick={testTeam}>{ctBusy === 'test' ? 'Testing…' : 'Test'}</button>
          <button type="submit" className="login-btn" disabled={Boolean(ctBusy)}>{ctBusy === 'save' ? 'Creating…' : 'Create team'} {!ctBusy ? <IconArrowRight /> : null}</button>
        </div>
      </form>
    );
  }

  function renderTeam() {
    return (
      <>
        <div className="login-card-head"><p>Secure access</p><h2>{showSignIn ? 'Sign in to your team' : 'Set up your team'}</h2></div>
        {message ? <div className="login-message">{message}</div> : null}
        {showSignIn ? renderSignIn() : renderCreateTeam()}

        <div className="login-join">
          <span className="login-join-label">Have an invite link?</span>
          <form className="login-join-row" onSubmit={joinWithLink}>
            <input style={inputStyle} type="text" value={inviteLink} onChange={(e) => setInviteLink(e.target.value)} placeholder="paste invite link" autoComplete="off" />
            <button type="submit" className="login-btn login-btn--ghost login-btn--inline">Join</button>
          </form>
        </div>

        {showSignIn ? (
          <p className="login-footnote">Supabase stores identity. madarX OS stores local runtime state, artifact ACLs, and share-link audit events.</p>
        ) : null}
      </>
    );
  }

  return (
    <main className="login-page-shell">
      <section className="login-hero-panel" aria-label="madarX OS landing">
        <div className="login-orbit" aria-hidden="true">
          <svg viewBox="0 0 700 700" width="700" height="700">
            <g className="login-orbit-spin">
              <circle cx="350" cy="350" r="320" stroke="#E8E8E5" strokeWidth="1" fill="none" opacity=".10" />
              <circle cx="350" cy="350" r="240" stroke="#E8E8E5" strokeWidth="1" fill="none" opacity=".08" />
            </g>
            <g className="login-orbit-spin login-orbit-spin--rev">
              <circle cx="350" cy="350" r="160" stroke="#C2452A" strokeWidth="1.2" fill="none" opacity=".30" />
              <circle cx="350" cy="350" r="80" stroke="#E8E8E5" strokeWidth=".8" fill="none" opacity=".06" />
            </g>
            <g className="login-orbit-bead">
              <circle cx="350" cy="190" r="3.5" fill="#C2452A" />
            </g>
            <g className="login-orbit-bead login-orbit-bead--outer">
              <circle cx="350" cy="30" r="2.5" fill="#E8E8E5" opacity=".5" />
            </g>
          </svg>
        </div>
        <div className="login-brand-lockup">
          <svg className="login-mark" width="40" height="40" viewBox="0 0 100 100" aria-hidden="true">
            <path className="lm-arc" d="M 85.32 31.22 A 40 40 0 1 1 78.78 22.20" stroke="#E8E8E5" strokeWidth="2.4" fill="none" strokeLinecap="round" />
            <line className="lm-x1" x1="21.72" y1="21.72" x2="78.28" y2="78.28" stroke="#E8E8E5" strokeWidth="2.4" strokeLinecap="round" />
            <line className="lm-x2" x1="21.72" y1="78.28" x2="78.28" y2="21.72" stroke="#E8E8E5" strokeWidth="2.4" strokeLinecap="round" />
            <circle className="lm-bead" cx="82.36" cy="26.49" r="3" fill="#C2452A" />
          </svg>
          <div className="login-wordmark">madar<span>X</span> OS</div>
        </div>
        <p className="login-kicker">Core operating layer</p>
        <h1>AI does the work. You hold the controls.</h1>
        <p className="login-lede">madarX OS is the operating layer for AI-run operations. Agents draft, plan, and execute &mdash; every consequential action waits for a human, and nothing happens off the record.</p>
        <div className="login-proof-grid">
          <div><b>Human in the loop</b><span>Agents propose. People approve. The HAIL methodology, built in.</span></div>
          <div><b>One operating logic</b><span>Workflows, governance, and orchestration in a single layer.</span></div>
          <div><b>Every action logged</b><span>Nothing is inferred. Creation, access, and approval are recorded.</span></div>
        </div>
      </section>
      <section className="login-card" aria-label="Sign in">
        <div className="login-seg" role="tablist" aria-label="Account type">
          <button type="button" role="tab" aria-selected={view === 'personal'} className={view === 'personal' ? 'active' : ''} onClick={() => setView('personal')}>Personal</button>
          <button type="button" role="tab" aria-selected={view === 'team'} className={view === 'team' ? 'active' : ''} onClick={() => setView('team')}>Team</button>
        </div>
        {view === 'personal' ? renderPersonal() : renderTeam()}
      </section>
    </main>
  );
}
